diff --git a/packages/0x.js/.npmignore b/packages/0x.js/.npmignore deleted file mode 100644 index 3dd5d05240..0000000000 --- a/packages/0x.js/.npmignore +++ /dev/null @@ -1,10 +0,0 @@ -# Blacklist all files -.* -* -# Whitelist lib -!lib/**/* -# Blacklist tests and publish scripts -/lib/test/* -/lib/monorepo_scripts/ -# Package specific ignore -!_bundles/**/* diff --git a/packages/0x.js/CHANGELOG.json b/packages/0x.js/CHANGELOG.json deleted file mode 100644 index dfb4b90a2d..0000000000 --- a/packages/0x.js/CHANGELOG.json +++ /dev/null @@ -1,1894 +0,0 @@ -[ - { - "version": "9.2.0", - "changes": [ - { - "note": "Export `GethCallOverrides` type", - "pr": 2620 - }, - { - "note": "Export `ExchangeProxyMetaTransaction` and `SignedExchangeProxyMetaTransaction`", - "pr": 2610 - } - ], - "timestamp": 1594788383 - }, - { - "timestamp": 1592969527, - "version": "9.1.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1583220306, - "version": "9.1.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1582837861, - "version": "9.1.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1582677073, - "version": "9.1.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1582623685, - "version": "9.1.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1581748629, - "version": "9.1.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "9.1.0", - "changes": [ - { - "note": "Export `EvmBytecodeOutputLinkReferences`", - "pr": 2462 - } - ], - "timestamp": 1581204851 - }, - { - "timestamp": 1580988106, - "version": "9.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1580811564, - "version": "9.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1579744659, - "version": "9.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "9.0.4", - "changes": [ - { - "note": "Update exports.", - "pr": 2432 - } - ], - "timestamp": 1579682890 - }, - { - "timestamp": 1578272714, - "version": "9.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1576540892, - "version": "9.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1575931811, - "version": "9.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "9.0.0", - "changes": [ - { - "note": "Remove ZRXToken contract wrapper", - "pr": 2324 - }, - { - "note": "ContractWrappers no longer exposes `erc20Proxy`, `erc721Proxy` and `dutchAuction` wrappers", - "pr": 2324 - }, - { - "note": "[Breaking] Big refactor of contract wrapper interface. See https://github.com/0xProject/0x-monorepo/pull/2325 for details", - "pr": 2325 - }, - { - "note": "Remove IWallet and IValidator contract wrappers", - "pr": 2337 - }, - { - "note": "Remove exports orderHashUtils and transactionHashUtils", - "pr": 2321 - }, - { - "note": "Update BigNumber version to ~9.0.0", - "pr": 2342 - }, - { - "note": "Exported intefaces changed: from getContractAddressesForNetworkOrThrow to getContractAddressesForChainOrThrow, from NetworkId to ChainId, from ContractNetworks to ContractChains, and from ContractNetworkData to ContractChainData.", - "pr": 2313 - }, - { - "note": "Updated to work with 0x v3" - } - ], - "timestamp": 1575296764 - }, - { - "version": "8.0.0-beta.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1575290197 - }, - { - "version": "8.0.0-beta.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1574238768 - }, - { - "version": "8.0.0-beta.1", - "changes": [ - { - "note": "Remove ZRXToken contract wrapper", - "pr": 2324 - }, - { - "note": "ContractWrappers no longer exposes `erc20Proxy`, `erc721Proxy` and `dutchAuction` wrappers", - "pr": 2324 - }, - { - "note": "[Breaking] Big refactor of contract wrapper interface. See https://github.com/0xProject/0x-monorepo/pull/2325 for details", - "pr": 2325 - }, - { - "note": "Remove IWallet and IValidator contract wrappers", - "pr": 2337 - }, - { - "note": "Remove exports orderHashUtils and transactionHashUtils", - "pr": 2321 - }, - { - "note": "Update BigNumber version to ~9.0.0", - "pr": 2342 - } - ], - "timestamp": 1574030254 - }, - { - "version": "8.0.0-beta.0", - "changes": [ - { - "note": "Exported intefaces changed: from getContractAddressesForNetworkOrThrow to getContractAddressesForChainOrThrow, from NetworkId to ChainId, from ContractNetworks to ContractChains, and from ContractNetworkData to ContractChainData.", - "pr": 2313 - } - ], - "timestamp": 1573159180 - }, - { - "version": "7.1.0-beta.0", - "changes": [ - { - "note": "Updated to work with 0x v3" - } - ], - "timestamp": 1570135330 - }, - { - "timestamp": 1568744790, - "version": "7.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1567521715, - "version": "7.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "7.0.0", - "changes": [ - { - "note": "Add optional `exchangeAddress` parameter to `signatureUtils.isValidSignatureAsync` to fix `Validator` type signatures.", - "pr": 2017 - }, - { - "note": "Removed @0x/order-watcher" - }, - { - "note": "Update to latest @0x/contract-wrappers v11", - "pr": 2068 - } - ], - "timestamp": 1566446343 - }, - { - "timestamp": 1565296576, - "version": "6.0.15", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1564604963, - "version": "6.0.14", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "6.0.13", - "changes": [ - { - "note": "re-export new ethereum-types type, TupleDataItem", - "pr": 1919 - } - ], - "timestamp": 1563957393 - }, - { - "timestamp": 1563193019, - "version": "6.0.12", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563047529, - "version": "6.0.11", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563006338, - "version": "6.0.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1557961111, - "version": "6.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1557799313, - "version": "6.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1557507213, - "version": "6.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "6.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1554997931 - }, - { - "timestamp": 1553183790, - "version": "6.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1553091633, - "version": "6.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551479279, - "version": "6.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551299797, - "version": "6.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551220833, - "version": "6.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "6.0.0", - "changes": [ - { - "note": "Add support for EIP1193 providers & Web3.js providers >= 1.0-beta.38", - "pr": 1627 - }, - { - "note": "Update provider params to type SupportedProvider which outlines all supported providers", - "pr": 1627 - } - ], - "timestamp": 1551130135 - }, - { - "version": "5.0.0", - "changes": [ - { - "note": "Export `transactionHashUtils`, `DecodedCalldata`, `ZeroExTransaction`, and `SignedZeroExTransaction`", - "pr": 1569 - } - ], - "timestamp": 1549733923 - }, - { - "version": "4.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1549547375 - }, - { - "timestamp": 1549504360, - "version": "4.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1549452781, - "version": "4.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "4.0.0", - "changes": [ - { - "note": "Upgrade the bignumber.js to v8.0.2", - "pr": 1517 - } - ], - "timestamp": 1549373905 - }, - { - "timestamp": 1547747677, - "version": "3.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547561734, - "version": "3.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547225310, - "version": "3.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.0.0", - "changes": [ - { - "note": "Export `MultiAssetData`, `MultiAssetDataWithRecursiveDecoding`, `ObjectMap`, and `SingleAssetData` from types. No longer export `AssetData`.", - "pr": 1363 - } - ], - "timestamp": 1547040760 - }, - { - "version": "2.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544739608 - }, - { - "version": "2.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544570656 - }, - { - "timestamp": 1543401373, - "version": "2.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542821676, - "version": "2.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542208198, - "version": "2.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542134075, - "version": "2.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542028948, - "version": "2.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1541740904 - }, - { - "version": "2.0.0", - "changes": [ - { - "note": "Add support for `eth_signTypedData`.", - "pr": 1102 - }, - { - "note": "Added `MetamaskSubprovider` to handle inconsistencies in Metamask's signing JSON RPC endpoints.", - "pr": 1102 - }, - { - "note": "Removed `SignerType` (including `SignerType.Metamask`). Please use the `MetamaskSubprovider` to wrap `web3.currentProvider`.", - "pr": 1102 - }, - { - "note": "Updated to use new modularized artifacts and the latest version of @0xproject/contract-wrappers", - "pr": 1105 - }, - { - "note": "Make web3-provider-engine types a 'dependency' so it's available to users of the library", - "pr": 1105 - }, - { - "note": "Export new `AssetData` type from types", - "pr": 1131 - } - ], - "timestamp": 1539871071 - }, - { - "version": "1.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1538693146 - }, - { - "timestamp": 1538157789, - "version": "1.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537907159, - "version": "1.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537875740, - "version": "1.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537541580, - "version": "1.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.3", - "changes": [ - { - "note": "Drastically reduce the bundle size by removing unused parts of included contract artifacts." - } - ], - "timestamp": 1537369748 - }, - { - "version": "1.0.2", - "changes": [ - { - "note": "Add ZRX & WETH mainnet contract addresses into the included artifacts" - } - ], - "timestamp": 1537265493 - }, - { - "timestamp": 1536142250, - "version": "1.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.1-rc.6", - "changes": [ - { - "note": "Fix missing `BlockParamLiteral` type import issue" - } - ], - "timestamp": 1535377027 - }, - { - "version": "1.0.1-rc.5", - "changes": [ - { - "note": "Fix `main` and `types` package.json entries so that they point to the new location of index.d.ts and index.js" - } - ] - }, - { - "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 - } - ], - "timestamp": 1535133899 - }, - { - "version": "1.0.1-rc.3", - "changes": [ - { - "note": "Dependencies updated" - }, - { - "pr": 914, - "note": "Update ecSignOrderHashAsync to return the signature as a string for immediate use in contracts" - } - ], - "timestamp": 1534210131 - }, - { - "version": "1.0.1-rc.2", - "changes": [ - { - "note": "Fixed bug caused by importing non-existent dep" - } - ], - "timestamp": 1532619515 - }, - { - "version": "1.0.1-rc.1", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1532605697 - }, - { - "timestamp": 1532357734, - "version": "1.0.0", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532043100, - "version": "1.0.0-rc.2", - "changes": [ - { - "note": "Remove `zeroEx.assetData` and instead re-export it's static functions directly off `ZeroEx`" - } - ] - }, - { - "timestamp": 1532043000, - "version": "1.0.0-rc.1", - "changes": [ - { - "note": "Remove tokenRegistry wrapper", - "pr": 863 - }, - { - "note": "Rename `zeroEx.token` to `zeroEx.erc20Token`, and add `zeroEx.erc721Token`", - "pr": 863 - }, - { - "note": "Rename `zeroEx.proxy` to `zeroEx.erc20Proxy` and add `zeroEx.erc721Proxy`", - "pr": 863 - }, - { - "note": "Refactored `ZeroEx.isValidSignature` to `zeroEx.isValidSignatureAsync`. It is now async so that it can verify contract-dependent signature types", - "pr": 863 - }, - { - "note": "Refactored `signOrderHashAsync` to `ecSignOrderHashAsync`. There are now many non-ECSignature ways to sign orders too.", - "pr": 863 - }, - { - "note": "Removed `createOrderWatcherAsync` method. Will be added back once OrderWatcher is refactored for V2", - "pr": 863 - }, - { - "note": "0x.js exports renamed contract events and event arg types", - "pr": 863 - }, - { - "note": "Export `ZeroEx.assetData` with methods to decode/encode assetData fields found in 0x orders", - "pr": 884 - } - ] - }, - { - "timestamp": 1531919263, - "version": "0.38.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1531149657, - "version": "0.38.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1529397769, - "version": "0.38.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1527617805, - "version": "0.38.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1527617227, - "version": "0.38.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1527616612, - "version": "0.38.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.38.0", - "changes": [ - { - "note": "Renamed createOrderStateWatcher to createOrderWatcherAsync since it is now async", - "pr": 579 - }, - { - "note": "Renamed ZeroExError to ContractWrappersErrors since they now lives in the @0xproject/contract-wrappers subpackage", - "pr": 579 - } - ], - "timestamp": 1527008270 - }, - { - "timestamp": 1525477860, - "version": "0.37.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1525453812, - "version": "0.37.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.37.0", - "changes": [ - { - "note": "Fixed expiration watcher comparator to handle orders with equal expiration times", - "pr": 526 - }, - { - "note": "Update Web3 Provider Engine to 14.0.4", - "pr": 555 - }, - { - "note": "Add `zeroEx.getProvider()`", - "pr": 559 - }, - { - "note": "Move `ZeroExError.InvalidSignature` to `@0xproject/order-utils` `OrderError.InvalidSignature`", - "pr": 559 - } - ], - "timestamp": 1525428773 - }, - { - "version": "0.36.3", - "changes": [ - { - "note": "Move @0xproject/migrations to devDependencies" - } - ], - "timestamp": 1524079658 - }, - { - "timestamp": 1524073495, - "version": "0.36.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.36.1", - "changes": [ - { - "note": "Internal changes and refactoring" - }, - { - "note": "Fix redundant expired order removal bug", - "pr": 527 - } - ], - "timestamp": 1524044013 - }, - { - "version": "0.36.0", - "changes": [ - { - "note": "Moved Web3.Provider to `@0xproject/types:Provider`", - "pr": 501 - }, - { - "note": "Add `zeroEx.exchange.getOrderStateAsync` to allow obtaining current OrderState for a signedOrder", - "pr": 510 - } - ], - "timestamp": 1523462196 - }, - { - "version": "0.35.0", - "changes": [ - { - "note": "Removed `ZeroExError.TransactionMiningTimeout` and moved it to '@0xproject/web3-wrapper' `Web3WrapperErrors.TransactionMiningTimeout`", - "pr": 485 - } - ], - "timestamp": 1522673609 - }, - { - "version": "0.34.0", - "changes": [ - { - "note": "Fix the bug causing `zeroEx.exchange.fillOrdersUpToAsync` validation to fail if there were some extra orders passed", - "pr": 470 - }, - { - "note": "Remove automatic instantiation of `zeroEx.orderStateWatcher`", - "pr": 488 - }, - { - "note": "Add `zeroEx.createOrderStateWatcher` to allow creating arbitrary number of OrderStateWatchers", - "pr": 488 - }, - { - "note": "Added `stateLayer` setting to `OrderStateWatcherConfig` so OrderStateWatcher can be set to monitor different blockchain state layers", - "pr": 488 - } - ], - "timestamp": 1522658513 - }, - { - "version": "0.33.2", - "changes": [ - { - "note": "Consolidate all `console.log` calls into `logUtils` in the `@0xproject/utils` package", - "pr": 452 - }, - { - "note": "Consolidate `Order`, `SignedOrder`, and `ECSignature` into the `@0xproject/types` package", - "pr": 456 - } - ], - "timestamp": 1521298800 - }, - { - "version": "0.33.1", - "changes": [ - { - "note": "Add missing EthersJs typescript typings as dependency" - } - ], - "timestamp": 1520434800 - }, - { - "version": "0.33.0", - "changes": [ - { - "note": "Validate and lowercase all addresses in public methods", - "pr": 373 - }, - { - "note": "Improve validation to force passing contract addresses on private networks", - "pr": 385 - }, - { - "note": "Change `LogErrorContractEventArgs.errorId` type from `BigNumber` to `number`", - "pr": 413 - }, - { - "note": "Rename all public `_unsubscribeAll` methods to `unsubscribeAll`", - "pr": 415 - }, - { - "note": "Move web3 typings from devDep to dep since cannot use this package without it", - "pr": 429 - } - ], - "timestamp": 1520089200 - }, - { - "version": "0.32.2", - "changes": [ - { - "note": "Fix publishing issue where .npmignore was not properly excluding undesired content", - "pr": 389 - } - ], - "timestamp": 1518102000 - }, - { - "version": "0.32.1", - "changes": [ - { - "note": "Reorganized `BlockParamLiteral` export into `@0xproject/types` package", - "pr": 355 - }, - { - "note": "Now using `abi-gen` package to generate ContractEventArgs types", - "pr": 371 - } - ], - "timestamp": 1517929200 - }, - { - "version": "0.32.0", - "changes": [ - { - "note": "Add `zeroEx.etherToken.getContractAddressIfExists`", - "pr": 350 - }, - { - "note": "Fixed the bug causing order watcher to throw if there is an event with the same signature but different indexed fields", - "pr": 366 - } - ], - "timestamp": 1517756400 - }, - { - "version": "0.31.1", - "changes": [ - { - "note": "Fix the bug causing order watcher to throw if makerToken === zrx", - "pr": 357 - } - ], - "timestamp": 1517410800 - }, - { - "version": "0.31.0", - "changes": [ - { - "note": "Add the `shouldAddPersonalMessagePrefix` parameter to `signOrderHashAsync` so that the caller can decide on whether to add the personalMessage prefix before relaying the request to the signer. Parity Signer, Ledger and TestRPC add the prefix themselves, Metamask expects it to have already been added.", - "pr": 349 - } - ], - "timestamp": 1517238000 - }, - { - "version": "0.30.2", - "changes": [ - { - "note": "Add Rinkeby testnet addresses to artifacts ", - "pr": 337 - }, - { - "note": "Move @0xproject/types to dependencies from devDependencies fixing missing type errors" - } - ], - "timestamp": 1517151600 - }, - { - "version": "0.30.1", - "changes": [ - { - "note": "Fix a bug allowing negative fill values ", - "pr": 212 - }, - { - "note": "Fix a bug that made it impossible to pass a custom ZRX address ", - "pr": 341 - } - ], - "timestamp": 1516719600 - }, - { - "version": "0.30.0", - "changes": [ - { - "note": "Add an error parameter to the order watcher callback", - "pr": 312 - }, - { - "note": "Fix a bug making it impossible to catch some errors from awaitTransactionMinedAsync", - "pr": 312 - }, - { - "note": "Fix a bug in fillOrdersUpTo validation making it impossible to fill up to if user doesn't have enough balance to fully fill all the orders", - "pr": 321 - } - ], - "timestamp": 1516114800 - }, - { - "version": "0.29.1", - "changes": [ - { - "note": "Fixed bignumber config issue #301", - "pr": 305 - } - ], - "timestamp": 1515596400 - }, - { - "version": "0.29.0", - "changes": [ - { - "note": "Assert baseUnit amount supplied to `toUnitAmount` is integer amount.", - "pr": 287 - }, - { - "note": "`toBaseUnitAmount` throws if amount supplied has too many decimals", - "pr": 287 - } - ], - "timestamp": 1514386800 - }, - { - "version": "0.28.0", - "changes": [ - { - "note": "Add `etherTokenAddress` arg to `depositAsync` and `withdrawAsync` methods on `zeroEx.etherToken`", - "pr": 267 - }, - { - "note": "Removed accidentally included `unsubscribeAll` method from `zeroEx.proxy`, `zeroEx.etherToken` and `zeroEx.tokenRegistry`", - "pr": 267 - }, - { - "note": "Removed `etherTokenContractAddress` from `ZeroEx` constructor arg `ZeroExConfig`", - "pr": 267 - }, - { - "note": "Rename `SubscriptionOpts` to `BlockRange`", - "pr": 272 - }, - { - "note": "Add `zeroEx.etherToken.subscribe`, `zeroEx.etherToken.unsubscribe`, `zeroEx.etherToken.unsubscribeAll`", - "pr": 277 - }, - { - "note": "Add `zeroEx.etherToken.getLogsAsync`", - "pr": 277 - }, - { - "note": "Add new public types `BlockParamLiteral`, `EtherTokenEvents`, `EtherTokenContractEventArgs`, `DepositContractEventArgs`, `WithdrawalContractEventArgs`", - "pr": 277 - }, - { - "note": "Support `Deposit` and `Withdraw` events on etherToken", - "pr": 277 - }, - { - "note": "Improve the error message when taker is not a string", - "pr": 278 - } - ], - "timestamp": 1513695600 - }, - { - "version": "0.27.1", - "changes": [ - { - "note": "Export `TransactionOpts` type" - } - ], - "timestamp": 1511794800 - }, - { - "version": "0.27.0", - "changes": [ - { - "note": "Make `ZeroExConfig` required parameter of `ZeroEx` constructor", - "pr": 233 - }, - { - "note": "Add a required property `networkId` to `ZeroExConfig`", - "pr": 233 - }, - { - "note": "Make all `getContractAddress` functions, `zeroEx.exchange.subscribe`, `zeroEx.exchange.getZRXTokenAddress` sync", - "pr": 233 - }, - { - "note": "Remove `ZeroExError.ContractNotFound` and replace it with contract-specific errors", - "pr": 233 - }, - { - "note": "Make `DecodedLogEvent` contain `LogWithDecodedArgs` under log key instead of merging it in like web3 does", - "pr": 234 - }, - { - "note": "Rename `removed` to `isRemoved` in `DecodedLogEvent`", - "pr": 234 - }, - { - "note": "Add config allowing to specify gasPrice and gasLimit for every transaction sending method", - "pr": 235 - }, - { - "note": "All transaction sending methods now call `estimateGas` if no gas amount was supplied", - "pr": 235 - }, - { - "note": "Modify order validation methods to validate against the `latest` block, not against the `pending` block", - "pr": 236 - } - ], - "timestamp": 1511794800 - }, - { - "version": "0.26.0", - "changes": [ - { - "note": "Add post-formatter for logs converting `blockNumber`, `logIndex`, `transactionIndex` from hexes to numbers", - "pr": 231 - }, - { - "note": "Remove support for Async callback types when used in Subscribe functions", - "pr": 222 - }, - { - "note": "In OrderWatcher subscribe to ZRX Token Transfer and Approval events when maker token is different", - "pr": 225 - } - ], - "timestamp": 1511190000 - }, - { - "version": "0.25.1", - "changes": [ - { - "note": "Standardise on Cancelled over Canceled", - "pr": 217 - }, - { - "note": "Add missing `DecodedLogEvent` type to exported types", - "pr": 205 - }, - { - "note": "Normalized the transactionReceipt status to be `null|0|1`, 1 meaning transaction execution successful, 0 unsuccessful and `null` if it is a pre-byzantinium transaction.", - "pr": 200 - } - ], - "timestamp": 1510498800 - }, - { - "version": "0.23.0", - "changes": [ - { - "note": "Fixed unhandled promise rejection error in subscribe methods", - "pr": 209 - }, - { - "note": "Subscribe callbacks now receive an error object as their first argument" - } - ], - "timestamp": 1510412400 - }, - { - "version": "0.22.6", - "changes": [ - { - "note": "Add a timeout parameter to transaction awaiting", - "pr": 206 - } - ], - "timestamp": 1510239600 - }, - { - "version": "0.22.5", - "changes": [ - { - "note": "Re-publish v0.22.4 to fix publishing issue" - } - ], - "timestamp": 1509980400 - }, - { - "version": "0.22.4", - "changes": [ - { - "note": "Upgraded bignumber.js to a new version that ships with native typings" - } - ], - "timestamp": 1508857200 - }, - { - "version": "0.22.3", - "changes": [ - { - "note": "Fixed an issue with new version of testrpc and unlimited proxy allowance", - "pr": 199 - } - ], - "timestamp": 1508857200 - }, - { - "version": "0.22.2", - "changes": [ - { - "note": "Fixed rounding of maker fill amount and incorrect validation of partial fees", - "pr": 197 - } - ], - "timestamp": 1508770800 - }, - { - "version": "0.22.0", - "changes": [ - { - "note": "Started using `OrderFillRequest` interface instead of `OrderFillOrKillRequest` interface for `zeroEx.exchange.batchFillOrKill`", - "pr": 187 - }, - { - "note": "Removed `OrderFillOrKillRequest`", - "pr": 187 - } - ], - "timestamp": 1508079600 - }, - { - "version": "0.21.4", - "changes": [ - { - "note": "Made 0x.js more type-safe by making `getLogsAsync` and `subscribe/subscribeAsync` generics parametrized with arg type", - "pr": 194 - } - ], - "timestamp": 1507820400 - }, - { - "version": "0.21.3", - "changes": [ - { - "note": "Fixed a bug causing order fills to throw `INSUFFICIENT_TAKER_ALLOWANCE`", - "pr": 193 - } - ], - "timestamp": 1507734000 - }, - { - "version": "0.21.2", - "changes": [ - { - "note": "Exported `ContractEventArg` as a public type", - "pr": 190 - } - ], - "timestamp": 1507647600 - }, - { - "version": "0.21.1", - "changes": [ - { - "note": "Fixed a bug in subscriptions", - "pr": 189 - } - ], - "timestamp": 1507647600 - }, - { - "version": "0.21.0", - "changes": [ - { - "note": "Complete rewrite of subscription logic", - "pr": 182 - }, - { - "note": "Subscriptions no longer return historical logs. If you want them - use `getLogsAsync`" - }, - { - "note": "Subscriptions now use [ethereumjs-blockstream](https://github.com/ethereumjs/ethereumjs-blockstream) under the hood" - }, - { - "note": "Subscriptions correctly handle block re-orgs (forks)" - }, - { - "note": "Subscriptions correctly backfill logs (connection problems)" - }, - { - "note": "They no longer setup filters on the underlying nodes, so you can use them with infura without a filter Subprovider" - }, - { - "note": "Removed `ContractEventEmitter` and added `LogEvent`" - }, - { - "note": "Renamed `zeroEx.token.subscribeAsync` to `zeroEx.token.subscribe`" - }, - { - "note": "Added `zeroEx.token.unsubscribe` and `zeroEx.exchange.unsubscribe`" - }, - { - "note": "Renamed `zeroEx.exchange.stopWatchingAllEventsAsync` to `zeroEx.exhange.unsubscribeAll`" - }, - { - "note": "Renamed `zeroEx.token.stopWatchingAllEventsAsync` to `zeroEx.token.unsubscribeAll`" - }, - { - "note": "Fixed the batch fills validation by emulating all balance & proxy allowance changes", - "pr": 185 - } - ], - "timestamp": 1507561200 - }, - { - "version": "0.20.0", - "changes": [ - { - "note": "Add `zeroEx.token.getLogsAsync`", - "pr": 178 - }, - { - "note": "Add `zeroEx.exchange.getLogsAsync`", - "pr": 178 - }, - { - "note": "Fixed fees validation when one of the tokens transferred is ZRX", - "pr": 181 - } - ], - "timestamp": 1507129200 - }, - { - "version": "0.19.0", - "changes": [ - { - "note": "Made order validation optional ", - "pr": 172 - }, - { - "note": "Added Ropsten testnet support", - "pr": 173 - }, - { - "note": "Fixed a bug causing awaitTransactionMinedAsync to DDos backend nodes", - "pr": 175 - } - ], - "timestamp": 1506610800 - }, - { - "version": "0.18.0", - "changes": [ - { - "note": "Added `zeroEx.exchange.validateOrderFillableOrThrowAsync` to simplify orderbook pruning", - "pr": 170 - } - ], - "timestamp": 1506351600 - }, - { - "version": "0.17.0", - "changes": [ - { - "note": "Made `zeroEx.exchange.getZRXTokenAddressAsync` public", - "pr": 171 - } - ], - "timestamp": 1506351600 - }, - { - "version": "0.16.0", - "changes": [ - { - "note": "Added the ability to specify custom contract addresses to be used with 0x.js", - "pr": 165 - }, - { - "note": "ZeroExConfig.exchangeContractAddress" - }, - { - "note": "ZeroExConfig.tokenRegistryContractAddress" - }, - { - "note": "ZeroExConfig.etherTokenContractAddress" - }, - { - "note": "Added `zeroEx.tokenRegistry.getContractAddressAsync`", - "pr": 165 - } - ], - "timestamp": 1505833200 - }, - { - "version": "0.15.0", - "changes": [ - { - "note": "Added the ability to specify a historical `blockNumber` at which to query the blockchain's state when calling a token or exchange method", - "pr": 161 - } - ], - "timestamp": 1504796400 - }, - { - "version": "0.14.2", - "changes": [ - { - "note": "Fixed an issue with bignumber.js types not found", - "pr": 160 - } - ], - "timestamp": 1504710000 - }, - { - "version": "0.14.1", - "changes": [ - { - "note": "Fixed an issue with Artifact type not found", - "pr": 159 - } - ], - "timestamp": 1504710000 - }, - { - "version": "0.14.0", - "changes": [ - { - "note": "Added `zeroEx.exchange.throwLogErrorsAsErrors` method to public interface", - "pr": 157 - }, - { - "note": "Fixed an issue with overlapping async intervals in `zeroEx.awaitTransactionMinedAsync`", - "pr": 157 - }, - { - "note": "Fixed an issue with log decoder returning `BigNumber`s as `strings`", - "pr": 157 - } - ], - "timestamp": 1504623600 - }, - { - "version": "0.13.0", - "changes": [ - { - "note": "Made all the functions submitting transactions to the network to immediately return transaction hash", - "pr": 151 - }, - { - "note": "Added `zeroEx.awaitTransactionMinedAsync`", - "pr": 151 - }, - { - "note": "Added `TransactionReceiptWithDecodedLogs`, `LogWithDecodedArgs`, `DecodedLogArgs` to public types", - "pr": 151 - }, - { - "note": "Added signature validation to `validateFillOrderThrowIfInvalidAsync`", - "pr": 152 - } - ], - "timestamp": 1504623600 - }, - { - "version": "0.12.1", - "changes": [ - { - "note": "Added the support for web3@1.x.x provider", - "pr": 142 - }, - { - "note": "Added the optional `zeroExConfig` parameter to the constructor of `ZeroEx`", - "pr": 139 - }, - { - "note": "Added the ability to specify `gasPrice` when instantiating `ZeroEx`", - "pr": 139 - } - ], - "timestamp": 1504278000 - }, - { - "version": "0.11.0", - "changes": [ - { - "note": "Added `zeroEx.token.setUnlimitedProxyAllowanceAsync`", - "pr": 137 - }, - { - "note": "Added `zeroEx.token.setUnlimitedAllowanceAsync`", - "pr": 137 - }, - { - "note": "Added `zeroEx.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS`", - "pr": 137 - } - ], - "timestamp": 1503500400 - }, - { - "version": "0.10.4", - "changes": [ - { - "note": "Fixed a bug where checksummed addresses were being pulled from artifacts and not lower-cased.", - "pr": 135 - } - ], - "timestamp": 1503500400 - }, - { - "version": "0.10.1", - "changes": [ - { - "note": "Added `zeroEx.exchange.validateFillOrderThrowIfInvalidAsync`", - "pr": 128 - }, - { - "note": "Added `zeroEx.exchange.validateFillOrKillOrderThrowIfInvalidAsync`", - "pr": 128 - }, - { - "note": "Added `zeroEx.exchange.validateCancelOrderThrowIfInvalidAsync`", - "pr": 128 - }, - { - "note": "Added `zeroEx.exchange.isRoundingErrorAsync`", - "pr": 128 - }, - { - "note": "Added `zeroEx.proxy.getContractAddressAsync`", - "pr": 130 - }, - { - "note": "Added `zeroEx.tokenRegistry.getTokenAddressesAsync`", - "pr": 132 - }, - { - "note": "Added `zeroEx.tokenRegistry.getTokenAddressBySymbolIfExistsAsync`", - "pr": 132 - }, - { - "note": "Added `zeroEx.tokenRegistry.getTokenAddressByNameIfExistsAsync`", - "pr": 132 - }, - { - "note": "Added `zeroEx.tokenRegistry.getTokenBySymbolIfExistsAsync`", - "pr": 132 - }, - { - "note": "Added `zeroEx.tokenRegistry.getTokenByNameIfExistsAsync`", - "pr": 132 - }, - { - "note": "Added clear error message when checksummed address is passed to a public method", - "pr": 124 - }, - { - "note": "Fixes the description of `shouldThrowOnInsufficientBalanceOrAllowance` in docs", - "pr": 127 - } - ], - "timestamp": 1503500400 - }, - { - "version": "0.9.3", - "changes": [ - { - "note": "Update contract artifacts to include latest Kovan and Mainnet deploys", - "pr": 118 - } - ], - "timestamp": 1503327600 - }, - { - "version": "0.9.2", - "changes": [ - { - "note": "*This version was unpublished because of a publishing issue.*" - }, - { - "note": "Update contract artifacts to include latest Kovan and Mainnet deploys", - "pr": 118 - } - ], - "timestamp": 1503241200 - }, - { - "version": "0.9.1", - "changes": [ - { - "note": "Fixed the bug causing `zeroEx.token.getBalanceAsync()` to fail if no addresses available", - "pr": 120 - } - ], - "timestamp": 1502809200 - }, - { - "version": "0.9.0", - "changes": [ - { - "note": "Migrated to the new version of smart contracts", - "pr": 101 - }, - { - "note": "Removed the ability to call methods on multiple authorized Exchange smart contracts", - "pr": 106 - }, - { - "note": "Made `zeroEx.getOrderHashHex` a static method", - "pr": 107 - }, - { - "note": "Cached `net_version` requests and invalidate the cache on calls to `setProvider`", - "pr": 95 - }, - { - "note": "Renamed `zeroEx.exchange.batchCancelOrderAsync` to `zeroEx.exchange.batchCancelOrdersAsync`" - }, - { - "note": "Renamed `zeroEx.exchange.batchFillOrderAsync` to `zeroEx.exchange.batchFillOrdersAsync`" - }, - { - "note": "Updated to typescript v2.4", - "pr": 104 - }, - { - "note": "Fixed an issue with incorrect balance/allowance validation when ZRX is one of the tokens traded", - "pr": 109 - } - ], - "timestamp": 1500994800 - }, - { - "version": "0.8.0", - "changes": [ - { - "note": "Added the ability to call methods on different authorized versions of the Exchange smart contract", - "pr": 82 - }, - { - "note": "Updated contract artifacts to reflect latest changes to the smart contracts (0xproject/contracts#59)" - }, - { - "note": "Added `zeroEx.proxy.isAuthorizedAsync` and `zeroEx.proxy.getAuthorizedAddressesAsync`", - "pr": 89 - }, - { - "note": "Added `zeroEx.token.subscribeAsync`", - "pr": 90 - }, - { - "note": "Made contract invalidation functions private", - "pr": 90 - }, - { - "note": "`zeroEx.token.invalidateContractInstancesAsync`" - }, - { - "note": "`zeroEx.exchange.invalidateContractInstancesAsync`" - }, - { - "note": "`zeroEx.proxy.invalidateContractInstance`" - }, - { - "note": "`zeroEx.tokenRegistry.invalidateContractInstance`" - }, - { - "note": "Fixed the bug where `zeroEx.setProviderAsync` didn't invalidate etherToken contract's instance" - } - ], - "timestamp": 1499094000 - }, - { - "version": "0.7.1", - "changes": [ - { - "note": "Added the ability to convert Ether to wrapped Ether tokens and back via `zeroEx.etherToken.depostAsync` and `zeroEx.etherToken.withdrawAsync`", - "pr": 81 - } - ], - "timestamp": 1498402800 - }, - { - "version": "0.7.0", - "changes": [ - { - "note": "Added Kovan smart contract artifacts", - "pr": 78 - }, - { - "note": "Started returning fillAmount from `fillOrderAsync` and `fillUpToAsync`", - "pr": 72 - }, - { - "note": "Started returning cancelledAmount from `cancelOrderAsync`", - "pr": 72 - }, - { - "note": "Renamed type `LogCancelArgs` to `LogCancelContractEventArgs` and `LogFillArgs` to `LogFillContractEventArgs`" - } - ], - "timestamp": 1498057200 - }, - { - "version": "0.6.2", - "changes": [ - { - "note": "Reduced bundle size" - }, - { - "note": "Improved documentation" - } - ], - "timestamp": 1497970800 - }, - { - "version": "0.6.1", - "changes": [ - { - "note": "Improved documentation" - } - ], - "timestamp": 1497798000 - }, - { - "version": "0.6.0", - "changes": [ - { - "note": "Made `ZeroEx` class accept `Web3Provider` instance instead of `Web3` instance" - }, - { - "note": "Added types for contract event arguments" - } - ], - "timestamp": 1497798000 - }, - { - "version": "0.5.2", - "changes": [ - { - "note": "Fixed the bug in `postpublish` script that caused that only unminified UMD bundle was uploaded to release page" - } - ], - "timestamp": 1497452400 - }, - { - "version": "0.5.1", - "changes": [ - { - "note": "Added `postpublish` script to publish to Github Releases with assets." - } - ], - "timestamp": 1497452400 - } -] diff --git a/packages/0x.js/CHANGELOG.md b/packages/0x.js/CHANGELOG.md deleted file mode 100644 index 79b1fc787e..0000000000 --- a/packages/0x.js/CHANGELOG.md +++ /dev/null @@ -1,727 +0,0 @@ - - -CHANGELOG - -## v9.2.0 - _July 15, 2020_ - - * Export `GethCallOverrides` type (#2620) - * Export `ExchangeProxyMetaTransaction` and `SignedExchangeProxyMetaTransaction` (#2610) - -## v9.1.6 - _June 24, 2020_ - - * Dependencies updated - -## v9.1.5 - _March 3, 2020_ - - * Dependencies updated - -## v9.1.4 - _February 27, 2020_ - - * Dependencies updated - -## v9.1.3 - _February 26, 2020_ - - * Dependencies updated - -## v9.1.2 - _February 25, 2020_ - - * Dependencies updated - -## v9.1.1 - _February 15, 2020_ - - * Dependencies updated - -## v9.1.0 - _February 8, 2020_ - - * Export `EvmBytecodeOutputLinkReferences` (#2462) - -## v9.0.7 - _February 6, 2020_ - - * Dependencies updated - -## v9.0.6 - _February 4, 2020_ - - * Dependencies updated - -## v9.0.5 - _January 23, 2020_ - - * Dependencies updated - -## v9.0.4 - _January 22, 2020_ - - * Update exports. (#2432) - -## v9.0.3 - _January 6, 2020_ - - * Dependencies updated - -## v9.0.2 - _December 17, 2019_ - - * Dependencies updated - -## v9.0.1 - _December 9, 2019_ - - * Dependencies updated - -## v9.0.0 - _December 2, 2019_ - - * Remove ZRXToken contract wrapper (#2324) - * ContractWrappers no longer exposes `erc20Proxy`, `erc721Proxy` and `dutchAuction` wrappers (#2324) - * [Breaking] Big refactor of contract wrapper interface. See https://github.com/0xProject/0x-monorepo/pull/2325 for details (#2325) - * Remove IWallet and IValidator contract wrappers (#2337) - * Remove exports orderHashUtils and transactionHashUtils (#2321) - * Update BigNumber version to ~9.0.0 (#2342) - * Exported intefaces changed: from getContractAddressesForNetworkOrThrow to getContractAddressesForChainOrThrow, from NetworkId to ChainId, from ContractNetworks to ContractChains, and from ContractNetworkData to ContractChainData. (#2313) - * Updated to work with 0x v3 - -## v8.0.0-beta.3 - _December 2, 2019_ - - * Dependencies updated - -## v8.0.0-beta.2 - _November 20, 2019_ - - * Dependencies updated - -## v8.0.0-beta.1 - _November 17, 2019_ - - * Remove ZRXToken contract wrapper (#2324) - * ContractWrappers no longer exposes `erc20Proxy`, `erc721Proxy` and `dutchAuction` wrappers (#2324) - * [Breaking] Big refactor of contract wrapper interface. See https://github.com/0xProject/0x-monorepo/pull/2325 for details (#2325) - * Remove IWallet and IValidator contract wrappers (#2337) - * Remove exports orderHashUtils and transactionHashUtils (#2321) - * Update BigNumber version to ~9.0.0 (#2342) - -## v8.0.0-beta.0 - _November 7, 2019_ - - * Exported intefaces changed: from getContractAddressesForNetworkOrThrow to getContractAddressesForChainOrThrow, from NetworkId to ChainId, from ContractNetworks to ContractChains, and from ContractNetworkData to ContractChainData. (#2313) - -## v7.1.0-beta.0 - _October 3, 2019_ - - * Updated to work with 0x v3 - -## v7.0.2 - _September 17, 2019_ - - * Dependencies updated - -## v7.0.1 - _September 3, 2019_ - - * Dependencies updated - -## v7.0.0 - _August 22, 2019_ - - * Add optional `exchangeAddress` parameter to `signatureUtils.isValidSignatureAsync` to fix `Validator` type signatures. (#2017) - * Removed @0x/order-watcher - * Update to latest @0x/contract-wrappers v11 (#2068) - -## v6.0.15 - _August 8, 2019_ - - * Dependencies updated - -## v6.0.14 - _July 31, 2019_ - - * Dependencies updated - -## v6.0.13 - _July 24, 2019_ - - * re-export new ethereum-types type, TupleDataItem (#1919) - -## v6.0.12 - _July 15, 2019_ - - * Dependencies updated - -## v6.0.11 - _July 13, 2019_ - - * Dependencies updated - -## v6.0.10 - _July 13, 2019_ - - * Dependencies updated - -## v6.0.9 - _May 15, 2019_ - - * Dependencies updated - -## v6.0.8 - _May 14, 2019_ - - * Dependencies updated - -## v6.0.7 - _May 10, 2019_ - - * Dependencies updated - -## v6.0.6 - _April 11, 2019_ - - * Dependencies updated - -## v6.0.5 - _March 21, 2019_ - - * Dependencies updated - -## v6.0.4 - _March 20, 2019_ - - * Dependencies updated - -## v6.0.3 - _March 1, 2019_ - - * Dependencies updated - -## v6.0.2 - _February 27, 2019_ - - * Dependencies updated - -## v6.0.1 - _February 26, 2019_ - - * Dependencies updated - -## v6.0.0 - _February 25, 2019_ - - * Add support for EIP1193 providers & Web3.js providers >= 1.0-beta.38 (#1627) - * Update provider params to type SupportedProvider which outlines all supported providers (#1627) - -## v5.0.0 - _February 9, 2019_ - - * Export `transactionHashUtils`, `DecodedCalldata`, `ZeroExTransaction`, and `SignedZeroExTransaction` (#1569) - -## v4.0.3 - _February 7, 2019_ - - * Dependencies updated - -## v4.0.2 - _February 7, 2019_ - - * Dependencies updated - -## v4.0.1 - _February 6, 2019_ - - * Dependencies updated - -## v4.0.0 - _February 5, 2019_ - - * Upgrade the bignumber.js to v8.0.2 (#1517) - -## v3.0.3 - _January 17, 2019_ - - * Dependencies updated - -## v3.0.2 - _January 15, 2019_ - - * Dependencies updated - -## v3.0.1 - _January 11, 2019_ - - * Dependencies updated - -## v3.0.0 - _January 9, 2019_ - - * Export `MultiAssetData`, `MultiAssetDataWithRecursiveDecoding`, `ObjectMap`, and `SingleAssetData` from types. No longer export `AssetData`. (#1363) - -## v2.0.8 - _December 13, 2018_ - - * Dependencies updated - -## v2.0.7 - _December 11, 2018_ - - * Dependencies updated - -## v2.0.6 - _November 28, 2018_ - - * Dependencies updated - -## v2.0.5 - _November 21, 2018_ - - * Dependencies updated - -## v2.0.4 - _November 14, 2018_ - - * Dependencies updated - -## v2.0.3 - _November 13, 2018_ - - * Dependencies updated - -## v2.0.2 - _November 12, 2018_ - - * Dependencies updated - -## v2.0.1 - _November 9, 2018_ - - * Dependencies updated - -## v2.0.0 - _October 18, 2018_ - - * Add support for `eth_signTypedData`. (#1102) - * Added `MetamaskSubprovider` to handle inconsistencies in Metamask's signing JSON RPC endpoints. (#1102) - * Removed `SignerType` (including `SignerType.Metamask`). Please use the `MetamaskSubprovider` to wrap `web3.currentProvider`. (#1102) - * Updated to use new modularized artifacts and the latest version of @0xproject/contract-wrappers (#1105) - * Make web3-provider-engine types a 'dependency' so it's available to users of the library (#1105) - * Export new `AssetData` type from types (#1131) - -## v1.0.8 - _October 4, 2018_ - - * Dependencies updated - -## v1.0.7 - _September 28, 2018_ - - * Dependencies updated - -## v1.0.6 - _September 25, 2018_ - - * Dependencies updated - -## v1.0.5 - _September 25, 2018_ - - * Dependencies updated - -## v1.0.4 - _September 21, 2018_ - - * Dependencies updated - -## v1.0.3 - _September 19, 2018_ - - * Drastically reduce the bundle size by removing unused parts of included contract artifacts. - -## v1.0.2 - _September 18, 2018_ - - * Add ZRX & WETH mainnet contract addresses into the included artifacts - -## v1.0.1 - _September 5, 2018_ - - * Dependencies updated - -## v1.0.1-rc.6 - _August 27, 2018_ - - * Fix missing `BlockParamLiteral` type import issue - -## v1.0.1-rc.5 - _Invalid date_ - - * Fix `main` and `types` package.json entries so that they point to the new location of index.d.ts and index.js - -## v1.0.1-rc.4 - _August 24, 2018_ - - * 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` (#963) - -## v1.0.1-rc.3 - _August 14, 2018_ - - * Dependencies updated - * Update ecSignOrderHashAsync to return the signature as a string for immediate use in contracts (#914) - -## v1.0.1-rc.2 - _July 26, 2018_ - - * Fixed bug caused by importing non-existent dep - -## v1.0.1-rc.1 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.0 - _July 23, 2018_ - - * Dependencies updated - -## v1.0.0-rc.2 - _July 19, 2018_ - - * Remove `zeroEx.assetData` and instead re-export it's static functions directly off `ZeroEx` - -## v1.0.0-rc.1 - _July 19, 2018_ - - * Remove tokenRegistry wrapper (#863) - * Rename `zeroEx.token` to `zeroEx.erc20Token`, and add `zeroEx.erc721Token` (#863) - * Rename `zeroEx.proxy` to `zeroEx.erc20Proxy` and add `zeroEx.erc721Proxy` (#863) - * Refactored `ZeroEx.isValidSignature` to `zeroEx.isValidSignatureAsync`. It is now async so that it can verify contract-dependent signature types (#863) - * Refactored `signOrderHashAsync` to `ecSignOrderHashAsync`. There are now many non-ECSignature ways to sign orders too. (#863) - * Removed `createOrderWatcherAsync` method. Will be added back once OrderWatcher is refactored for V2 (#863) - * 0x.js exports renamed contract events and event arg types (#863) - * Export `ZeroEx.assetData` with methods to decode/encode assetData fields found in 0x orders (#884) - -## v0.38.6 - _July 18, 2018_ - - * Dependencies updated - -## v0.38.5 - _July 9, 2018_ - - * Dependencies updated - -## v0.38.4 - _June 19, 2018_ - - * Dependencies updated - -## v0.38.3 - _May 29, 2018_ - - * Dependencies updated - -## v0.38.2 - _May 29, 2018_ - - * Dependencies updated - -## v0.38.1 - _May 29, 2018_ - - * Dependencies updated - -## v0.38.0 - _May 22, 2018_ - - * Renamed createOrderStateWatcher to createOrderWatcherAsync since it is now async (#579) - * Renamed ZeroExError to ContractWrappersErrors since they now lives in the @0xproject/contract-wrappers subpackage (#579) - -## v0.37.2 - _May 4, 2018_ - - * Dependencies updated - -## v0.37.1 - _May 4, 2018_ - - * Dependencies updated - -## v0.37.0 - _May 4, 2018_ - - * Fixed expiration watcher comparator to handle orders with equal expiration times (#526) - * Update Web3 Provider Engine to 14.0.4 (#555) - * Add `zeroEx.getProvider()` (#559) - * Move `ZeroExError.InvalidSignature` to `@0xproject/order-utils` `OrderError.InvalidSignature` (#559) - -## v0.36.3 - _April 18, 2018_ - - * Move @0xproject/migrations to devDependencies - -## v0.36.2 - _April 18, 2018_ - - * Dependencies updated - -## v0.36.1 - _April 18, 2018_ - - * Internal changes and refactoring - * Fix redundant expired order removal bug (#527) - -## v0.36.0 - _April 11, 2018_ - - * Moved Web3.Provider to `@0xproject/types:Provider` (#501) - * Add `zeroEx.exchange.getOrderStateAsync` to allow obtaining current OrderState for a signedOrder (#510) - -## v0.35.0 - _April 2, 2018_ - - * Removed `ZeroExError.TransactionMiningTimeout` and moved it to '@0xproject/web3-wrapper' `Web3WrapperErrors.TransactionMiningTimeout` (#485) - -## v0.34.0 - _April 2, 2018_ - - * Fix the bug causing `zeroEx.exchange.fillOrdersUpToAsync` validation to fail if there were some extra orders passed (#470) - * Remove automatic instantiation of `zeroEx.orderStateWatcher` (#488) - * Add `zeroEx.createOrderStateWatcher` to allow creating arbitrary number of OrderStateWatchers (#488) - * Added `stateLayer` setting to `OrderStateWatcherConfig` so OrderStateWatcher can be set to monitor different blockchain state layers (#488) - -## v0.33.2 - _March 17, 2018_ - - * Consolidate all `console.log` calls into `logUtils` in the `@0xproject/utils` package (#452) - * Consolidate `Order`, `SignedOrder`, and `ECSignature` into the `@0xproject/types` package (#456) - -## v0.33.1 - _March 7, 2018_ - - * Add missing EthersJs typescript typings as dependency - -## v0.33.0 - _March 3, 2018_ - - * Validate and lowercase all addresses in public methods (#373) - * Improve validation to force passing contract addresses on private networks (#385) - * Change `LogErrorContractEventArgs.errorId` type from `BigNumber` to `number` (#413) - * Rename all public `_unsubscribeAll` methods to `unsubscribeAll` (#415) - * Move web3 typings from devDep to dep since cannot use this package without it (#429) - -## v0.32.2 - _February 8, 2018_ - - * Fix publishing issue where .npmignore was not properly excluding undesired content (#389) - -## v0.32.1 - _February 6, 2018_ - - * Reorganized `BlockParamLiteral` export into `@0xproject/types` package (#355) - * Now using `abi-gen` package to generate ContractEventArgs types (#371) - -## v0.32.0 - _February 4, 2018_ - - * Add `zeroEx.etherToken.getContractAddressIfExists` (#350) - * Fixed the bug causing order watcher to throw if there is an event with the same signature but different indexed fields (#366) - -## v0.31.1 - _January 31, 2018_ - - * Fix the bug causing order watcher to throw if makerToken === zrx (#357) - -## v0.31.0 - _January 29, 2018_ - - * Add the `shouldAddPersonalMessagePrefix` parameter to `signOrderHashAsync` so that the caller can decide on whether to add the personalMessage prefix before relaying the request to the signer. Parity Signer, Ledger and TestRPC add the prefix themselves, Metamask expects it to have already been added. (#349) - -## v0.30.2 - _January 28, 2018_ - - * Add Rinkeby testnet addresses to artifacts (#337) - * Move @0xproject/types to dependencies from devDependencies fixing missing type errors - -## v0.30.1 - _January 23, 2018_ - - * Fix a bug allowing negative fill values (#212) - * Fix a bug that made it impossible to pass a custom ZRX address (#341) - -## v0.30.0 - _January 16, 2018_ - - * Add an error parameter to the order watcher callback (#312) - * Fix a bug making it impossible to catch some errors from awaitTransactionMinedAsync (#312) - * Fix a bug in fillOrdersUpTo validation making it impossible to fill up to if user doesn't have enough balance to fully fill all the orders (#321) - -## v0.29.1 - _January 10, 2018_ - - * Fixed bignumber config issue #301 (#305) - -## v0.29.0 - _December 27, 2017_ - - * Assert baseUnit amount supplied to `toUnitAmount` is integer amount. (#287) - * `toBaseUnitAmount` throws if amount supplied has too many decimals (#287) - -## v0.28.0 - _December 19, 2017_ - - * Add `etherTokenAddress` arg to `depositAsync` and `withdrawAsync` methods on `zeroEx.etherToken` (#267) - * Removed accidentally included `unsubscribeAll` method from `zeroEx.proxy`, `zeroEx.etherToken` and `zeroEx.tokenRegistry` (#267) - * Removed `etherTokenContractAddress` from `ZeroEx` constructor arg `ZeroExConfig` (#267) - * Rename `SubscriptionOpts` to `BlockRange` (#272) - * Add `zeroEx.etherToken.subscribe`, `zeroEx.etherToken.unsubscribe`, `zeroEx.etherToken.unsubscribeAll` (#277) - * Add `zeroEx.etherToken.getLogsAsync` (#277) - * Add new public types `BlockParamLiteral`, `EtherTokenEvents`, `EtherTokenContractEventArgs`, `DepositContractEventArgs`, `WithdrawalContractEventArgs` (#277) - * Support `Deposit` and `Withdraw` events on etherToken (#277) - * Improve the error message when taker is not a string (#278) - -## v0.27.1 - _November 27, 2017_ - - * Export `TransactionOpts` type - -## v0.27.0 - _November 27, 2017_ - - * Make `ZeroExConfig` required parameter of `ZeroEx` constructor (#233) - * Add a required property `networkId` to `ZeroExConfig` (#233) - * Make all `getContractAddress` functions, `zeroEx.exchange.subscribe`, `zeroEx.exchange.getZRXTokenAddress` sync (#233) - * Remove `ZeroExError.ContractNotFound` and replace it with contract-specific errors (#233) - * Make `DecodedLogEvent` contain `LogWithDecodedArgs` under log key instead of merging it in like web3 does (#234) - * Rename `removed` to `isRemoved` in `DecodedLogEvent` (#234) - * Add config allowing to specify gasPrice and gasLimit for every transaction sending method (#235) - * All transaction sending methods now call `estimateGas` if no gas amount was supplied (#235) - * Modify order validation methods to validate against the `latest` block, not against the `pending` block (#236) - -## v0.26.0 - _November 20, 2017_ - - * Add post-formatter for logs converting `blockNumber`, `logIndex`, `transactionIndex` from hexes to numbers (#231) - * Remove support for Async callback types when used in Subscribe functions (#222) - * In OrderWatcher subscribe to ZRX Token Transfer and Approval events when maker token is different (#225) - -## v0.25.1 - _November 12, 2017_ - - * Standardise on Cancelled over Canceled (#217) - * Add missing `DecodedLogEvent` type to exported types (#205) - * Normalized the transactionReceipt status to be `null|0|1`, 1 meaning transaction execution successful, 0 unsuccessful and `null` if it is a pre-byzantinium transaction. (#200) - -## v0.23.0 - _November 11, 2017_ - - * Fixed unhandled promise rejection error in subscribe methods (#209) - * Subscribe callbacks now receive an error object as their first argument - -## v0.22.6 - _November 9, 2017_ - - * Add a timeout parameter to transaction awaiting (#206) - -## v0.22.5 - _November 6, 2017_ - - * Re-publish v0.22.4 to fix publishing issue - -## v0.22.4 - _October 24, 2017_ - - * Upgraded bignumber.js to a new version that ships with native typings - -## v0.22.3 - _October 24, 2017_ - - * Fixed an issue with new version of testrpc and unlimited proxy allowance (#199) - -## v0.22.2 - _October 23, 2017_ - - * Fixed rounding of maker fill amount and incorrect validation of partial fees (#197) - -## v0.22.0 - _October 15, 2017_ - - * Started using `OrderFillRequest` interface instead of `OrderFillOrKillRequest` interface for `zeroEx.exchange.batchFillOrKill` (#187) - * Removed `OrderFillOrKillRequest` (#187) - -## v0.21.4 - _October 12, 2017_ - - * Made 0x.js more type-safe by making `getLogsAsync` and `subscribe/subscribeAsync` generics parametrized with arg type (#194) - -## v0.21.3 - _October 11, 2017_ - - * Fixed a bug causing order fills to throw `INSUFFICIENT_TAKER_ALLOWANCE` (#193) - -## v0.21.2 - _October 10, 2017_ - - * Exported `ContractEventArg` as a public type (#190) - -## v0.21.1 - _October 10, 2017_ - - * Fixed a bug in subscriptions (#189) - -## v0.21.0 - _October 9, 2017_ - - * Complete rewrite of subscription logic (#182) - * Subscriptions no longer return historical logs. If you want them - use `getLogsAsync` - * Subscriptions now use [ethereumjs-blockstream](https://github.com/ethereumjs/ethereumjs-blockstream) under the hood - * Subscriptions correctly handle block re-orgs (forks) - * Subscriptions correctly backfill logs (connection problems) - * They no longer setup filters on the underlying nodes, so you can use them with infura without a filter Subprovider - * Removed `ContractEventEmitter` and added `LogEvent` - * Renamed `zeroEx.token.subscribeAsync` to `zeroEx.token.subscribe` - * Added `zeroEx.token.unsubscribe` and `zeroEx.exchange.unsubscribe` - * Renamed `zeroEx.exchange.stopWatchingAllEventsAsync` to `zeroEx.exhange.unsubscribeAll` - * Renamed `zeroEx.token.stopWatchingAllEventsAsync` to `zeroEx.token.unsubscribeAll` - * Fixed the batch fills validation by emulating all balance & proxy allowance changes (#185) - -## v0.20.0 - _October 4, 2017_ - - * Add `zeroEx.token.getLogsAsync` (#178) - * Add `zeroEx.exchange.getLogsAsync` (#178) - * Fixed fees validation when one of the tokens transferred is ZRX (#181) - -## v0.19.0 - _September 28, 2017_ - - * Made order validation optional (#172) - * Added Ropsten testnet support (#173) - * Fixed a bug causing awaitTransactionMinedAsync to DDos backend nodes (#175) - -## v0.18.0 - _September 25, 2017_ - - * Added `zeroEx.exchange.validateOrderFillableOrThrowAsync` to simplify orderbook pruning (#170) - -## v0.17.0 - _September 25, 2017_ - - * Made `zeroEx.exchange.getZRXTokenAddressAsync` public (#171) - -## v0.16.0 - _September 19, 2017_ - - * Added the ability to specify custom contract addresses to be used with 0x.js (#165) - * ZeroExConfig.exchangeContractAddress - * ZeroExConfig.tokenRegistryContractAddress - * ZeroExConfig.etherTokenContractAddress - * Added `zeroEx.tokenRegistry.getContractAddressAsync` (#165) - -## v0.15.0 - _September 7, 2017_ - - * Added the ability to specify a historical `blockNumber` at which to query the blockchain's state when calling a token or exchange method (#161) - -## v0.14.2 - _September 6, 2017_ - - * Fixed an issue with bignumber.js types not found (#160) - -## v0.14.1 - _September 6, 2017_ - - * Fixed an issue with Artifact type not found (#159) - -## v0.14.0 - _September 5, 2017_ - - * Added `zeroEx.exchange.throwLogErrorsAsErrors` method to public interface (#157) - * Fixed an issue with overlapping async intervals in `zeroEx.awaitTransactionMinedAsync` (#157) - * Fixed an issue with log decoder returning `BigNumber`s as `strings` (#157) - -## v0.13.0 - _September 5, 2017_ - - * Made all the functions submitting transactions to the network to immediately return transaction hash (#151) - * Added `zeroEx.awaitTransactionMinedAsync` (#151) - * Added `TransactionReceiptWithDecodedLogs`, `LogWithDecodedArgs`, `DecodedLogArgs` to public types (#151) - * Added signature validation to `validateFillOrderThrowIfInvalidAsync` (#152) - -## v0.12.1 - _September 1, 2017_ - - * Added the support for web3@1.x.x provider (#142) - * Added the optional `zeroExConfig` parameter to the constructor of `ZeroEx` (#139) - * Added the ability to specify `gasPrice` when instantiating `ZeroEx` (#139) - -## v0.11.0 - _August 23, 2017_ - - * Added `zeroEx.token.setUnlimitedProxyAllowanceAsync` (#137) - * Added `zeroEx.token.setUnlimitedAllowanceAsync` (#137) - * Added `zeroEx.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS` (#137) - -## v0.10.4 - _August 23, 2017_ - - * Fixed a bug where checksummed addresses were being pulled from artifacts and not lower-cased. (#135) - -## v0.10.1 - _August 23, 2017_ - - * Added `zeroEx.exchange.validateFillOrderThrowIfInvalidAsync` (#128) - * Added `zeroEx.exchange.validateFillOrKillOrderThrowIfInvalidAsync` (#128) - * Added `zeroEx.exchange.validateCancelOrderThrowIfInvalidAsync` (#128) - * Added `zeroEx.exchange.isRoundingErrorAsync` (#128) - * Added `zeroEx.proxy.getContractAddressAsync` (#130) - * Added `zeroEx.tokenRegistry.getTokenAddressesAsync` (#132) - * Added `zeroEx.tokenRegistry.getTokenAddressBySymbolIfExistsAsync` (#132) - * Added `zeroEx.tokenRegistry.getTokenAddressByNameIfExistsAsync` (#132) - * Added `zeroEx.tokenRegistry.getTokenBySymbolIfExistsAsync` (#132) - * Added `zeroEx.tokenRegistry.getTokenByNameIfExistsAsync` (#132) - * Added clear error message when checksummed address is passed to a public method (#124) - * Fixes the description of `shouldThrowOnInsufficientBalanceOrAllowance` in docs (#127) - -## v0.9.3 - _August 21, 2017_ - - * Update contract artifacts to include latest Kovan and Mainnet deploys (#118) - -## v0.9.2 - _August 20, 2017_ - - * *This version was unpublished because of a publishing issue.* - * Update contract artifacts to include latest Kovan and Mainnet deploys (#118) - -## v0.9.1 - _August 15, 2017_ - - * Fixed the bug causing `zeroEx.token.getBalanceAsync()` to fail if no addresses available (#120) - -## v0.9.0 - _July 25, 2017_ - - * Migrated to the new version of smart contracts (#101) - * Removed the ability to call methods on multiple authorized Exchange smart contracts (#106) - * Made `zeroEx.getOrderHashHex` a static method (#107) - * Cached `net_version` requests and invalidate the cache on calls to `setProvider` (#95) - * Renamed `zeroEx.exchange.batchCancelOrderAsync` to `zeroEx.exchange.batchCancelOrdersAsync` - * Renamed `zeroEx.exchange.batchFillOrderAsync` to `zeroEx.exchange.batchFillOrdersAsync` - * Updated to typescript v2.4 (#104) - * Fixed an issue with incorrect balance/allowance validation when ZRX is one of the tokens traded (#109) - -## v0.8.0 - _July 3, 2017_ - - * Added the ability to call methods on different authorized versions of the Exchange smart contract (#82) - * Updated contract artifacts to reflect latest changes to the smart contracts (0xproject/contracts#59) - * Added `zeroEx.proxy.isAuthorizedAsync` and `zeroEx.proxy.getAuthorizedAddressesAsync` (#89) - * Added `zeroEx.token.subscribeAsync` (#90) - * Made contract invalidation functions private (#90) - * `zeroEx.token.invalidateContractInstancesAsync` - * `zeroEx.exchange.invalidateContractInstancesAsync` - * `zeroEx.proxy.invalidateContractInstance` - * `zeroEx.tokenRegistry.invalidateContractInstance` - * Fixed the bug where `zeroEx.setProviderAsync` didn't invalidate etherToken contract's instance - -## v0.7.1 - _June 25, 2017_ - - * Added the ability to convert Ether to wrapped Ether tokens and back via `zeroEx.etherToken.depostAsync` and `zeroEx.etherToken.withdrawAsync` (#81) - -## v0.7.0 - _June 21, 2017_ - - * Added Kovan smart contract artifacts (#78) - * Started returning fillAmount from `fillOrderAsync` and `fillUpToAsync` (#72) - * Started returning cancelledAmount from `cancelOrderAsync` (#72) - * Renamed type `LogCancelArgs` to `LogCancelContractEventArgs` and `LogFillArgs` to `LogFillContractEventArgs` - -## v0.6.2 - _June 20, 2017_ - - * Reduced bundle size - * Improved documentation - -## v0.6.1 - _June 18, 2017_ - - * Improved documentation - -## v0.6.0 - _June 18, 2017_ - - * Made `ZeroEx` class accept `Web3Provider` instance instead of `Web3` instance - * Added types for contract event arguments - -## v0.5.2 - _June 14, 2017_ - - * Fixed the bug in `postpublish` script that caused that only unminified UMD bundle was uploaded to release page - -## v0.5.1 - _June 14, 2017_ - - * Added `postpublish` script to publish to Github Releases with assets. diff --git a/packages/0x.js/README.md b/packages/0x.js/README.md deleted file mode 100644 index ba3288b5d5..0000000000 --- a/packages/0x.js/README.md +++ /dev/null @@ -1,129 +0,0 @@ -## 0x.js - -A TypeScript/Javascript library for interacting with the 0x protocol. It is a high level package which combines a number of underlying packages such as order-utils and asset-data-utils. - -### Read the [Documentation](https://0x.org/docs/tools/0x.js). - -## Installation - -0x.js ships as both a [UMD](https://github.com/umdjs/umd) module and a [CommonJS](https://en.wikipedia.org/wiki/CommonJS) package. - -#### CommonJS _(recommended)_: - -**Install** - -```bash -npm install 0x.js --save -``` - -**Import** - -```javascript -import { - assetDataUtils, - BigNumber, - ContractWrappers, - generatePseudoRandomSalt, - orderHashUtils, - signatureUtils, -} from '0x.js'; -``` - -If your project is in [TypeScript](https://www.typescriptlang.org/), add the following to your `tsconfig.json`: - -```json -"compilerOptions": { - "typeRoots": ["node_modules/@0x/typescript-typings/types", "node_modules/@types"], -} -``` - -#### UMD: - -**Install** - -Download the UMD module from our [releases page](https://github.com/0xProject/0x-monorepo/releases) and add it to your project. - -**Import** - -```html - -``` - -#### Webpack config - -If bundling your project with [Webpack](https://webpack.js.org/), add the following to your `webpack.config.js`: - -If building for web: - -```js -node: { - fs: 'empty'; -} -``` - -If building a node library: - -```js -externals: { - fs: true; -} -``` - -`ContractWrappers` uses WebAssembly to simulate Ethereum calls. This toolchain involves generated 'glue' code that requires the `fs` built-in, but won't actually use it in a web environment. We tell Webpack not to resolve them since we won't need them. The specific dependency is [here](https://github.com/ethereumjs/rustbn.js/blob/master/lib/index.asm.js). - -Also see: - -- https://webpack.js.org/configuration/externals -- https://webpack.js.org/configuration/node - -## Contributing - -We strongly recommend that the community help us make improvements and determine the future direction of 0x protocol. To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install dependencies - -If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: - -```bash -yarn config set workspaces-experimental true -``` - -Then install dependencies - -```bash -yarn install -``` - -### Build - -To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory: - -```bash -PKG=0x.js yarn build -``` - -Or continuously rebuild on change: - -```bash -PKG=0x.js yarn watch -``` - -### Clean - -```bash -yarn clean -``` - -### Lint - -```bash -yarn lint -``` - -### Run Tests - -```bash -yarn test -``` diff --git a/packages/0x.js/coverage/.gitkeep b/packages/0x.js/coverage/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/0x.js/docs/reference.mdx b/packages/0x.js/docs/reference.mdx deleted file mode 100644 index f7135b9153..0000000000 --- a/packages/0x.js/docs/reference.mdx +++ /dev/null @@ -1,8998 +0,0 @@ - - -# Class: ERC20TokenContract - - -## Constructors - - - -\+ **new ERC20TokenContract**(`address`: string, `supportedProvider`: [SupportedProvider](#supportedprovider), `txDefaults?`: `Partial`, `logDecodeDependencies?`: undefined | object, `deployedBytecode`: string | undefined): *[ERC20TokenContract](#class-erc20tokencontract)* - -*Overrides void* - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:735](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L735)* - -**Parameters:** - -Name | Type | Default | ------- | ------ | ------ | -`address` | string | - | -`supportedProvider` | [SupportedProvider](#supportedprovider) | - | -`txDefaults?` | `Partial` | - | -`logDecodeDependencies?` | undefined \| object | - | -`deployedBytecode` | string \| undefined | ERC20TokenContract.deployedBytecode | - -**Returns:** *[ERC20TokenContract](#class-erc20tokencontract)* - -## Properties - -### `Optional` _deployedBytecodeIfExists - -• **_deployedBytecodeIfExists**? : *`Buffer`* - - - -Defined in base-contract/lib/src/index.d.ts:34 - -___ - -### abi - -• **abi**: *[ContractAbi](#contractabi)* - - - -Defined in base-contract/lib/src/index.d.ts:30 - -___ - -### address - -• **address**: *string* - - - -Defined in base-contract/lib/src/index.d.ts:31 - -___ - -Args - -• **constructorArgs**: *any[]* - - - -Defined in base-contract/lib/src/index.d.ts:33 - -___ - -### contractName - -• **contractName**: *string* - - - -Defined in base-contract/lib/src/index.d.ts:32 - -___ - -### `Static` contractName - -▪ **contractName**: *string* = "ERC20Token" - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:66](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L66)* - -## Methods - -### allowance - -▸ **allowance**(`_owner`: string, `_spender`: string): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:428](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L428)* - -**Parameters:** - -Name | Type | ------- | ------ | -`_owner` | string | -`_spender` | string | - -**Returns:** *`ContractFunctionObj`* - -___ - -### approve - -▸ **approve**(`_spender`: string, `_value`: `BigNumber`): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:456](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L456)* - -`msg.sender` approves `_spender` to spend `_value` tokens - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`_spender` | string | The address of the account able to transfer the tokens | -`_value` | `BigNumber` | The amount of wei to be approved for transfer | - -**Returns:** *`ContractTxFunctionObj`* - -Always true if the call has enough gas to complete execution - -___ - -### balanceOf - -▸ **balanceOf**(`_owner`: string): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:509](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L509)* - -Query the balance of owner - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`_owner` | string | The address from which the balance will be retrieved | - -**Returns:** *`ContractFunctionObj`* - -Balance of owner - -___ - -### getABIDecodedReturnData - -▸ **getABIDecodedReturnData**<**T**>(`methodName`: string, `callData`: string): *`T`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:413](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L413)* - -**Type parameters:** - -▪ **T** - -**Parameters:** - -Name | Type | ------- | ------ | -`methodName` | string | -`callData` | string | - -**Returns:** *`T`* - -___ - -### getABIDecodedTransactionData - -▸ **getABIDecodedTransactionData**<**T**>(`methodName`: string, `callData`: string): *`T`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:405](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L405)* - -**Type parameters:** - -▪ **T** - -**Parameters:** - -Name | Type | ------- | ------ | -`methodName` | string | -`callData` | string | - -**Returns:** *`T`* - -___ - -### getFunctionSignature - -▸ **getFunctionSignature**(`methodName`: string): *string* - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:398](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L398)* - -**Parameters:** - -Name | Type | ------- | ------ | -`methodName` | string | - -**Returns:** *string* - -___ - -### getLogsAsync - -▸ **getLogsAsync**<**ArgsType**>(`eventName`: [ERC20TokenEvents](#enumeration-erc20tokenevents), `blockRange`: `BlockRange`, `indexFilterValues`: `IndexedFilterValues`): *`Promise>>`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:719](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L719)* - -Gets historical logs without creating a subscription - -**Type parameters:** - -▪ **ArgsType**: *[ERC20TokenEventArgs](#erc20tokeneventargs)* - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`eventName` | [ERC20TokenEvents](#enumeration-erc20tokenevents) | The ERC20Token contract event you would like to subscribe to. | -`blockRange` | `BlockRange` | Block range to get logs from. | -`indexFilterValues` | `IndexedFilterValues` | An object where the keys are indexed args returned by the event and the value is the value you are interested in. E.g `{_from: aUserAddressHex}` | - -**Returns:** *`Promise>>`* - -Array of logs that match the parameters - -___ - -### getSelector - -▸ **getSelector**(`methodName`: string): *string* - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:421](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L421)* - -**Parameters:** - -Name | Type | ------- | ------ | -`methodName` | string | - -**Returns:** *string* - -___ - -### subscribe - -▸ **subscribe**<**ArgsType**>(`eventName`: [ERC20TokenEvents](#enumeration-erc20tokenevents), `indexFilterValues`: `IndexedFilterValues`, `callback`: [EventCallback](#eventcallback)‹*`ArgsType`*›, `isVerbose`: boolean, `blockPollingIntervalMs?`: undefined | number): *string* - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:674](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L674)* - -Subscribe to an event type emitted by the ERC20Token contract. - -**Type parameters:** - -▪ **ArgsType**: *[ERC20TokenEventArgs](#erc20tokeneventargs)* - -**Parameters:** - -Name | Type | Default | Description | ------- | ------ | ------ | ------ | -`eventName` | [ERC20TokenEvents](#enumeration-erc20tokenevents) | - | The ERC20Token contract event you would like to subscribe to. | -`indexFilterValues` | `IndexedFilterValues` | - | An object where the keys are indexed args returned by the event and the value is the value you are interested in. E.g `{maker: aUserAddressHex}` | -`callback` | [EventCallback](#eventcallback)‹*`ArgsType`*› | - | Callback that gets called when a log is added/removed | -`isVerbose` | boolean | false | Enable verbose subscription warnings (e.g recoverable network issues encountered) | -`blockPollingIntervalMs?` | undefined \| number | - | - | - -**Returns:** *string* - -Subscription token used later to unsubscribe - -___ - -### totalSupply - -▸ **totalSupply**(): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:534](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L534)* - -Query total supply of token - -**Returns:** *`ContractFunctionObj`* - -Total supply of token - -___ - -### transfer - -▸ **transfer**(`_to`: string, `_value`: `BigNumber`): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:560](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L560)* - -send `value` token to `to` from `msg.sender` - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`_to` | string | The address of the recipient | -`_value` | `BigNumber` | The amount of token to be transferred | - -**Returns:** *`ContractTxFunctionObj`* - -True if transfer was successful - -___ - -### transferFrom - -▸ **transferFrom**(`_from`: string, `_to`: string, `_value`: `BigNumber`): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:615](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L615)* - -send `value` token to `to` from `from` on the condition it is approved by `from` - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`_from` | string | The address of the sender | -`_to` | string | The address of the recipient | -`_value` | `BigNumber` | The amount of token to be transferred | - -**Returns:** *`ContractTxFunctionObj`* - -True if transfer was successful - -___ - -### unsubscribe - -▸ **unsubscribe**(`subscriptionToken`: string): *void* - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:700](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L700)* - -Cancel a subscription - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`subscriptionToken` | string | Subscription token returned by `subscribe()` | - -**Returns:** *void* - -___ - -### unsubscribeAll - -▸ **unsubscribeAll**(): *void* - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:707](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L707)* - -Cancels all existing subscriptions - -**Returns:** *void* - -___ - -### `Static` ABI - -▸ **ABI**(): *[ContractAbi](#contractabi)* - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:172](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L172)* - -**Returns:** *[ContractAbi](#contractabi)* - -The contract ABI - -___ - -### `Static` deployAsync - -▸ **deployAsync**(`bytecode`: string, `abi`: [ContractAbi](#contractabi), `supportedProvider`: [SupportedProvider](#supportedprovider), `txDefaults`: `Partial`, `logDecodeDependencies`: object): *`Promise`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:128](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L128)* - -**Parameters:** - -Name | Type | ------- | ------ | -`bytecode` | string | -`abi` | [ContractAbi](#contractabi) | -`supportedProvider` | [SupportedProvider](#supportedprovider) | -`txDefaults` | `Partial` | -`logDecodeDependencies` | object | - -**Returns:** *`Promise`* - -___ - -### `Static` deployFrom0xArtifactAsync - -▸ **deployFrom0xArtifactAsync**(`artifact`: `ContractArtifact` | `SimpleContractArtifact`, `supportedProvider`: [SupportedProvider](#supportedprovider), `txDefaults`: `Partial`, `logDecodeDependencies`: object): *`Promise`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:69](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L69)* - -**Parameters:** - -Name | Type | ------- | ------ | -`artifact` | `ContractArtifact` \| `SimpleContractArtifact` | -`supportedProvider` | [SupportedProvider](#supportedprovider) | -`txDefaults` | `Partial` | -`logDecodeDependencies` | object | - -**Returns:** *`Promise`* - -___ - -### `Static` deployWithLibrariesFrom0xArtifactAsync - -▸ **deployWithLibrariesFrom0xArtifactAsync**(`artifact`: `ContractArtifact`, `libraryArtifacts`: object, `supportedProvider`: [SupportedProvider](#supportedprovider), `txDefaults`: `Partial`, `logDecodeDependencies`: object): *`Promise`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:95](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L95)* - -**Parameters:** - -Name | Type | ------- | ------ | -`artifact` | `ContractArtifact` | -`libraryArtifacts` | object | -`supportedProvider` | [SupportedProvider](#supportedprovider) | -`txDefaults` | `Partial` | -`logDecodeDependencies` | object | - -**Returns:** *`Promise`* - -___ - -### `Static` strictArgumentEncodingCheck - -▸ **strictArgumentEncodingCheck**(`inputAbi`: `DataItem`[], `args`: any[]): *string* - - - -Defined in base-contract/lib/src/index.d.ts:44 - -**Parameters:** - -Name | Type | ------- | ------ | -`inputAbi` | `DataItem`[] | -`args` | any[] | - -**Returns:** *string* - -
- -# Class: ERC721TokenContract - - -## Constructors - - - -\+ **new ERC721TokenContract**(`address`: string, `supportedProvider`: [SupportedProvider](#supportedprovider), `txDefaults?`: `Partial`, `logDecodeDependencies?`: undefined | object, `deployedBytecode`: string | undefined): *[ERC721TokenContract](#class-erc721tokencontract)* - -*Overrides void* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:995](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L995)* - -**Parameters:** - -Name | Type | Default | ------- | ------ | ------ | -`address` | string | - | -`supportedProvider` | [SupportedProvider](#supportedprovider) | - | -`txDefaults?` | `Partial` | - | -`logDecodeDependencies?` | undefined \| object | - | -`deployedBytecode` | string \| undefined | ERC721TokenContract.deployedBytecode | - -**Returns:** *[ERC721TokenContract](#class-erc721tokencontract)* - -## Properties - -### `Optional` _deployedBytecodeIfExists - -• **_deployedBytecodeIfExists**? : *`Buffer`* - - - -Defined in base-contract/lib/src/index.d.ts:34 - -___ - -### abi - -• **abi**: *[ContractAbi](#contractabi)* - - - -Defined in base-contract/lib/src/index.d.ts:30 - -___ - -### address - -• **address**: *string* - - - -Defined in base-contract/lib/src/index.d.ts:31 - -___ - -Args - -• **constructorArgs**: *any[]* - - - -Defined in base-contract/lib/src/index.d.ts:33 - -___ - -### contractName - -• **contractName**: *string* - - - -Defined in base-contract/lib/src/index.d.ts:32 - -___ - -### `Static` contractName - -▪ **contractName**: *string* = "ERC721Token" - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:76](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L76)* - -## Methods - -### approve - -▸ **approve**(`_approved`: string, `_tokenId`: `BigNumber`): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:525](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L525)* - -The zero address indicates there is no approved address. -Throws unless `msg.sender` is the current NFT owner, or an authorized -operator of the current owner. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`_approved` | string | The new approved NFT controller | -`_tokenId` | `BigNumber` | The NFT to approve | - -**Returns:** *`ContractTxFunctionObj`* - -___ - -### balanceOf - -▸ **balanceOf**(`_owner`: string): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:579](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L579)* - -NFTs assigned to the zero address are considered invalid, and this -function throws for queries about the zero address. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`_owner` | string | An address for whom to query the balance | - -**Returns:** *`ContractFunctionObj`* - -The number of NFTs owned by `_owner`, possibly zero - -___ - -### getABIDecodedReturnData - -▸ **getABIDecodedReturnData**<**T**>(`methodName`: string, `callData`: string): *`T`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:503](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L503)* - -**Type parameters:** - -▪ **T** - -**Parameters:** - -Name | Type | ------- | ------ | -`methodName` | string | -`callData` | string | - -**Returns:** *`T`* - -___ - -### getABIDecodedTransactionData - -▸ **getABIDecodedTransactionData**<**T**>(`methodName`: string, `callData`: string): *`T`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:495](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L495)* - -**Type parameters:** - -▪ **T** - -**Parameters:** - -Name | Type | ------- | ------ | -`methodName` | string | -`callData` | string | - -**Returns:** *`T`* - -___ - -### getApproved - -▸ **getApproved**(`_tokenId`: `BigNumber`): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:605](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L605)* - -Throws if `_tokenId` is not a valid NFT. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`_tokenId` | `BigNumber` | The NFT to find the approved address for | - -**Returns:** *`ContractFunctionObj`* - -The approved address for this NFT, or the zero address if there is none - -___ - -### getFunctionSignature - -▸ **getFunctionSignature**(`methodName`: string): *string* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:488](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L488)* - -**Parameters:** - -Name | Type | ------- | ------ | -`methodName` | string | - -**Returns:** *string* - -___ - -### getLogsAsync - -▸ **getLogsAsync**<**ArgsType**>(`eventName`: [ERC721TokenEvents](#enumeration-erc721tokenevents), `blockRange`: `BlockRange`, `indexFilterValues`: `IndexedFilterValues`): *`Promise>>`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:979](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L979)* - -Gets historical logs without creating a subscription - -**Type parameters:** - -▪ **ArgsType**: *[ERC721TokenEventArgs](#erc721tokeneventargs)* - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`eventName` | [ERC721TokenEvents](#enumeration-erc721tokenevents) | The ERC721Token contract event you would like to subscribe to. | -`blockRange` | `BlockRange` | Block range to get logs from. | -`indexFilterValues` | `IndexedFilterValues` | An object where the keys are indexed args returned by the event and the value is the value you are interested in. E.g `{_from: aUserAddressHex}` | - -**Returns:** *`Promise>>`* - -Array of logs that match the parameters - -___ - -### getSelector - -▸ **getSelector**(`methodName`: string): *string* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:511](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L511)* - -**Parameters:** - -Name | Type | ------- | ------ | -`methodName` | string | - -**Returns:** *string* - -___ - -### isApprovedForAll - -▸ **isApprovedForAll**(`_owner`: string, `_operator`: string): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:626](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L626)* - -**Parameters:** - -Name | Type | ------- | ------ | -`_owner` | string | -`_operator` | string | - -**Returns:** *`ContractFunctionObj`* - -___ - -### ownerOf - -▸ **ownerOf**(`_tokenId`: `BigNumber`): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:654](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L654)* - -NFTs assigned to zero address are considered invalid, and queries -about them do throw. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`_tokenId` | `BigNumber` | The identifier for an NFT | - -**Returns:** *`ContractFunctionObj`* - -The address of the owner of the NFT - -___ - -### safeTransferFrom1 - -▸ **safeTransferFrom1**(`_from`: string, `_to`: string, `_tokenId`: `BigNumber`): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:682](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L682)* - -This works identically to the other function with an extra data parameter, -except this function just sets data to "". - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`_from` | string | The current owner of the NFT | -`_to` | string | The new owner | -`_tokenId` | `BigNumber` | The NFT to transfer | - -**Returns:** *`ContractTxFunctionObj`* - -___ - -### safeTransferFrom2 - -▸ **safeTransferFrom2**(`_from`: string, `_to`: string, `_tokenId`: `BigNumber`, `_data`: string): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:748](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L748)* - -Throws unless `msg.sender` is the current owner, an authorized -operator, or the approved address for this NFT. Throws if `_from` is -not the current owner. Throws if `_to` is the zero address. Throws if -`_tokenId` is not a valid NFT. When transfer is complete, this function -checks if `_to` is a smart contract (code size > 0). If so, it calls -`onERC721Received` on `_to` and throws if the return value is not -`bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`_from` | string | The current owner of the NFT | -`_to` | string | The new owner | -`_tokenId` | `BigNumber` | The NFT to transfer | -`_data` | string | Additional data with no specified format, sent in call to `_to` | - -**Returns:** *`ContractTxFunctionObj`* - -___ - -### setApprovalForAll - -▸ **setApprovalForAll**(`_operator`: string, `_approved`: boolean): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:814](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L814)* - -Emits the ApprovalForAll event. The contract MUST allow -multiple operators per owner. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`_operator` | string | Address to add to the set of authorized operators | -`_approved` | boolean | True if the operator is approved, false to revoke approval | - -**Returns:** *`ContractTxFunctionObj`* - -___ - -### subscribe - -▸ **subscribe**<**ArgsType**>(`eventName`: [ERC721TokenEvents](#enumeration-erc721tokenevents), `indexFilterValues`: `IndexedFilterValues`, `callback`: [EventCallback](#eventcallback)‹*`ArgsType`*›, `isVerbose`: boolean, `blockPollingIntervalMs?`: undefined | number): *string* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:934](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L934)* - -Subscribe to an event type emitted by the ERC721Token contract. - -**Type parameters:** - -▪ **ArgsType**: *[ERC721TokenEventArgs](#erc721tokeneventargs)* - -**Parameters:** - -Name | Type | Default | Description | ------- | ------ | ------ | ------ | -`eventName` | [ERC721TokenEvents](#enumeration-erc721tokenevents) | - | The ERC721Token contract event you would like to subscribe to. | -`indexFilterValues` | `IndexedFilterValues` | - | An object where the keys are indexed args returned by the event and the value is the value you are interested in. E.g `{maker: aUserAddressHex}` | -`callback` | [EventCallback](#eventcallback)‹*`ArgsType`*› | - | Callback that gets called when a log is added/removed | -`isVerbose` | boolean | false | Enable verbose subscription warnings (e.g recoverable network issues encountered) | -`blockPollingIntervalMs?` | undefined \| number | - | - | - -**Returns:** *string* - -Subscription token used later to unsubscribe - -___ - -### transferFrom - -▸ **transferFrom**(`_from`: string, `_to`: string, `_tokenId`: `BigNumber`): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:871](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L871)* - -Throws unless `msg.sender` is the current owner, an authorized -operator, or the approved address for this NFT. Throws if `_from` is -not the current owner. Throws if `_to` is the zero address. Throws if -`_tokenId` is not a valid NFT. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`_from` | string | The current owner of the NFT | -`_to` | string | The new owner | -`_tokenId` | `BigNumber` | The NFT to transfer | - -**Returns:** *`ContractTxFunctionObj`* - -___ - -### unsubscribe - -▸ **unsubscribe**(`subscriptionToken`: string): *void* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:960](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L960)* - -Cancel a subscription - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`subscriptionToken` | string | Subscription token returned by `subscribe()` | - -**Returns:** *void* - -___ - -### unsubscribeAll - -▸ **unsubscribeAll**(): *void* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:967](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L967)* - -Cancels all existing subscriptions - -**Returns:** *void* - -___ - -### `Static` ABI - -▸ **ABI**(): *[ContractAbi](#contractabi)* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:182](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L182)* - -**Returns:** *[ContractAbi](#contractabi)* - -The contract ABI - -___ - -### `Static` deployAsync - -▸ **deployAsync**(`bytecode`: string, `abi`: [ContractAbi](#contractabi), `supportedProvider`: [SupportedProvider](#supportedprovider), `txDefaults`: `Partial`, `logDecodeDependencies`: object): *`Promise`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:138](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L138)* - -**Parameters:** - -Name | Type | ------- | ------ | -`bytecode` | string | -`abi` | [ContractAbi](#contractabi) | -`supportedProvider` | [SupportedProvider](#supportedprovider) | -`txDefaults` | `Partial` | -`logDecodeDependencies` | object | - -**Returns:** *`Promise`* - -___ - -### `Static` deployFrom0xArtifactAsync - -▸ **deployFrom0xArtifactAsync**(`artifact`: `ContractArtifact` | `SimpleContractArtifact`, `supportedProvider`: [SupportedProvider](#supportedprovider), `txDefaults`: `Partial`, `logDecodeDependencies`: object): *`Promise`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:79](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L79)* - -**Parameters:** - -Name | Type | ------- | ------ | -`artifact` | `ContractArtifact` \| `SimpleContractArtifact` | -`supportedProvider` | [SupportedProvider](#supportedprovider) | -`txDefaults` | `Partial` | -`logDecodeDependencies` | object | - -**Returns:** *`Promise`* - -___ - -### `Static` deployWithLibrariesFrom0xArtifactAsync - -▸ **deployWithLibrariesFrom0xArtifactAsync**(`artifact`: `ContractArtifact`, `libraryArtifacts`: object, `supportedProvider`: [SupportedProvider](#supportedprovider), `txDefaults`: `Partial`, `logDecodeDependencies`: object): *`Promise`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:105](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L105)* - -**Parameters:** - -Name | Type | ------- | ------ | -`artifact` | `ContractArtifact` | -`libraryArtifacts` | object | -`supportedProvider` | [SupportedProvider](#supportedprovider) | -`txDefaults` | `Partial` | -`logDecodeDependencies` | object | - -**Returns:** *`Promise`* - -___ - -### `Static` strictArgumentEncodingCheck - -▸ **strictArgumentEncodingCheck**(`inputAbi`: `DataItem`[], `args`: any[]): *string* - - - -Defined in base-contract/lib/src/index.d.ts:44 - -**Parameters:** - -Name | Type | ------- | ------ | -`inputAbi` | `DataItem`[] | -`args` | any[] | - -**Returns:** *string* - -
- -# Class: ExchangeContract - - -## Constructors - - - -\+ **new ExchangeContract**(`address`: string, `supportedProvider`: [SupportedProvider](#supportedprovider), `txDefaults?`: `Partial`, `logDecodeDependencies?`: undefined | object, `deployedBytecode`: string | undefined): *[ExchangeContract](#class-exchangecontract)* - -*Overrides void* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:6007](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L6007)* - -**Parameters:** - -Name | Type | Default | ------- | ------ | ------ | -`address` | string | - | -`supportedProvider` | [SupportedProvider](#supportedprovider) | - | -`txDefaults?` | `Partial` | - | -`logDecodeDependencies?` | undefined \| object | - | -`deployedBytecode` | string \| undefined | ExchangeContract.deployedBytecode | - -**Returns:** *[ExchangeContract](#class-exchangecontract)* - -## Properties - -### `Optional` _deployedBytecodeIfExists - -• **_deployedBytecodeIfExists**? : *`Buffer`* - - - -Defined in base-contract/lib/src/index.d.ts:34 - -___ - -### abi - -• **abi**: *[ContractAbi](#contractabi)* - - - -Defined in base-contract/lib/src/index.d.ts:30 - -___ - -### address - -• **address**: *string* - - - -Defined in base-contract/lib/src/index.d.ts:31 - -___ - -Args - -• **constructorArgs**: *any[]* - - - -Defined in base-contract/lib/src/index.d.ts:33 - -___ - -### contractName - -• **contractName**: *string* - - - -Defined in base-contract/lib/src/index.d.ts:32 - -___ - -### `Static` contractName - -▪ **contractName**: *string* = "Exchange" - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:132](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L132)* - -## Methods - -### EIP1271_MAGIC_VALUE - -▸ **EIP1271_MAGIC_VALUE**(): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:3228](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L3228)* - -**Returns:** *`ContractFunctionObj`* - -___ - -### EIP712_EXCHANGE_DOMAIN_HASH - -▸ **EIP712_EXCHANGE_DOMAIN_HASH**(): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:3248](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L3248)* - -**Returns:** *`ContractFunctionObj`* - -___ - -### allowedValidators - -▸ **allowedValidators**(`index_0`: string, `index_1`: string): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:3268](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L3268)* - -**Parameters:** - -Name | Type | ------- | ------ | -`index_0` | string | -`index_1` | string | - -**Returns:** *`ContractFunctionObj`* - -___ - -### batchCancelOrders - -▸ **batchCancelOrders**(`orders`: `Array`): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:3294](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L3294)* - -Executes multiple calls of cancelOrder. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`orders` | `Array` | Array of order specifications. | - -**Returns:** *`ContractTxFunctionObj`* - -___ - -### batchExecuteTransactions - -▸ **batchExecuteTransactions**(`transactions`: `Array`, `signatures`: string[]): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:3366](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L3366)* - -Executes a batch of Exchange method calls in the context of signer(s). - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`transactions` | `Array` | Array of 0x transaction structures. | -`signatures` | string[] | Array of proofs that transactions have been signed by signer(s). | - -**Returns:** *`ContractTxFunctionObj`* - -returnData Array containing ABI encoded return data for each of the underlying Exchange function calls. - -___ - -### batchFillOrKillOrders - -▸ **batchFillOrKillOrders**(`orders`: `Array`, `takerAssetFillAmounts`: `BigNumber`[], `signatures`: string[]): *`ContractTxFunctionObj>`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:3431](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L3431)* - -Executes multiple calls of fillOrKillOrder. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`orders` | `Array` | Array of order specifications. | -`takerAssetFillAmounts` | `BigNumber`[] | Array of desired amounts of takerAsset to sell in orders. | -`signatures` | string[] | Proofs that orders have been created by makers. | - -**Returns:** *`ContractTxFunctionObj>`* - -fillResults Array of amounts filled and fees paid by makers and taker. - -___ - -### batchFillOrders - -▸ **batchFillOrders**(`orders`: `Array`, `takerAssetFillAmounts`: `BigNumber`[], `signatures`: string[]): *`ContractTxFunctionObj>`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:3535](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L3535)* - -Executes multiple calls of fillOrder. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`orders` | `Array` | Array of order specifications. | -`takerAssetFillAmounts` | `BigNumber`[] | Array of desired amounts of takerAsset to sell in orders. | -`signatures` | string[] | Proofs that orders have been created by makers. | - -**Returns:** *`ContractTxFunctionObj>`* - -fillResults Array of amounts filled and fees paid by makers and taker. - -___ - -### batchFillOrdersNoThrow - -▸ **batchFillOrdersNoThrow**(`orders`: `Array`, `takerAssetFillAmounts`: `BigNumber`[], `signatures`: string[]): *`ContractTxFunctionObj>`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:3639](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L3639)* - -Executes multiple calls of fillOrder. If any fill reverts, the error is caught and ignored. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`orders` | `Array` | Array of order specifications. | -`takerAssetFillAmounts` | `BigNumber`[] | Array of desired amounts of takerAsset to sell in orders. | -`signatures` | string[] | Proofs that orders have been created by makers. | - -**Returns:** *`ContractTxFunctionObj>`* - -fillResults Array of amounts filled and fees paid by makers and taker. - -___ - -### batchMatchOrders - -▸ **batchMatchOrders**(`leftOrders`: `Array`, `rightOrders`: `Array`, `leftSignatures`: string[], `rightSignatures`: string[]): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:3747](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L3747)* - -Match complementary orders that have a profitable spread. -Each order is filled at their respective price point, and -the matcher receives a profit denominated in the left maker asset. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`leftOrders` | `Array` | Set of orders with the same maker / taker asset. | -`rightOrders` | `Array` | Set of orders to match against `leftOrders` | -`leftSignatures` | string[] | Proof that left orders were created by the left makers. | -`rightSignatures` | string[] | Proof that right orders were created by the right makers. | - -**Returns:** *`ContractTxFunctionObj`* - -batchMatchedFillResults Amounts filled and profit generated. - -___ - -### batchMatchOrdersWithMaximalFill - -▸ **batchMatchOrdersWithMaximalFill**(`leftOrders`: `Array`, `rightOrders`: `Array`, `leftSignatures`: string[], `rightSignatures`: string[]): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:3905](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L3905)* - -Match complementary orders that have a profitable spread. -Each order is maximally filled at their respective price point, and -the matcher receives a profit denominated in either the left maker asset, -right maker asset, or a combination of both. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`leftOrders` | `Array` | Set of orders with the same maker / taker asset. | -`rightOrders` | `Array` | Set of orders to match against `leftOrders` | -`leftSignatures` | string[] | Proof that left orders were created by the left makers. | -`rightSignatures` | string[] | Proof that right orders were created by the right makers. | - -**Returns:** *`ContractTxFunctionObj`* - -batchMatchedFillResults Amounts filled and profit generated. - -___ - -### cancelOrder - -▸ **cancelOrder**(`order`: object): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:4054](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L4054)* - -After calling, the order can not be filled anymore. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`order` | object | Order struct containing order specifications. | - -**Returns:** *`ContractTxFunctionObj`* - -___ - -### cancelOrdersUpTo - -▸ **cancelOrdersUpTo**(`targetOrderEpoch`: `BigNumber`): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:4123](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L4123)* - -Cancels all orders created by makerAddress with a salt less than or equal to the targetOrderEpoch -and senderAddress equal to msg.sender (or null address if msg.sender == makerAddress). - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`targetOrderEpoch` | `BigNumber` | Orders created with a salt less or equal to this value will be cancelled. | - -**Returns:** *`ContractTxFunctionObj`* - -___ - -### cancelled - -▸ **cancelled**(`index_0`: string): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:4170](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L4170)* - -**Parameters:** - -Name | Type | ------- | ------ | -`index_0` | string | - -**Returns:** *`ContractFunctionObj`* - -___ - -### currentContextAddress - -▸ **currentContextAddress**(): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:4191](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L4191)* - -**Returns:** *`ContractFunctionObj`* - -___ - -### detachProtocolFeeCollector - -▸ **detachProtocolFeeCollector**(): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:4215](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L4215)* - -Sets the protocolFeeCollector contract address to 0. -Only callable by owner. - -**Returns:** *`ContractTxFunctionObj`* - -___ - -### executeTransaction - -▸ **executeTransaction**(`transaction`: object, `signature`: string): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:4267](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L4267)* - -Executes an Exchange method call in the context of signer. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`transaction` | object | 0x transaction structure. | -`signature` | string | Proof that transaction has been signed by signer. | - -**Returns:** *`ContractTxFunctionObj`* - -ABI encoded return data of the underlying Exchange function call. - -___ - -### fillOrKillOrder - -▸ **fillOrKillOrder**(`order`: object, `takerAssetFillAmount`: `BigNumber`, `signature`: string): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:4331](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L4331)* - -Fills the input order. Reverts if exact `takerAssetFillAmount` not filled. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`order` | object | Order struct containing order specifications. | -`takerAssetFillAmount` | `BigNumber` | Desired amount of takerAsset to sell. | -`signature` | string | Proof that order has been created by maker. | - -**Returns:** *`ContractTxFunctionObj`* - -fillResults Amounts filled and fees paid. - -___ - -### fillOrder - -▸ **fillOrder**(`order`: object, `takerAssetFillAmount`: `BigNumber`, `signature`: string): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:4428](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L4428)* - -Fills the input order. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`order` | object | Order struct containing order specifications. | -`takerAssetFillAmount` | `BigNumber` | Desired amount of takerAsset to sell. | -`signature` | string | Proof that order has been created by maker. | - -**Returns:** *`ContractTxFunctionObj`* - -fillResults Amounts filled and fees paid by maker and taker. - -___ - -### filled - -▸ **filled**(`index_0`: string): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:4518](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L4518)* - -**Parameters:** - -Name | Type | ------- | ------ | -`index_0` | string | - -**Returns:** *`ContractFunctionObj`* - -___ - -### getABIDecodedReturnData - -▸ **getABIDecodedReturnData**<**T**>(`methodName`: string, `callData`: string): *`T`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:3213](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L3213)* - -**Type parameters:** - -▪ **T** - -**Parameters:** - -Name | Type | ------- | ------ | -`methodName` | string | -`callData` | string | - -**Returns:** *`T`* - -___ - -### getABIDecodedTransactionData - -▸ **getABIDecodedTransactionData**<**T**>(`methodName`: string, `callData`: string): *`T`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:3205](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L3205)* - -**Type parameters:** - -▪ **T** - -**Parameters:** - -Name | Type | ------- | ------ | -`methodName` | string | -`callData` | string | - -**Returns:** *`T`* - -___ - -### getAssetProxy - -▸ **getAssetProxy**(`assetProxyId`: string): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:4544](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L4544)* - -Gets an asset proxy. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`assetProxyId` | string | Id of the asset proxy. | - -**Returns:** *`ContractFunctionObj`* - -assetProxy The asset proxy address registered to assetProxyId. Returns 0x0 if no proxy is registered. - -___ - -### getFunctionSignature - -▸ **getFunctionSignature**(`methodName`: string): *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:3198](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L3198)* - -**Parameters:** - -Name | Type | ------- | ------ | -`methodName` | string | - -**Returns:** *string* - -___ - -### getLogsAsync - -▸ **getLogsAsync**<**ArgsType**>(`eventName`: [ExchangeEvents](#enumeration-exchangeevents), `blockRange`: `BlockRange`, `indexFilterValues`: `IndexedFilterValues`): *`Promise>>`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:5991](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L5991)* - -Gets historical logs without creating a subscription - -**Type parameters:** - -▪ **ArgsType**: *[ExchangeEventArgs](#exchangeeventargs)* - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`eventName` | [ExchangeEvents](#enumeration-exchangeevents) | The Exchange contract event you would like to subscribe to. | -`blockRange` | `BlockRange` | Block range to get logs from. | -`indexFilterValues` | `IndexedFilterValues` | An object where the keys are indexed args returned by the event and the value is the value you are interested in. E.g `{_from: aUserAddressHex}` | - -**Returns:** *`Promise>>`* - -Array of logs that match the parameters - -___ - -### getOrderInfo - -▸ **getOrderInfo**(`order`: object): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:4570](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L4570)* - -Gets information about an order: status, hash, and amount filled. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`order` | object | Order to gather information on. | - -**Returns:** *`ContractFunctionObj`* - -orderInfo Information about the order and its state. See LibOrder.OrderInfo for a complete description. - -___ - -### getSelector - -▸ **getSelector**(`methodName`: string): *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:3221](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L3221)* - -**Parameters:** - -Name | Type | ------- | ------ | -`methodName` | string | - -**Returns:** *string* - -___ - -### isValidHashSignature - -▸ **isValidHashSignature**(`hash`: string, `signerAddress`: string, `signature`: string): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:4621](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L4621)* - -Verifies that a hash has been signed by the given signer. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`hash` | string | Any 32-byte hash. | -`signerAddress` | string | Address that should have signed the given hash. | -`signature` | string | Proof that the hash has been signed by signer. | - -**Returns:** *`ContractFunctionObj`* - -isValid `true` if the signature is valid for the given hash and signer. - -___ - -### isValidOrderSignature - -▸ **isValidOrderSignature**(`order`: object, `signature`: string): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:4650](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L4650)* - -Verifies that a signature for an order is valid. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`order` | object | The order. | -`signature` | string | Proof that the order has been signed by signer. | - -**Returns:** *`ContractFunctionObj`* - -isValid `true` if the signature is valid for the given order and signer. - -___ - -### isValidTransactionSignature - -▸ **isValidTransactionSignature**(`transaction`: object, `signature`: string): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:4697](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L4697)* - -Verifies that a signature for a transaction is valid. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`transaction` | object | The transaction. | -`signature` | string | Proof that the order has been signed by signer. | - -**Returns:** *`ContractFunctionObj`* - -isValid `true` if the signature is valid for the given transaction and signer. - -___ - -### marketBuyOrdersFillOrKill - -▸ **marketBuyOrdersFillOrKill**(`orders`: `Array`, `makerAssetFillAmount`: `BigNumber`, `signatures`: string[]): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:4736](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L4736)* - -Calls marketBuyOrdersNoThrow then reverts if < makerAssetFillAmount has been bought. -NOTE: This function does not enforce that the makerAsset is the same for each order. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`orders` | `Array` | Array of order specifications. | -`makerAssetFillAmount` | `BigNumber` | Minimum amount of makerAsset to buy. | -`signatures` | string[] | Proofs that orders have been signed by makers. | - -**Returns:** *`ContractTxFunctionObj`* - -fillResults Amounts filled and fees paid by makers and taker. - -___ - -### marketBuyOrdersNoThrow - -▸ **marketBuyOrdersNoThrow**(`orders`: `Array`, `makerAssetFillAmount`: `BigNumber`, `signatures`: string[]): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:4835](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L4835)* - -Executes multiple calls of fillOrder until total amount of makerAsset is bought by taker. -If any fill reverts, the error is caught and ignored. -NOTE: This function does not enforce that the makerAsset is the same for each order. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`orders` | `Array` | Array of order specifications. | -`makerAssetFillAmount` | `BigNumber` | Desired amount of makerAsset to buy. | -`signatures` | string[] | Proofs that orders have been signed by makers. | - -**Returns:** *`ContractTxFunctionObj`* - -fillResults Amounts filled and fees paid by makers and taker. - -___ - -### marketSellOrdersFillOrKill - -▸ **marketSellOrdersFillOrKill**(`orders`: `Array`, `takerAssetFillAmount`: `BigNumber`, `signatures`: string[]): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:4933](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L4933)* - -Calls marketSellOrdersNoThrow then reverts if < takerAssetFillAmount has been sold. -NOTE: This function does not enforce that the takerAsset is the same for each order. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`orders` | `Array` | Array of order specifications. | -`takerAssetFillAmount` | `BigNumber` | Minimum amount of takerAsset to sell. | -`signatures` | string[] | Proofs that orders have been signed by makers. | - -**Returns:** *`ContractTxFunctionObj`* - -fillResults Amounts filled and fees paid by makers and taker. - -___ - -### marketSellOrdersNoThrow - -▸ **marketSellOrdersNoThrow**(`orders`: `Array`, `takerAssetFillAmount`: `BigNumber`, `signatures`: string[]): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:5032](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L5032)* - -Executes multiple calls of fillOrder until total amount of takerAsset is sold by taker. -If any fill reverts, the error is caught and ignored. -NOTE: This function does not enforce that the takerAsset is the same for each order. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`orders` | `Array` | Array of order specifications. | -`takerAssetFillAmount` | `BigNumber` | Desired amount of takerAsset to sell. | -`signatures` | string[] | Proofs that orders have been signed by makers. | - -**Returns:** *`ContractTxFunctionObj`* - -fillResults Amounts filled and fees paid by makers and taker. - -___ - -### matchOrders - -▸ **matchOrders**(`leftOrder`: object, `rightOrder`: object, `leftSignature`: string, `rightSignature`: string): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:5133](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L5133)* - -Match two complementary orders that have a profitable spread. -Each order is filled at their respective price point. However, the calculations are -carried out as though the orders are both being filled at the right order's price point. -The profit made by the left order goes to the taker (who matched the two orders). - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`leftOrder` | object | First order to match. | -`rightOrder` | object | Second order to match. | -`leftSignature` | string | Proof that order was created by the left maker. | -`rightSignature` | string | Proof that order was created by the right maker. | - -**Returns:** *`ContractTxFunctionObj`* - -matchedFillResults Amounts filled and fees paid by maker and taker of matched orders. - -___ - -### matchOrdersWithMaximalFill - -▸ **matchOrdersWithMaximalFill**(`leftOrder`: object, `rightOrder`: object, `leftSignature`: string, `rightSignature`: string): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:5288](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L5288)* - -Match two complementary orders that have a profitable spread. -Each order is maximally filled at their respective price point, and -the matcher receives a profit denominated in either the left maker asset, -right maker asset, or a combination of both. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`leftOrder` | object | First order to match. | -`rightOrder` | object | Second order to match. | -`leftSignature` | string | Proof that order was created by the left maker. | -`rightSignature` | string | Proof that order was created by the right maker. | - -**Returns:** *`ContractTxFunctionObj`* - -matchedFillResults Amounts filled by maker and taker of matched orders. - -___ - -### orderEpoch - -▸ **orderEpoch**(`index_0`: string, `index_1`: string): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:5432](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L5432)* - -**Parameters:** - -Name | Type | ------- | ------ | -`index_0` | string | -`index_1` | string | - -**Returns:** *`ContractFunctionObj`* - -___ - -### owner - -▸ **owner**(): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:5454](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L5454)* - -**Returns:** *`ContractFunctionObj`* - -___ - -### preSign - -▸ **preSign**(`hash`: string): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:5479](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L5479)* - -Approves a hash on-chain. -After presigning a hash, the preSign signature type will become valid for that hash and signer. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`hash` | string | Any 32-byte hash. | - -**Returns:** *`ContractTxFunctionObj`* - -___ - -### preSigned - -▸ **preSigned**(`index_0`: string, `index_1`: string): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:5526](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L5526)* - -**Parameters:** - -Name | Type | ------- | ------ | -`index_0` | string | -`index_1` | string | - -**Returns:** *`ContractFunctionObj`* - -___ - -### protocolFeeCollector - -▸ **protocolFeeCollector**(): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:5548](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L5548)* - -**Returns:** *`ContractFunctionObj`* - -___ - -### protocolFeeMultiplier - -▸ **protocolFeeMultiplier**(): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:5568](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L5568)* - -**Returns:** *`ContractFunctionObj`* - -___ - -### registerAssetProxy - -▸ **registerAssetProxy**(`assetProxy`: string): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:5593](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L5593)* - -Registers an asset proxy to its asset proxy id. -Once an asset proxy is registered, it cannot be unregistered. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`assetProxy` | string | Address of new asset proxy to register. | - -**Returns:** *`ContractTxFunctionObj`* - -___ - -### setProtocolFeeCollectorAddress - -▸ **setProtocolFeeCollectorAddress**(`updatedProtocolFeeCollector`: string): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:5645](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L5645)* - -Allows the owner to update the protocolFeeCollector address. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`updatedProtocolFeeCollector` | string | The updated protocolFeeCollector contract address. | - -**Returns:** *`ContractTxFunctionObj`* - -___ - -### setProtocolFeeMultiplier - -▸ **setProtocolFeeMultiplier**(`updatedProtocolFeeMultiplier`: `BigNumber`): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:5696](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L5696)* - -Allows the owner to update the protocol fee multiplier. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`updatedProtocolFeeMultiplier` | `BigNumber` | The updated protocol fee multiplier. | - -**Returns:** *`ContractTxFunctionObj`* - -___ - -### setSignatureValidatorApproval - -▸ **setSignatureValidatorApproval**(`validatorAddress`: string, `approval`: boolean): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:5749](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L5749)* - -Approves/unnapproves a Validator contract to verify signatures on signer's behalf -using the `Validator` signature type. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`validatorAddress` | string | Address of Validator contract. | -`approval` | boolean | Approval or disapproval of Validator contract. | - -**Returns:** *`ContractTxFunctionObj`* - -___ - -### simulateDispatchTransferFromCalls - -▸ **simulateDispatchTransferFromCalls**(`assetData`: string[], `fromAddresses`: string[], `toAddresses`: string[], `amounts`: `BigNumber`[]): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:5809](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L5809)* - -This function may be used to simulate any amount of transfers As they would occur through the Exchange contract. Note that this function will always revert, even if all transfers are successful. However, it may be used with eth_call or with a try/catch pattern in order to simulate the results of the transfers. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`assetData` | string[] | Array of asset details, each encoded per the AssetProxy contract specification. | -`fromAddresses` | string[] | Array containing the `from` addresses that correspond with each transfer. | -`toAddresses` | string[] | Array containing the `to` addresses that correspond with each transfer. | -`amounts` | `BigNumber`[] | Array containing the amounts that correspond to each transfer. | - -**Returns:** *`ContractTxFunctionObj`* - -This function does not return a value. However, it will always revert with `Error("TRANSFERS_SUCCESSFUL")` if all of the transfers were successful. - -___ - -### subscribe - -▸ **subscribe**<**ArgsType**>(`eventName`: [ExchangeEvents](#enumeration-exchangeevents), `indexFilterValues`: `IndexedFilterValues`, `callback`: [EventCallback](#eventcallback)‹*`ArgsType`*›, `isVerbose`: boolean, `blockPollingIntervalMs?`: undefined | number): *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:5946](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L5946)* - -Subscribe to an event type emitted by the Exchange contract. - -**Type parameters:** - -▪ **ArgsType**: *[ExchangeEventArgs](#exchangeeventargs)* - -**Parameters:** - -Name | Type | Default | Description | ------- | ------ | ------ | ------ | -`eventName` | [ExchangeEvents](#enumeration-exchangeevents) | - | The Exchange contract event you would like to subscribe to. | -`indexFilterValues` | `IndexedFilterValues` | - | An object where the keys are indexed args returned by the event and the value is the value you are interested in. E.g `{maker: aUserAddressHex}` | -`callback` | [EventCallback](#eventcallback)‹*`ArgsType`*› | - | Callback that gets called when a log is added/removed | -`isVerbose` | boolean | false | Enable verbose subscription warnings (e.g recoverable network issues encountered) | -`blockPollingIntervalMs?` | undefined \| number | - | - | - -**Returns:** *string* - -Subscription token used later to unsubscribe - -___ - -### transactionsExecuted - -▸ **transactionsExecuted**(`index_0`: string): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:5864](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L5864)* - -**Parameters:** - -Name | Type | ------- | ------ | -`index_0` | string | - -**Returns:** *`ContractFunctionObj`* - -___ - -### transferOwnership - -▸ **transferOwnership**(`newOwner`: string): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:5889](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L5889)* - -Change the owner of this contract. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`newOwner` | string | New owner address. | - -**Returns:** *`ContractTxFunctionObj`* - -___ - -### unsubscribe - -▸ **unsubscribe**(`subscriptionToken`: string): *void* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:5972](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L5972)* - -Cancel a subscription - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`subscriptionToken` | string | Subscription token returned by `subscribe()` | - -**Returns:** *void* - -___ - -### unsubscribeAll - -▸ **unsubscribeAll**(): *void* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:5979](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L5979)* - -Cancels all existing subscriptions - -**Returns:** *void* - -___ - -### `Static` ABI - -▸ **ABI**(): *[ContractAbi](#contractabi)* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:245](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L245)* - -**Returns:** *[ContractAbi](#contractabi)* - -The contract ABI - -___ - -### `Static` deployAsync - -▸ **deployAsync**(`bytecode`: string, `abi`: [ContractAbi](#contractabi), `supportedProvider`: [SupportedProvider](#supportedprovider), `txDefaults`: `Partial`, `logDecodeDependencies`: object, `chainId`: `BigNumber`): *`Promise`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:196](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L196)* - -**Parameters:** - -Name | Type | ------- | ------ | -`bytecode` | string | -`abi` | [ContractAbi](#contractabi) | -`supportedProvider` | [SupportedProvider](#supportedprovider) | -`txDefaults` | `Partial` | -`logDecodeDependencies` | object | -`chainId` | `BigNumber` | - -**Returns:** *`Promise`* - -___ - -### `Static` deployFrom0xArtifactAsync - -▸ **deployFrom0xArtifactAsync**(`artifact`: `ContractArtifact` | `SimpleContractArtifact`, `supportedProvider`: [SupportedProvider](#supportedprovider), `txDefaults`: `Partial`, `logDecodeDependencies`: object, `chainId`: `BigNumber`): *`Promise`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:135](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L135)* - -**Parameters:** - -Name | Type | ------- | ------ | -`artifact` | `ContractArtifact` \| `SimpleContractArtifact` | -`supportedProvider` | [SupportedProvider](#supportedprovider) | -`txDefaults` | `Partial` | -`logDecodeDependencies` | object | -`chainId` | `BigNumber` | - -**Returns:** *`Promise`* - -___ - -### `Static` deployWithLibrariesFrom0xArtifactAsync - -▸ **deployWithLibrariesFrom0xArtifactAsync**(`artifact`: `ContractArtifact`, `libraryArtifacts`: object, `supportedProvider`: [SupportedProvider](#supportedprovider), `txDefaults`: `Partial`, `logDecodeDependencies`: object, `chainId`: `BigNumber`): *`Promise`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:162](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L162)* - -**Parameters:** - -Name | Type | ------- | ------ | -`artifact` | `ContractArtifact` | -`libraryArtifacts` | object | -`supportedProvider` | [SupportedProvider](#supportedprovider) | -`txDefaults` | `Partial` | -`logDecodeDependencies` | object | -`chainId` | `BigNumber` | - -**Returns:** *`Promise`* - -___ - -### `Static` strictArgumentEncodingCheck - -▸ **strictArgumentEncodingCheck**(`inputAbi`: `DataItem`[], `args`: any[]): *string* - - - -Defined in base-contract/lib/src/index.d.ts:44 - -**Parameters:** - -Name | Type | ------- | ------ | -`inputAbi` | `DataItem`[] | -`args` | any[] | - -**Returns:** *string* - -
- -# Class: WETH9Contract - - -## Constructors - - - -\+ **new WETH9Contract**(`address`: string, `supportedProvider`: [SupportedProvider](#supportedprovider), `txDefaults?`: `Partial`, `logDecodeDependencies?`: undefined | object, `deployedBytecode`: string | undefined): *[WETH9Contract](#class-weth9contract)* - -*Overrides void* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:984](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L984)* - -**Parameters:** - -Name | Type | Default | ------- | ------ | ------ | -`address` | string | - | -`supportedProvider` | [SupportedProvider](#supportedprovider) | - | -`txDefaults?` | `Partial` | - | -`logDecodeDependencies?` | undefined \| object | - | -`deployedBytecode` | string \| undefined | WETH9Contract.deployedBytecode | - -**Returns:** *[WETH9Contract](#class-weth9contract)* - -## Properties - -### `Optional` _deployedBytecodeIfExists - -• **_deployedBytecodeIfExists**? : *`Buffer`* - - - -Defined in base-contract/lib/src/index.d.ts:34 - -___ - -### abi - -• **abi**: *[ContractAbi](#contractabi)* - - - -Defined in base-contract/lib/src/index.d.ts:30 - -___ - -### address - -• **address**: *string* - - - -Defined in base-contract/lib/src/index.d.ts:31 - -___ - -Args - -• **constructorArgs**: *any[]* - - - -Defined in base-contract/lib/src/index.d.ts:33 - -___ - -### contractName - -• **contractName**: *string* - - - -Defined in base-contract/lib/src/index.d.ts:32 - -___ - -### `Static` contractName - -▪ **contractName**: *string* = "WETH9" - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:82](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L82)* - -## Methods - -### allowance - -▸ **allowance**(`index_0`: string, `index_1`: string): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:552](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L552)* - -**Parameters:** - -Name | Type | ------- | ------ | -`index_0` | string | -`index_1` | string | - -**Returns:** *`ContractFunctionObj`* - -___ - -### approve - -▸ **approve**(`guy`: string, `wad`: `BigNumber`): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:574](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L574)* - -**Parameters:** - -Name | Type | ------- | ------ | -`guy` | string | -`wad` | `BigNumber` | - -**Returns:** *`ContractTxFunctionObj`* - -___ - -### balanceOf - -▸ **balanceOf**(`index_0`: string): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:622](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L622)* - -**Parameters:** - -Name | Type | ------- | ------ | -`index_0` | string | - -**Returns:** *`ContractFunctionObj`* - -___ - -### decimals - -▸ **decimals**(): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:643](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L643)* - -**Returns:** *`ContractFunctionObj`* - -___ - -### deposit - -▸ **deposit**(): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:663](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L663)* - -**Returns:** *`ContractTxFunctionObj`* - -___ - -### getABIDecodedReturnData - -▸ **getABIDecodedReturnData**<**T**>(`methodName`: string, `callData`: string): *`T`* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:537](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L537)* - -**Type parameters:** - -▪ **T** - -**Parameters:** - -Name | Type | ------- | ------ | -`methodName` | string | -`callData` | string | - -**Returns:** *`T`* - -___ - -### getABIDecodedTransactionData - -▸ **getABIDecodedTransactionData**<**T**>(`methodName`: string, `callData`: string): *`T`* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:529](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L529)* - -**Type parameters:** - -▪ **T** - -**Parameters:** - -Name | Type | ------- | ------ | -`methodName` | string | -`callData` | string | - -**Returns:** *`T`* - -___ - -### getFunctionSignature - -▸ **getFunctionSignature**(`methodName`: string): *string* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:522](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L522)* - -**Parameters:** - -Name | Type | ------- | ------ | -`methodName` | string | - -**Returns:** *string* - -___ - -### getLogsAsync - -▸ **getLogsAsync**<**ArgsType**>(`eventName`: [WETH9Events](#enumeration-weth9events), `blockRange`: `BlockRange`, `indexFilterValues`: `IndexedFilterValues`): *`Promise>>`* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:968](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L968)* - -Gets historical logs without creating a subscription - -**Type parameters:** - -▪ **ArgsType**: *[WETH9EventArgs](#weth9eventargs)* - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`eventName` | [WETH9Events](#enumeration-weth9events) | The WETH9 contract event you would like to subscribe to. | -`blockRange` | `BlockRange` | Block range to get logs from. | -`indexFilterValues` | `IndexedFilterValues` | An object where the keys are indexed args returned by the event and the value is the value you are interested in. E.g `{_from: aUserAddressHex}` | - -**Returns:** *`Promise>>`* - -Array of logs that match the parameters - -___ - -### getSelector - -▸ **getSelector**(`methodName`: string): *string* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:545](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L545)* - -**Parameters:** - -Name | Type | ------- | ------ | -`methodName` | string | - -**Returns:** *string* - -___ - -### name - -▸ **name**(): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:709](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L709)* - -**Returns:** *`ContractFunctionObj`* - -___ - -### subscribe - -▸ **subscribe**<**ArgsType**>(`eventName`: [WETH9Events](#enumeration-weth9events), `indexFilterValues`: `IndexedFilterValues`, `callback`: [EventCallback](#eventcallback)‹*`ArgsType`*›, `isVerbose`: boolean, `blockPollingIntervalMs?`: undefined | number): *string* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:923](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L923)* - -Subscribe to an event type emitted by the WETH9 contract. - -**Type parameters:** - -▪ **ArgsType**: *[WETH9EventArgs](#weth9eventargs)* - -**Parameters:** - -Name | Type | Default | Description | ------- | ------ | ------ | ------ | -`eventName` | [WETH9Events](#enumeration-weth9events) | - | The WETH9 contract event you would like to subscribe to. | -`indexFilterValues` | `IndexedFilterValues` | - | An object where the keys are indexed args returned by the event and the value is the value you are interested in. E.g `{maker: aUserAddressHex}` | -`callback` | [EventCallback](#eventcallback)‹*`ArgsType`*› | - | Callback that gets called when a log is added/removed | -`isVerbose` | boolean | false | Enable verbose subscription warnings (e.g recoverable network issues encountered) | -`blockPollingIntervalMs?` | undefined \| number | - | - | - -**Returns:** *string* - -Subscription token used later to unsubscribe - -___ - -### symbol - -▸ **symbol**(): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:729](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L729)* - -**Returns:** *`ContractFunctionObj`* - -___ - -### totalSupply - -▸ **totalSupply**(): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:749](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L749)* - -**Returns:** *`ContractFunctionObj`* - -___ - -### transfer - -▸ **transfer**(`dst`: string, `wad`: `BigNumber`): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:769](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L769)* - -**Parameters:** - -Name | Type | ------- | ------ | -`dst` | string | -`wad` | `BigNumber` | - -**Returns:** *`ContractTxFunctionObj`* - -___ - -### transferFrom - -▸ **transferFrom**(`src`: string, `dst`: string, `wad`: `BigNumber`): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:817](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L817)* - -**Parameters:** - -Name | Type | ------- | ------ | -`src` | string | -`dst` | string | -`wad` | `BigNumber` | - -**Returns:** *`ContractTxFunctionObj`* - -___ - -### unsubscribe - -▸ **unsubscribe**(`subscriptionToken`: string): *void* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:949](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L949)* - -Cancel a subscription - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`subscriptionToken` | string | Subscription token returned by `subscribe()` | - -**Returns:** *void* - -___ - -### unsubscribeAll - -▸ **unsubscribeAll**(): *void* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:956](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L956)* - -Cancels all existing subscriptions - -**Returns:** *void* - -___ - -### withdraw - -▸ **withdraw**(`wad`: `BigNumber`): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:866](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L866)* - -**Parameters:** - -Name | Type | ------- | ------ | -`wad` | `BigNumber` | - -**Returns:** *`ContractTxFunctionObj`* - -___ - -### `Static` ABI - -▸ **ABI**(): *[ContractAbi](#contractabi)* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:188](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L188)* - -**Returns:** *[ContractAbi](#contractabi)* - -The contract ABI - -___ - -### `Static` deployAsync - -▸ **deployAsync**(`bytecode`: string, `abi`: [ContractAbi](#contractabi), `supportedProvider`: [SupportedProvider](#supportedprovider), `txDefaults`: `Partial`, `logDecodeDependencies`: object): *`Promise`* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:144](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L144)* - -**Parameters:** - -Name | Type | ------- | ------ | -`bytecode` | string | -`abi` | [ContractAbi](#contractabi) | -`supportedProvider` | [SupportedProvider](#supportedprovider) | -`txDefaults` | `Partial` | -`logDecodeDependencies` | object | - -**Returns:** *`Promise`* - -___ - -### `Static` deployFrom0xArtifactAsync - -▸ **deployFrom0xArtifactAsync**(`artifact`: `ContractArtifact` | `SimpleContractArtifact`, `supportedProvider`: [SupportedProvider](#supportedprovider), `txDefaults`: `Partial`, `logDecodeDependencies`: object): *`Promise`* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:85](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L85)* - -**Parameters:** - -Name | Type | ------- | ------ | -`artifact` | `ContractArtifact` \| `SimpleContractArtifact` | -`supportedProvider` | [SupportedProvider](#supportedprovider) | -`txDefaults` | `Partial` | -`logDecodeDependencies` | object | - -**Returns:** *`Promise`* - -___ - -### `Static` deployWithLibrariesFrom0xArtifactAsync - -▸ **deployWithLibrariesFrom0xArtifactAsync**(`artifact`: `ContractArtifact`, `libraryArtifacts`: object, `supportedProvider`: [SupportedProvider](#supportedprovider), `txDefaults`: `Partial`, `logDecodeDependencies`: object): *`Promise`* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:111](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L111)* - -**Parameters:** - -Name | Type | ------- | ------ | -`artifact` | `ContractArtifact` | -`libraryArtifacts` | object | -`supportedProvider` | [SupportedProvider](#supportedprovider) | -`txDefaults` | `Partial` | -`logDecodeDependencies` | object | - -**Returns:** *`Promise`* - -___ - -### `Static` strictArgumentEncodingCheck - -▸ **strictArgumentEncodingCheck**(`inputAbi`: `DataItem`[], `args`: any[]): *string* - - - -Defined in base-contract/lib/src/index.d.ts:44 - -**Parameters:** - -Name | Type | ------- | ------ | -`inputAbi` | `DataItem`[] | -`args` | any[] | - -**Returns:** *string* - -
- -# Class: MetamaskSubprovider - -This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) -subprovider interface and the provider sendAsync interface. -It handles inconsistencies with Metamask implementations of various JSON RPC methods. -It forwards JSON RPC requests involving the domain of a signer (getAccounts, -sendTransaction, signMessage etc...) to the provider instance supplied at instantiation. All other requests -are passed onwards for subsequent subproviders to handle. - - -## Constructors - - - -\+ **new MetamaskSubprovider**(`supportedProvider`: [SupportedProvider](#supportedprovider)): *[MetamaskSubprovider](#class-metamasksubprovider)* - -*Defined in [subproviders/src/subproviders/metamask_subprovider.ts:19](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/subproviders/src/subproviders/metamask_subprovider.ts#L19)* - -Instantiates a new MetamaskSubprovider - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`supportedProvider` | [SupportedProvider](#supportedprovider) | Web3 provider that should handle all user account related requests | - -**Returns:** *[MetamaskSubprovider](#class-metamasksubprovider)* - -## Methods - -### emitPayloadAsync - -▸ **emitPayloadAsync**(`payload`: `Partial`): *`Promise`* - - - -*Defined in [subproviders/src/subproviders/subprovider.ts:55](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/subproviders/src/subproviders/subprovider.ts#L55)* - -Emits a JSON RPC payload that will then be handled by the ProviderEngine instance -this subprovider is a part of. The payload will cascade down the subprovider middleware -stack until finding the responsible entity for handling the request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `Partial` | JSON RPC payload | - -**Returns:** *`Promise`* - -JSON RPC response payload - -___ - -### handleRequest - -▸ **handleRequest**(`payload`: `JSONRPCRequestPayload`, `next`: [Callback](#callback), `end`: [ErrorCallback](#errorcallback)): *`Promise`* - -*Overrides void* - -*Defined in [subproviders/src/subproviders/metamask_subprovider.ts:39](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/subproviders/src/subproviders/metamask_subprovider.ts#L39)* - -This method conforms to the web3-provider-engine interface. -It is called internally by the ProviderEngine when it is this subproviders -turn to handle a JSON RPC request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `JSONRPCRequestPayload` | JSON RPC payload | -`next` | [Callback](#callback) | Callback to call if this subprovider decides not to handle the request | -`end` | [ErrorCallback](#errorcallback) | Callback to call if subprovider handled the request and wants to pass back the request. | - -**Returns:** *`Promise`* - -___ - -### sendAsync - -▸ **sendAsync**(`payload`: `JSONRPCRequestPayload`, `callback`: [ErrorCallback](#errorcallback)): *void* - -*Defined in [subproviders/src/subproviders/metamask_subprovider.ts:117](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/subproviders/src/subproviders/metamask_subprovider.ts#L117)* - -This method conforms to the provider sendAsync interface. -Allowing the MetamaskSubprovider to be used as a generic provider (outside of Web3ProviderEngine) with the -addition of wrapping the inconsistent Metamask behaviour - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `JSONRPCRequestPayload` | JSON RPC payload | -`callback` | [ErrorCallback](#errorcallback) | - | - -**Returns:** *void* - -The contents nested under the result key of the response body - -___ - -### setEngine - -▸ **setEngine**(`engine`: `Web3ProviderEngine`): *void* - - - -*Defined in [subproviders/src/subproviders/subprovider.ts:68](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/subproviders/src/subproviders/subprovider.ts#L68)* - -Set's the subprovider's engine to the ProviderEngine it is added to. -This is only called within the ProviderEngine source code, do not call -directly. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`engine` | `Web3ProviderEngine` | The ProviderEngine this subprovider is added to | - -**Returns:** *void* - -
- -# Class: RPCSubprovider - -This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface. -It forwards on JSON RPC requests to the supplied `rpcUrl` endpoint - - -## Constructors - - - -\+ **new RPCSubprovider**(`rpcUrl`: string, `requestTimeoutMs`: number): *[RPCSubprovider](#class-rpcsubprovider)* - -*Defined in [subproviders/src/subproviders/rpc_subprovider.ts:17](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/subproviders/src/subproviders/rpc_subprovider.ts#L17)* - -**Parameters:** - -Name | Type | Default | Description | ------- | ------ | ------ | ------ | -`rpcUrl` | string | - | URL to the backing Ethereum node to which JSON RPC requests should be sent | -`requestTimeoutMs` | number | 20000 | Amount of miliseconds to wait before timing out the JSON RPC request | - -**Returns:** *[RPCSubprovider](#class-rpcsubprovider)* - -## Methods - -### emitPayloadAsync - -▸ **emitPayloadAsync**(`payload`: `Partial`): *`Promise`* - - - -*Defined in [subproviders/src/subproviders/subprovider.ts:55](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/subproviders/src/subproviders/subprovider.ts#L55)* - -Emits a JSON RPC payload that will then be handled by the ProviderEngine instance -this subprovider is a part of. The payload will cascade down the subprovider middleware -stack until finding the responsible entity for handling the request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `Partial` | JSON RPC payload | - -**Returns:** *`Promise`* - -JSON RPC response payload - -___ - -### handleRequest - -▸ **handleRequest**(`payload`: `JSONRPCRequestPayload`, `_next`: [Callback](#callback), `end`: [ErrorCallback](#errorcallback)): *`Promise`* - -*Overrides void* - -*Defined in [subproviders/src/subproviders/rpc_subprovider.ts:38](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/subproviders/src/subproviders/rpc_subprovider.ts#L38)* - -This method conforms to the web3-provider-engine interface. -It is called internally by the ProviderEngine when it is this subproviders -turn to handle a JSON RPC request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `JSONRPCRequestPayload` | JSON RPC payload | -`_next` | [Callback](#callback) | Callback to call if this subprovider decides not to handle the request | -`end` | [ErrorCallback](#errorcallback) | Callback to call if subprovider handled the request and wants to pass back the request. | - -**Returns:** *`Promise`* - -___ - -### setEngine - -▸ **setEngine**(`engine`: `Web3ProviderEngine`): *void* - - - -*Defined in [subproviders/src/subproviders/subprovider.ts:68](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/subproviders/src/subproviders/subprovider.ts#L68)* - -Set's the subprovider's engine to the ProviderEngine it is added to. -This is only called within the ProviderEngine source code, do not call -directly. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`engine` | `Web3ProviderEngine` | The ProviderEngine this subprovider is added to | - -**Returns:** *void* - -
- -# Enumeration: SubscriptionErrors - - -## Enumeration members - -### SubscriptionAlreadyPresent - -• **SubscriptionAlreadyPresent**: = "SUBSCRIPTION_ALREADY_PRESENT" - -*Defined in [base-contract/src/types.ts:21](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/base-contract/src/types.ts#L21)* - -___ - -### SubscriptionNotFound - -• **SubscriptionNotFound**: = "SUBSCRIPTION_NOT_FOUND" - -*Defined in [base-contract/src/types.ts:20](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/base-contract/src/types.ts#L20)* - -
- -# Enumeration: ChainId - - -## Enumeration members - -### Ganache - -• **Ganache**: = 1337 - -*Defined in [contract-addresses/src/index.ts:56](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L56)* - -___ - -### Kovan - -• **Kovan**: = 42 - -*Defined in [contract-addresses/src/index.ts:55](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L55)* - -___ - -### Mainnet - -• **Mainnet**: = 1 - -*Defined in [contract-addresses/src/index.ts:52](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L52)* - -___ - -### Rinkeby - -• **Rinkeby**: = 4 - -*Defined in [contract-addresses/src/index.ts:54](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L54)* - -___ - -### Ropsten - -• **Ropsten**: = 3 - -*Defined in [contract-addresses/src/index.ts:53](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L53)* - -
- -# Enumeration: ERC20TokenEvents - - -## Enumeration members - -### Approval - -• **Approval**: = "Approval" - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:41](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L41)* - -___ - -### Transfer - -• **Transfer**: = "Transfer" - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:42](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L42)* - -
- -# Enumeration: ERC721TokenEvents - - -## Enumeration members - -### Approval - -• **Approval**: = "Approval" - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:44](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L44)* - -___ - -### ApprovalForAll - -• **ApprovalForAll**: = "ApprovalForAll" - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:45](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L45)* - -___ - -### Transfer - -• **Transfer**: = "Transfer" - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:46](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L46)* - -
- -# Enumeration: ExchangeEvents - - -## Enumeration members - -### AssetProxyRegistered - -• **AssetProxyRegistered**: = "AssetProxyRegistered" - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:50](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L50)* - -___ - -### Cancel - -• **Cancel**: = "Cancel" - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:51](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L51)* - -___ - -### CancelUpTo - -• **CancelUpTo**: = "CancelUpTo" - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:52](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L52)* - -___ - -### Fill - -• **Fill**: = "Fill" - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:53](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L53)* - -___ - -### OwnershipTransferred - -• **OwnershipTransferred**: = "OwnershipTransferred" - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:54](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L54)* - -___ - -### ProtocolFeeCollectorAddress - -• **ProtocolFeeCollectorAddress**: = "ProtocolFeeCollectorAddress" - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:55](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L55)* - -___ - -### ProtocolFeeMultiplier - -• **ProtocolFeeMultiplier**: = "ProtocolFeeMultiplier" - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:56](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L56)* - -___ - -### SignatureValidatorApproval - -• **SignatureValidatorApproval**: = "SignatureValidatorApproval" - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:57](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L57)* - -___ - -### TransactionExecution - -• **TransactionExecution**: = "TransactionExecution" - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:58](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L58)* - -
- -# Enumeration: WETH9Events - - -## Enumeration members - -### Approval - -• **Approval**: = "Approval" - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:45](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L45)* - -___ - -### Deposit - -• **Deposit**: = "Deposit" - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:46](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L46)* - -___ - -### Transfer - -• **Transfer**: = "Transfer" - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:47](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L47)* - -___ - -### Withdrawal - -• **Withdrawal**: = "Withdrawal" - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:48](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L48)* - -
- - - -# Enumeration: BlockParamLiteral - - -## Enumeration members - -### Earliest - -• **Earliest**: = "earliest" - -*Defined in [ethereum-types/src/index.ts:488](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L488)* - -___ - -### Latest - -• **Latest**: = "latest" - -*Defined in [ethereum-types/src/index.ts:489](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L489)* - -___ - -### Pending - -• **Pending**: = "pending" - -*Defined in [ethereum-types/src/index.ts:490](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L490)* - -
- - - - - - - - - - - - - - - - - - - - - - - - - -# Enumeration: SignatureType - - -## Enumeration members - -### EIP1271Wallet - -• **EIP1271Wallet**: - -*Defined in [types/src/index.ts:182](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L182)* - -___ - -### EIP712 - -• **EIP712**: - -*Defined in [types/src/index.ts:177](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L177)* - -___ - -### EthSign - -• **EthSign**: - -*Defined in [types/src/index.ts:178](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L178)* - -___ - -### Illegal - -• **Illegal**: - -*Defined in [types/src/index.ts:175](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L175)* - -___ - -### Invalid - -• **Invalid**: - -*Defined in [types/src/index.ts:176](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L176)* - -___ - -### NSignatureTypes - -• **NSignatureTypes**: - -*Defined in [types/src/index.ts:183](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L183)* - -___ - -### PreSigned - -• **PreSigned**: - -*Defined in [types/src/index.ts:181](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L181)* - -___ - -### Validator - -• **Validator**: - -*Defined in [types/src/index.ts:180](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L180)* - -___ - -### Wallet - -• **Wallet**: - -*Defined in [types/src/index.ts:179](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L179)* - -
- - - - - - - - - - - -
- -# Interface: AwaitTransactionSuccessOpts - -Used with `awaitTransactionSuccessAsync` -* pollingIntervalMs: Determine polling intervals in milliseconds -* timeoutMs: Determines timeout in milliseconds - - -## Properties - -### `Optional` pollingIntervalMs - -• **pollingIntervalMs**? : *undefined | number* - -*Defined in [base-contract/src/types.ts:39](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/base-contract/src/types.ts#L39)* - -___ - -### `Optional` shouldValidate - -• **shouldValidate**? : *undefined | false | true* - -*Inherited from [SendTransactionOpts](#interface-sendtransactionopts).[shouldValidate](#optional-shouldvalidate)* - -*Defined in [base-contract/src/types.ts:30](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/base-contract/src/types.ts#L30)* - -___ - -### `Optional` timeoutMs - -• **timeoutMs**? : *undefined | number* - -*Defined in [base-contract/src/types.ts:40](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/base-contract/src/types.ts#L40)* - -
- -# Interface: ContractEvent <**ContractEventArgs**> - -## Type parameters - -▪ **ContractEventArgs** - - -## Properties - -### address - -• **address**: *string* - -*Defined in [base-contract/src/types.ts:13](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/base-contract/src/types.ts#L13)* - -___ - -### args - -• **args**: *`ContractEventArgs`* - -*Defined in [base-contract/src/types.ts:16](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/base-contract/src/types.ts#L16)* - -___ - -### blockHash - -• **blockHash**: *string* - -*Defined in [base-contract/src/types.ts:11](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/base-contract/src/types.ts#L11)* - -___ - -### blockNumber - -• **blockNumber**: *number* - -*Defined in [base-contract/src/types.ts:12](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/base-contract/src/types.ts#L12)* - -___ - -### event - -• **event**: *string* - -*Defined in [base-contract/src/types.ts:15](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/base-contract/src/types.ts#L15)* - -___ - -### logIndex - -• **logIndex**: *number* - -*Defined in [base-contract/src/types.ts:8](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/base-contract/src/types.ts#L8)* - -___ - -### transactionHash - -• **transactionHash**: *string* - -*Defined in [base-contract/src/types.ts:10](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/base-contract/src/types.ts#L10)* - -___ - -### transactionIndex - -• **transactionIndex**: *number* - -*Defined in [base-contract/src/types.ts:9](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/base-contract/src/types.ts#L9)* - -___ - -### type - -• **type**: *string* - -*Defined in [base-contract/src/types.ts:14](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/base-contract/src/types.ts#L14)* - -
- -# Interface: ContractFunctionObj <**T**> - -## Type parameters - -▪ **T** - - -## Methods - -### callAsync - -▸ **callAsync**(`callData?`: `Partial`, `defaultBlock?`: [BlockParam](#blockparam)): *`Promise`* - -*Defined in [base-contract/src/types.ts:44](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/base-contract/src/types.ts#L44)* - -**Parameters:** - -Name | Type | ------- | ------ | -`callData?` | `Partial` | -`defaultBlock?` | [BlockParam](#blockparam) | - -**Returns:** *`Promise`* - -___ - -### getABIEncodedTransactionData - -▸ **getABIEncodedTransactionData**(): *string* - -*Defined in [base-contract/src/types.ts:45](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/base-contract/src/types.ts#L45)* - -**Returns:** *string* - -
- -# Interface: ContractTxFunctionObj <**T**> - -## Type parameters - -▪ **T** - - -## Methods - -### awaitTransactionSuccessAsync - -▸ **awaitTransactionSuccessAsync**(`txData?`: `Partial`, `opts?`: [AwaitTransactionSuccessOpts](#class-awaittransactionsuccessopts)): *`PromiseWithTransactionHash`* - -*Defined in [base-contract/src/types.ts:50](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/base-contract/src/types.ts#L50)* - -**Parameters:** - -Name | Type | ------- | ------ | -`txData?` | `Partial` | -`opts?` | [AwaitTransactionSuccessOpts](#class-awaittransactionsuccessopts) | - -**Returns:** *`PromiseWithTransactionHash`* - -___ - -### callAsync - -▸ **callAsync**(`callData?`: `Partial`, `defaultBlock?`: [BlockParam](#blockparam)): *`Promise`* - -*Inherited from [ContractFunctionObj](#interface-contractfunctionobj).[callAsync](#callasync)* - -*Defined in [base-contract/src/types.ts:44](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/base-contract/src/types.ts#L44)* - -**Parameters:** - -Name | Type | ------- | ------ | -`callData?` | `Partial` | -`defaultBlock?` | [BlockParam](#blockparam) | - -**Returns:** *`Promise`* - -___ - -### estimateGasAsync - -▸ **estimateGasAsync**(`txData?`: `Partial`): *`Promise`* - -*Defined in [base-contract/src/types.ts:54](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/base-contract/src/types.ts#L54)* - -**Parameters:** - -Name | Type | ------- | ------ | -`txData?` | `Partial` | - -**Returns:** *`Promise`* - -___ - -### getABIEncodedTransactionData - -▸ **getABIEncodedTransactionData**(): *string* - -*Inherited from [ContractFunctionObj](#interface-contractfunctionobj).[getABIEncodedTransactionData](#getabiencodedtransactiondata)* - -*Defined in [base-contract/src/types.ts:45](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/base-contract/src/types.ts#L45)* - -**Returns:** *string* - -___ - -### sendTransactionAsync - -▸ **sendTransactionAsync**(`txData?`: `Partial`, `opts?`: [SendTransactionOpts](#class-sendtransactionopts)): *`Promise`* - -*Defined in [base-contract/src/types.ts:49](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/base-contract/src/types.ts#L49)* - -**Parameters:** - -Name | Type | ------- | ------ | -`txData?` | `Partial` | -`opts?` | [SendTransactionOpts](#class-sendtransactionopts) | - -**Returns:** *`Promise`* - -
- -# Interface: SendTransactionOpts - -Used with `sendTransactionAsync` -* shouldValidate: Flag indicating whether the library should make attempts to validate a transaction before -broadcasting it. For example, order has a valid signature, maker has sufficient funds, etc. Default=true. - - -## Properties - -### `Optional` shouldValidate - -• **shouldValidate**? : *undefined | false | true* - -*Defined in [base-contract/src/types.ts:30](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/base-contract/src/types.ts#L30)* - -
- -# Interface: ContractAddresses - - -## Properties - -### assetProxyOwner - -• **assetProxyOwner**: *string* - -*Defined in [contract-addresses/src/index.ts:10](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L10)* - -___ - -### balancerBridge - -• **balancerBridge**: *string* - -*Defined in [contract-addresses/src/index.ts:37](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L37)* - -___ - -### broker - -• **broker**: *string* - -*Defined in [contract-addresses/src/index.ts:32](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L32)* - -___ - -### chaiBridge - -• **chaiBridge**: *string* - -*Defined in [contract-addresses/src/index.ts:28](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L28)* - -___ - -### chainlinkStopLimit - -• **chainlinkStopLimit**: *string* - -*Defined in [contract-addresses/src/index.ts:33](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L33)* - -___ - -### coordinator - -• **coordinator**: *string* - -*Defined in [contract-addresses/src/index.ts:14](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L14)* - -___ - -### coordinatorRegistry - -• **coordinatorRegistry**: *string* - -*Defined in [contract-addresses/src/index.ts:13](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L13)* - -___ - -### curveBridge - -• **curveBridge**: *string* - -*Defined in [contract-addresses/src/index.ts:30](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L30)* - -___ - -### devUtils - -• **devUtils**: *string* - -*Defined in [contract-addresses/src/index.ts:18](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L18)* - -___ - -### dexForwarderBridge - -• **dexForwarderBridge**: *string* - -*Defined in [contract-addresses/src/index.ts:35](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L35)* - -___ - -### dydxBridge - -• **dydxBridge**: *string* - -*Defined in [contract-addresses/src/index.ts:29](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L29)* - -___ - -### erc1155Proxy - -• **erc1155Proxy**: *string* - -*Defined in [contract-addresses/src/index.ts:17](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L17)* - -___ - -### erc20BridgeProxy - -• **erc20BridgeProxy**: *string* - -*Defined in [contract-addresses/src/index.ts:22](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L22)* - -___ - -### erc20BridgeSampler - -• **erc20BridgeSampler**: *string* - -*Defined in [contract-addresses/src/index.ts:23](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L23)* - -___ - -### erc20Proxy - -• **erc20Proxy**: *string* - -*Defined in [contract-addresses/src/index.ts:4](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L4)* - -___ - -### erc721Proxy - -• **erc721Proxy**: *string* - -*Defined in [contract-addresses/src/index.ts:5](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L5)* - -___ - -### eth2DaiBridge - -• **eth2DaiBridge**: *string* - -*Defined in [contract-addresses/src/index.ts:26](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L26)* - -___ - -### etherToken - -• **etherToken**: *string* - -*Defined in [contract-addresses/src/index.ts:7](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L7)* - -___ - -### exchange - -• **exchange**: *string* - -*Defined in [contract-addresses/src/index.ts:9](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L9)* - -___ - -### exchangeProxy - -• **exchangeProxy**: *string* - -*Defined in [contract-addresses/src/index.ts:39](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L39)* - -___ - -### exchangeProxyAllowanceTarget - -• **exchangeProxyAllowanceTarget**: *string* - -*Defined in [contract-addresses/src/index.ts:40](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L40)* - -___ - -### exchangeProxyFlashWallet - -• **exchangeProxyFlashWallet**: *string* - -*Defined in [contract-addresses/src/index.ts:42](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L42)* - -___ - -### exchangeProxyGovernor - -• **exchangeProxyGovernor**: *string* - -*Defined in [contract-addresses/src/index.ts:38](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L38)* - -___ - -### exchangeProxyTransformerDeployer - -• **exchangeProxyTransformerDeployer**: *string* - -*Defined in [contract-addresses/src/index.ts:41](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L41)* - -___ - -### exchangeV2 - -• **exchangeV2**: *string* - -*Defined in [contract-addresses/src/index.ts:8](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L8)* - -___ - -### forwarder - -• **forwarder**: *string* - -*Defined in [contract-addresses/src/index.ts:12](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L12)* - -___ - -### godsUnchainedValidator - -• **godsUnchainedValidator**: *string* - -*Defined in [contract-addresses/src/index.ts:31](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L31)* - -___ - -### kyberBridge - -• **kyberBridge**: *string* - -*Defined in [contract-addresses/src/index.ts:27](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L27)* - -___ - -### maximumGasPrice - -• **maximumGasPrice**: *string* - -*Defined in [contract-addresses/src/index.ts:34](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L34)* - -___ - -### multiAssetProxy - -• **multiAssetProxy**: *string* - -*Defined in [contract-addresses/src/index.ts:15](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L15)* - -___ - -### multiBridge - -• **multiBridge**: *string* - -*Defined in [contract-addresses/src/index.ts:36](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L36)* - -___ - -### staking - -• **staking**: *string* - -*Defined in [contract-addresses/src/index.ts:20](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L20)* - -___ - -### stakingProxy - -• **stakingProxy**: *string* - -*Defined in [contract-addresses/src/index.ts:21](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L21)* - -___ - -### staticCallProxy - -• **staticCallProxy**: *string* - -*Defined in [contract-addresses/src/index.ts:16](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L16)* - -___ - -### transformers - -• **transformers**: *object* - -*Defined in [contract-addresses/src/index.ts:43](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L43)* - -#### Type declaration: - -___ - -### uniswapBridge - -• **uniswapBridge**: *string* - -*Defined in [contract-addresses/src/index.ts:24](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L24)* - -___ - -### uniswapV2Bridge - -• **uniswapV2Bridge**: *string* - -*Defined in [contract-addresses/src/index.ts:25](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L25)* - -___ - -### zeroExGovernor - -• **zeroExGovernor**: *string* - -*Defined in [contract-addresses/src/index.ts:11](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L11)* - -___ - -### zrxToken - -• **zrxToken**: *string* - -*Defined in [contract-addresses/src/index.ts:6](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L6)* - -___ - -### zrxVault - -• **zrxVault**: *string* - -*Defined in [contract-addresses/src/index.ts:19](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L19)* - -
- -# Interface: ERC20TokenApprovalEventArgs - - -## Index - -### Properties - -* [_owner](#_owner) -* [_spender](#_spender) -* [_value](#_value) - -## Properties - -### _owner - -• **_owner**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:46](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L46)* - -___ - -### _spender - -• **_spender**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:47](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L47)* - -___ - -### _value - -• **_value**: *`BigNumber`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:48](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L48)* - -
- -# Interface: ERC20TokenTransferEventArgs - - -## Index - -### Properties - -* [_from](#_from) -* [_to](#_to) -* [_value](#_value) - -## Properties - -### _from - -• **_from**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:52](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L52)* - -___ - -### _to - -• **_to**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:53](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L53)* - -___ - -### _value - -• **_value**: *`BigNumber`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:54](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L54)* - -
- -# Interface: ERC721TokenApprovalEventArgs - - -## Index - -### Properties - -* [_approved](#_approved) -* [_owner](#_owner) -* [_tokenId](#_tokenid) - -## Properties - -### _approved - -• **_approved**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:51](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L51)* - -___ - -### _owner - -• **_owner**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:50](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L50)* - -___ - -### _tokenId - -• **_tokenId**: *`BigNumber`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:52](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L52)* - -
- -# Interface: ERC721TokenApprovalForAllEventArgs - - -## Index - -### Properties - -* [_approved](#_approved) -* [_operator](#_operator) -* [_owner](#_owner) - -## Properties - -### _approved - -• **_approved**: *boolean* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:58](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L58)* - -___ - -### _operator - -• **_operator**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:57](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L57)* - -___ - -### _owner - -• **_owner**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:56](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L56)* - -
- -# Interface: ERC721TokenTransferEventArgs - - -## Index - -### Properties - -* [_from](#_from) -* [_to](#_to) -* [_tokenId](#_tokenid) - -## Properties - -### _from - -• **_from**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:62](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L62)* - -___ - -### _to - -• **_to**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:63](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L63)* - -___ - -### _tokenId - -• **_tokenId**: *`BigNumber`* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:64](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L64)* - -
- -# Interface: ExchangeAssetProxyRegisteredEventArgs - - -## Index - -### Properties - -* [assetProxy](#assetproxy) -* [id](#id) - -## Properties - -### assetProxy - -• **assetProxy**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:63](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L63)* - -___ - -### id - -• **id**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:62](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L62)* - -
- -# Interface: ExchangeCancelEventArgs - - -## Index - -### Properties - -* [feeRecipientAddress](#feerecipientaddress) -* [makerAddress](#makeraddress) -* [makerAssetData](#makerassetdata) -* [orderHash](#orderhash) -* [senderAddress](#senderaddress) -* [takerAssetData](#takerassetdata) - -## Properties - -### feeRecipientAddress - -• **feeRecipientAddress**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:68](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L68)* - -___ - -### makerAddress - -• **makerAddress**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:67](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L67)* - -___ - -### makerAssetData - -• **makerAssetData**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:69](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L69)* - -___ - -### orderHash - -• **orderHash**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:72](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L72)* - -___ - -### senderAddress - -• **senderAddress**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:71](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L71)* - -___ - -### takerAssetData - -• **takerAssetData**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:70](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L70)* - -
- -# Interface: ExchangeCancelUpToEventArgs - - -## Index - -### Properties - -* [makerAddress](#makeraddress) -* [orderEpoch](#orderepoch) -* [orderSenderAddress](#ordersenderaddress) - -## Properties - -### makerAddress - -• **makerAddress**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:76](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L76)* - -___ - -### orderEpoch - -• **orderEpoch**: *`BigNumber`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:78](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L78)* - -___ - -### orderSenderAddress - -• **orderSenderAddress**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:77](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L77)* - -
- -# Interface: ExchangeFillEventArgs - - -## Index - -### Properties - -* [feeRecipientAddress](#feerecipientaddress) -* [makerAddress](#makeraddress) -* [makerAssetData](#makerassetdata) -* [makerAssetFilledAmount](#makerassetfilledamount) -* [makerFeeAssetData](#makerfeeassetdata) -* [makerFeePaid](#makerfeepaid) -* [orderHash](#orderhash) -* [protocolFeePaid](#protocolfeepaid) -* [senderAddress](#senderaddress) -* [takerAddress](#takeraddress) -* [takerAssetData](#takerassetdata) -* [takerAssetFilledAmount](#takerassetfilledamount) -* [takerFeeAssetData](#takerfeeassetdata) -* [takerFeePaid](#takerfeepaid) - -## Properties - -### feeRecipientAddress - -• **feeRecipientAddress**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:83](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L83)* - -___ - -### makerAddress - -• **makerAddress**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:82](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L82)* - -___ - -### makerAssetData - -• **makerAssetData**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:84](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L84)* - -___ - -### makerAssetFilledAmount - -• **makerAssetFilledAmount**: *`BigNumber`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:91](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L91)* - -___ - -### makerFeeAssetData - -• **makerFeeAssetData**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:86](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L86)* - -___ - -### makerFeePaid - -• **makerFeePaid**: *`BigNumber`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:93](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L93)* - -___ - -### orderHash - -• **orderHash**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:88](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L88)* - -___ - -### protocolFeePaid - -• **protocolFeePaid**: *`BigNumber`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:95](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L95)* - -___ - -### senderAddress - -• **senderAddress**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:90](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L90)* - -___ - -### takerAddress - -• **takerAddress**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:89](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L89)* - -___ - -### takerAssetData - -• **takerAssetData**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:85](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L85)* - -___ - -### takerAssetFilledAmount - -• **takerAssetFilledAmount**: *`BigNumber`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:92](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L92)* - -___ - -### takerFeeAssetData - -• **takerFeeAssetData**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:87](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L87)* - -___ - -### takerFeePaid - -• **takerFeePaid**: *`BigNumber`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:94](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L94)* - -
- -# Interface: ExchangeOwnershipTransferredEventArgs - - -## Index - -### Properties - -* [newOwner](#newowner) -* [previousOwner](#previousowner) - -## Properties - -### newOwner - -• **newOwner**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:100](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L100)* - -___ - -### previousOwner - -• **previousOwner**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:99](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L99)* - -
- -# Interface: ExchangeProtocolFeeCollectorAddressEventArgs - - -## Index - -### Properties - -* [oldProtocolFeeCollector](#oldprotocolfeecollector) -* [updatedProtocolFeeCollector](#updatedprotocolfeecollector) - -## Properties - -### oldProtocolFeeCollector - -• **oldProtocolFeeCollector**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:104](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L104)* - -___ - -### updatedProtocolFeeCollector - -• **updatedProtocolFeeCollector**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:105](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L105)* - -
- -# Interface: ExchangeProtocolFeeMultiplierEventArgs - - -## Index - -### Properties - -* [oldProtocolFeeMultiplier](#oldprotocolfeemultiplier) -* [updatedProtocolFeeMultiplier](#updatedprotocolfeemultiplier) - -## Properties - -### oldProtocolFeeMultiplier - -• **oldProtocolFeeMultiplier**: *`BigNumber`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:109](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L109)* - -___ - -### updatedProtocolFeeMultiplier - -• **updatedProtocolFeeMultiplier**: *`BigNumber`* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:110](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L110)* - -
- -# Interface: ExchangeSignatureValidatorApprovalEventArgs - - -## Index - -### Properties - -* [isApproved](#isapproved) -* [signerAddress](#signeraddress) -* [validatorAddress](#validatoraddress) - -## Properties - -### isApproved - -• **isApproved**: *boolean* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:116](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L116)* - -___ - -### signerAddress - -• **signerAddress**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:114](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L114)* - -___ - -### validatorAddress - -• **validatorAddress**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:115](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L115)* - -
- -# Interface: ExchangeTransactionExecutionEventArgs - - -## Index - -### Properties - -* [transactionHash](#transactionhash) - -## Properties - -### transactionHash - -• **transactionHash**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:120](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L120)* - -
- -# Interface: WETH9ApprovalEventArgs - - -## Index - -### Properties - -* [_owner](#_owner) -* [_spender](#_spender) -* [_value](#_value) - -## Properties - -### _owner - -• **_owner**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:52](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L52)* - -___ - -### _spender - -• **_spender**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:53](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L53)* - -___ - -### _value - -• **_value**: *`BigNumber`* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:54](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L54)* - -
- -# Interface: WETH9DepositEventArgs - - -## Index - -### Properties - -* [_owner](#_owner) -* [_value](#_value) - -## Properties - -### _owner - -• **_owner**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:58](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L58)* - -___ - -### _value - -• **_value**: *`BigNumber`* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:59](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L59)* - -
- -# Interface: WETH9TransferEventArgs - - -## Index - -### Properties - -* [_from](#_from) -* [_to](#_to) -* [_value](#_value) - -## Properties - -### _from - -• **_from**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:63](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L63)* - -___ - -### _to - -• **_to**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:64](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L64)* - -___ - -### _value - -• **_value**: *`BigNumber`* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:65](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L65)* - -
- -# Interface: WETH9WithdrawalEventArgs - - -## Index - -### Properties - -* [_owner](#_owner) -* [_value](#_value) - -## Properties - -### _owner - -• **_owner**: *string* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:69](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L69)* - -___ - -### _value - -• **_value**: *`BigNumber`* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:70](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L70)* - -
- - - -# Interface: BlockRange - - -## Properties - -### fromBlock - -• **fromBlock**: *[BlockParam](#blockparam)* - -*Defined in [ethereum-types/src/index.ts:759](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L759)* - -___ - -### toBlock - -• **toBlock**: *[BlockParam](#blockparam)* - -*Defined in [ethereum-types/src/index.ts:760](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L760)* - -
- - - - - -# Interface: CallData - - -## Properties - -### `Optional` data - -• **data**? : *undefined | string* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[data](#optional-data)* - -*Defined in [ethereum-types/src/index.ts:394](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L394)* - -___ - -### `Optional` from - -• **from**? : *undefined | string* - -*Defined in [ethereum-types/src/index.ts:411](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L411)* - -___ - -### `Optional` gas - -• **gas**? : *number | string | `BigNumber`* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[gas](#optional-gas)* - -*Defined in [ethereum-types/src/index.ts:392](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L392)* - -___ - -### `Optional` gasPrice - -• **gasPrice**? : *number | string | `BigNumber`* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[gasPrice](#optional-gasprice)* - -*Defined in [ethereum-types/src/index.ts:393](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L393)* - -___ - -### `Optional` nonce - -• **nonce**? : *undefined | number* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[nonce](#optional-nonce)* - -*Defined in [ethereum-types/src/index.ts:395](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L395)* - -___ - -### `Optional` overrides - -• **overrides**? : *[GethCallOverrides](#class-gethcalloverrides)* - -*Defined in [ethereum-types/src/index.ts:412](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L412)* - -___ - -### `Optional` to - -• **to**? : *undefined | string* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[to](#optional-to)* - -*Defined in [ethereum-types/src/index.ts:390](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L390)* - -___ - -### `Optional` value - -• **value**? : *number | string | `BigNumber`* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[value](#optional-value)* - -*Defined in [ethereum-types/src/index.ts:391](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L391)* - -
- - - - - -# Interface: CompilerOpts - - -## Properties - -### name - -• **name**: *"solc"* - -*Defined in [ethereum-types/src/index.ts:672](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L672)* - -___ - -### settings - -• **settings**: *[CompilerSettings](#class-compilersettings)* - -*Defined in [ethereum-types/src/index.ts:674](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L674)* - -___ - -### version - -• **version**: *string* - -*Defined in [ethereum-types/src/index.ts:673](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L673)* - -
- -# Interface: CompilerSettings - - -## Properties - -### `Optional` evmVersion - -• **evmVersion**? : *"homestead" | "tangerineWhistle" | "spuriousDragon" | "byzantium" | "constantinople"* - -*Defined in [ethereum-types/src/index.ts:706](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L706)* - -___ - -### `Optional` libraries - -• **libraries**? : *undefined | object* - -*Defined in [ethereum-types/src/index.ts:708](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L708)* - -___ - -### `Optional` metadata - -• **metadata**? : *[CompilerSettingsMetadata](#class-compilersettingsmetadata)* - -*Defined in [ethereum-types/src/index.ts:707](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L707)* - -___ - -### `Optional` optimizer - -• **optimizer**? : *[OptimizerSettings](#class-optimizersettings)* - -*Defined in [ethereum-types/src/index.ts:705](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L705)* - -___ - -### outputSelection - -• **outputSelection**: *object* - -*Defined in [ethereum-types/src/index.ts:713](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L713)* - -#### Type declaration: - -● \[▪ **fileName**: *string*\]: object - -● \[▪ **contractName**: *string*\]: [OutputField](#outputfield)[] - -___ - -### `Optional` remappings - -• **remappings**? : *string[]* - -*Defined in [ethereum-types/src/index.ts:704](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L704)* - -
- -# Interface: CompilerSettingsMetadata - - -## Properties - -### useLiteralContent - -• **useLiteralContent**: *true* - -*Defined in [ethereum-types/src/index.ts:721](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L721)* - -
- -# Interface: ConstructorAbi - - -## Properties - -### inputs - -• **inputs**: *[DataItem](#class-dataitem)[]* - -*Defined in [ethereum-types/src/index.ts:103](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L103)* - -___ - -### payable - -• **payable**: *boolean* - -*Defined in [ethereum-types/src/index.ts:104](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L104)* - -___ - -### stateMutability - -• **stateMutability**: *[ConstructorStateMutability](#constructorstatemutability)* - -*Defined in [ethereum-types/src/index.ts:105](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L105)* - -___ - -### type - -• **type**: *string* - -*Defined in [ethereum-types/src/index.ts:102](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L102)* - -
- -# Interface: ContractArtifact - -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 -chains: Chain specific information by chain (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 - - -## Properties - -### chains - -• **chains**: *[ContractChains](#class-contractchains)* - -*Defined in [ethereum-types/src/index.ts:693](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L693)* - -___ - -### compiler - -• **compiler**: *[CompilerOpts](#class-compileropts)* - -*Inherited from [ContractVersionData](#interface-contractversiondata).[compiler](#compiler)* - -*Defined in [ethereum-types/src/index.ts:658](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L658)* - -___ - -### compilerOutput - -• **compilerOutput**: *[StandardContractOutput](#class-standardcontractoutput)* - -*Inherited from [ContractVersionData](#interface-contractversiondata).[compilerOutput](#compileroutput)* - -*Defined in [ethereum-types/src/index.ts:668](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L668)* - -___ - -### contractName - -• **contractName**: *string* - -*Defined in [ethereum-types/src/index.ts:692](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L692)* - -___ - -### schemaVersion - -• **schemaVersion**: *string* - -*Defined in [ethereum-types/src/index.ts:691](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L691)* - -___ - -### sourceCodes - -• **sourceCodes**: *object* - -*Inherited from [ContractVersionData](#interface-contractversiondata).[sourceCodes](#sourcecodes)* - -*Defined in [ethereum-types/src/index.ts:664](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L664)* - -#### Type declaration: - -● \[▪ **sourceName**: *string*\]: string - -___ - -### sourceTreeHashHex - -• **sourceTreeHashHex**: *string* - -*Inherited from [ContractVersionData](#interface-contractversiondata).[sourceTreeHashHex](#sourcetreehashhex)* - -*Defined in [ethereum-types/src/index.ts:667](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L667)* - -___ - -### sources - -• **sources**: *object* - -*Inherited from [ContractVersionData](#interface-contractversiondata).[sources](#sources)* - -*Defined in [ethereum-types/src/index.ts:659](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L659)* - -#### Type declaration: - -● \[▪ **sourceName**: *string*\]: object - -
- -# Interface: ContractChainData - - -## Properties - -### address - -• **address**: *string* - -*Defined in [ethereum-types/src/index.ts:564](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L564)* - -___ - -Args - -• **constructorArgs**: *string* - -*Defined in [ethereum-types/src/index.ts:568](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L568)* - -___ - -### links - -• **links**: *object* - -*Defined in [ethereum-types/src/index.ts:565](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L565)* - -#### Type declaration: - -● \[▪ **linkName**: *string*\]: string - -
- -# Interface: ContractChains - - -## Hierarchy - -* **ContractVersionData** - - * [ContractArtifact](#class-contractartifact) - - -## Properties - -### compiler - -• **compiler**: *[CompilerOpts](#class-compileropts)* - -*Defined in [ethereum-types/src/index.ts:658](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L658)* - -___ - -### compilerOutput - -• **compilerOutput**: *[StandardContractOutput](#class-standardcontractoutput)* - -*Defined in [ethereum-types/src/index.ts:668](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L668)* - -___ - -### sourceCodes - -• **sourceCodes**: *object* - -*Defined in [ethereum-types/src/index.ts:664](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L664)* - -#### Type declaration: - -● \[▪ **sourceName**: *string*\]: string - -___ - -### sourceTreeHashHex - -• **sourceTreeHashHex**: *string* - -*Defined in [ethereum-types/src/index.ts:667](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L667)* - -___ - -### sources - -• **sources**: *object* - -*Defined in [ethereum-types/src/index.ts:659](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L659)* - -#### Type declaration: - -● \[▪ **sourceName**: *string*\]: object - -
- -# Interface: DataItem - - -## Properties - -### `Optional` components - -• **components**? : *[DataItem](#class-dataitem)[]* - -*Defined in [ethereum-types/src/index.ts:138](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L138)* - -___ - -### `Optional` internalType - -• **internalType**? : *undefined | string* - -*Defined in [ethereum-types/src/index.ts:137](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L137)* - -___ - -### name - -• **name**: *string* - -*Defined in [ethereum-types/src/index.ts:135](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L135)* - -___ - -### type - -• **type**: *string* - -*Defined in [ethereum-types/src/index.ts:136](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L136)* - -
- -# Interface: DecodedLogArgs - - -## Type parameters - -▪ **A** - - -## Properties - -### address - -• **address**: *string* - -*Inherited from [LogEntry](#interface-logentry).[address](#address)* - -*Defined in [ethereum-types/src/index.ts:444](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L444)* - -___ - -### args - -• **args**: *`A`* - -*Defined in [ethereum-types/src/index.ts:427](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L427)* - -___ - -### blockHash - -• **blockHash**: *string | null* - -*Inherited from [LogEntry](#interface-logentry).[blockHash](#blockhash)* - -*Defined in [ethereum-types/src/index.ts:442](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L442)* - -___ - -### blockNumber - -• **blockNumber**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[blockNumber](#blocknumber)* - -*Defined in [ethereum-types/src/index.ts:443](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L443)* - -___ - -### data - -• **data**: *string* - -*Inherited from [LogEntry](#interface-logentry).[data](#data)* - -*Defined in [ethereum-types/src/index.ts:445](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L445)* - -___ - -### event - -• **event**: *string* - -*Defined in [ethereum-types/src/index.ts:426](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L426)* - -___ - -### logIndex - -• **logIndex**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[logIndex](#logindex)* - -*Defined in [ethereum-types/src/index.ts:439](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L439)* - -___ - -### topics - -• **topics**: *string[]* - -*Inherited from [LogEntry](#interface-logentry).[topics](#topics)* - -*Defined in [ethereum-types/src/index.ts:446](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L446)* - -___ - -### transactionHash - -• **transactionHash**: *string* - -*Inherited from [LogEntry](#interface-logentry).[transactionHash](#transactionhash)* - -*Defined in [ethereum-types/src/index.ts:441](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L441)* - -___ - -### transactionIndex - -• **transactionIndex**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[transactionIndex](#transactionindex)* - -*Defined in [ethereum-types/src/index.ts:440](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L440)* - -
- - - -# Interface: DevdocOutput - - -## Properties - -### `Optional` author - -• **author**? : *undefined | string* - -*Defined in [ethereum-types/src/index.ts:645](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L645)* - -___ - -### methods - -• **methods**: *object* - -*Defined in [ethereum-types/src/index.ts:646](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L646)* - -#### Type declaration: - -● \[▪ **signature**: *string*\]: object - -___ - -### `Optional` title - -• **title**? : *undefined | string* - -*Defined in [ethereum-types/src/index.ts:644](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L644)* - -
- -# Interface: EIP1193Provider - - -## Properties - -### isEIP1193 - -• **isEIP1193**: *boolean* - -*Defined in [ethereum-types/src/index.ts:73](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L73)* - -## Methods - -### on - -▸ **on**(`event`: [EIP1193Event](#eip1193event), `listener`: function): *this* - -*Defined in [ethereum-types/src/index.ts:75](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L75)* - -**Parameters:** - -▪ **event**: *[EIP1193Event](#eip1193event)* - -▪ **listener**: *function* - -▸ (`result`: any): *void* - -**Parameters:** - -Name | Type | ------- | ------ | -`result` | any | - -**Returns:** *this* - -___ - -### send - -▸ **send**(`method`: string, `params?`: any[]): *`Promise`* - -*Defined in [ethereum-types/src/index.ts:74](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L74)* - -**Parameters:** - -Name | Type | ------- | ------ | -`method` | string | -`params?` | any[] | - -**Returns:** *`Promise`* - -
- - - - - -# Interface: EvmBytecodeOutput - - -## Properties - -### linkReferences - -• **linkReferences**: *[EvmBytecodeOutputLinkReferences](#class-evmbytecodeoutputlinkreferences)* - -*Defined in [ethereum-types/src/index.ts:632](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L632)* - -___ - -### object - -• **object**: *string* - -*Defined in [ethereum-types/src/index.ts:633](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L633)* - -___ - -### sourceMap - -• **sourceMap**: *string* - -*Defined in [ethereum-types/src/index.ts:634](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L634)* - -
- -# Interface: EvmBytecodeOutputLinkReferences - - -## Hierarchy - -* **EvmOutput** - - -## Properties - -### bytecode - -• **bytecode**: *[EvmBytecodeOutput](#class-evmbytecodeoutput)* - -*Defined in [ethereum-types/src/index.ts:627](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L627)* - -___ - -### deployedBytecode - -• **deployedBytecode**: *[EvmBytecodeOutput](#class-evmbytecodeoutput)* - -*Defined in [ethereum-types/src/index.ts:628](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L628)* - -
- -# Interface: FallbackAbi - - -## Properties - -### payable - -• **payable**: *boolean* - -*Defined in [ethereum-types/src/index.ts:112](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L112)* - -___ - -### type - -• **type**: *string* - -*Defined in [ethereum-types/src/index.ts:111](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L111)* - -
- - - -# Interface: GanacheProvider - - -## Methods - -### sendAsync - -▸ **sendAsync**(`payload`: [JSONRPCRequestPayload](_ethereum_types_src_index_.jsonrpcrequestpayload.md), `callback`: [JSONRPCErrorCallback](#jsonrpcerrorcallback)): *void* - -*Defined in [ethereum-types/src/index.ts:14](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L14)* - -**Parameters:** - -Name | Type | ------- | ------ | -`payload` | [JSONRPCRequestPayload](#class-jsonrpcrequestpayload) | -`callback` | [JSONRPCErrorCallback](#jsonrpcerrorcallback) | - -**Returns:** *void* - -
- - - -# Interface: GethCallOverrides - - -## Hierarchy - -* **JSONRPCRequestPayload** - - -## Properties - -### id - -• **id**: *number* - -*Defined in [ethereum-types/src/index.ts:331](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L331)* - -___ - -### jsonrpc - -• **jsonrpc**: *string* - -*Defined in [ethereum-types/src/index.ts:332](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L332)* - -___ - -### method - -• **method**: *string* - -*Defined in [ethereum-types/src/index.ts:330](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L330)* - -___ - -### params - -• **params**: *any[]* - -*Defined in [ethereum-types/src/index.ts:329](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L329)* - -
- -# Interface: JSONRPCResponseError - - -## Properties - -### code - -• **code**: *number* - -*Defined in [ethereum-types/src/index.ts:337](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L337)* - -___ - -### message - -• **message**: *string* - -*Defined in [ethereum-types/src/index.ts:336](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L336)* - -
- -# Interface: JSONRPCResponsePayload - - -## Properties - -### `Optional` error - -• **error**? : *[JSONRPCResponseError](#class-jsonrpcresponseerror)* - -*Defined in [ethereum-types/src/index.ts:344](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L344)* - -___ - -### id - -• **id**: *number* - -*Defined in [ethereum-types/src/index.ts:342](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L342)* - -___ - -### jsonrpc - -• **jsonrpc**: *string* - -*Defined in [ethereum-types/src/index.ts:343](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L343)* - -___ - -### result - -• **result**: *any* - -*Defined in [ethereum-types/src/index.ts:341](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L341)* - -
- - - - - -# Interface: LogWithDecodedArgs <**ArgsType**> - -## Type parameters - -▪ **ArgsType**: *[DecodedLogArgs](#class-decodedlogargs)* - - -## Properties - -### address - -• **address**: *string* - -*Inherited from [LogEntry](#interface-logentry).[address](#address)* - -*Defined in [ethereum-types/src/index.ts:444](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L444)* - -___ - -### args - -• **args**: *`ArgsType`* - -*Inherited from [DecodedLogEntry](#interface-decodedlogentry).[args](#args)* - -*Defined in [ethereum-types/src/index.ts:427](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L427)* - -___ - -### blockHash - -• **blockHash**: *string | null* - -*Inherited from [LogEntry](#interface-logentry).[blockHash](#blockhash)* - -*Defined in [ethereum-types/src/index.ts:442](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L442)* - -___ - -### blockNumber - -• **blockNumber**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[blockNumber](#blocknumber)* - -*Defined in [ethereum-types/src/index.ts:443](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L443)* - -___ - -### data - -• **data**: *string* - -*Inherited from [LogEntry](#interface-logentry).[data](#data)* - -*Defined in [ethereum-types/src/index.ts:445](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L445)* - -___ - -### event - -• **event**: *string* - -*Inherited from [DecodedLogEntry](#interface-decodedlogentry).[event](#event)* - -*Defined in [ethereum-types/src/index.ts:426](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L426)* - -___ - -### logIndex - -• **logIndex**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[logIndex](#logindex)* - -*Defined in [ethereum-types/src/index.ts:439](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L439)* - -___ - -### topics - -• **topics**: *string[]* - -*Inherited from [LogEntry](#interface-logentry).[topics](#topics)* - -*Defined in [ethereum-types/src/index.ts:446](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L446)* - -___ - -### transactionHash - -• **transactionHash**: *string* - -*Inherited from [LogEntry](#interface-logentry).[transactionHash](#transactionhash)* - -*Defined in [ethereum-types/src/index.ts:441](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L441)* - -___ - -### transactionIndex - -• **transactionIndex**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[transactionIndex](#transactionindex)* - -*Defined in [ethereum-types/src/index.ts:440](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L440)* - -
- -# Interface: MethodAbi - - -## Properties - -### `Optional` constant - -• **constant**? : *undefined | false | true* - -*Defined in [ethereum-types/src/index.ts:94](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L94)* - -___ - -### inputs - -• **inputs**: *[DataItem](#class-dataitem)[]* - -*Defined in [ethereum-types/src/index.ts:92](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L92)* - -___ - -### name - -• **name**: *string* - -*Defined in [ethereum-types/src/index.ts:91](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L91)* - -___ - -### outputs - -• **outputs**: *[DataItem](#class-dataitem)[]* - -*Defined in [ethereum-types/src/index.ts:93](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L93)* - -___ - -### `Optional` payable - -• **payable**? : *undefined | false | true* - -*Defined in [ethereum-types/src/index.ts:96](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L96)* - -___ - -### stateMutability - -• **stateMutability**: *[StateMutability](#statemutability)* - -*Defined in [ethereum-types/src/index.ts:95](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L95)* - -___ - -### type - -• **type**: *string* - -*Defined in [ethereum-types/src/index.ts:90](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L90)* - -
- -# Interface: OptimizerSettings - - -## Properties - -### enabled - -• **enabled**: *boolean* - -*Defined in [ethereum-types/src/index.ts:725](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L725)* - -___ - -### `Optional` runs - -• **runs**? : *undefined | number* - -*Defined in [ethereum-types/src/index.ts:726](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L726)* - -
- - - - - -# Interface: RevertErrorAbi - - -## Properties - -### `Optional` arguments - -• **arguments**? : *[DataItem](#class-dataitem)[]* - -*Defined in [ethereum-types/src/index.ts:122](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L122)* - -___ - -### name - -• **name**: *string* - -*Defined in [ethereum-types/src/index.ts:121](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L121)* - -___ - -### type - -• **type**: *"error"* - -*Defined in [ethereum-types/src/index.ts:120](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L120)* - -
- - - - - - - -# Interface: StandardContractOutput - - -## Properties - -### abi - -• **abi**: *[ContractAbi](#contractabi)* - -*Defined in [ethereum-types/src/index.ts:574](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L574)* - -___ - -### `Optional` devdoc - -• **devdoc**? : *[DevdocOutput](#class-devdocoutput)* - -*Defined in [ethereum-types/src/index.ts:576](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L576)* - -___ - -### evm - -• **evm**: *[EvmOutput](#class-evmoutput)* - -*Defined in [ethereum-types/src/index.ts:575](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L575)* - -
- - - - - - - - - - - - - - - -# Interface: TupleDataItem - - -## Properties - -### components - -• **components**: *[DataItem](#class-dataitem)[]* - -*Overrides [DataItem](_ethereum_types_src_index_.dataitem.md).[components](#optional-components)* - -*Defined in [ethereum-types/src/index.ts:142](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L142)* - -___ - -### `Optional` internalType - -• **internalType**? : *undefined | string* - -*Inherited from [DataItem](#interface-dataitem).[internalType](#optional-internaltype)* - -*Defined in [ethereum-types/src/index.ts:137](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L137)* - -___ - -### name - -• **name**: *string* - -*Inherited from [DataItem](#interface-dataitem).[name](#name)* - -*Defined in [ethereum-types/src/index.ts:135](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L135)* - -___ - -### type - -• **type**: *string* - -*Inherited from [DataItem](#interface-dataitem).[type](#type)* - -*Defined in [ethereum-types/src/index.ts:136](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L136)* - -
- -# Interface: TxData - - -## Properties - -### `Optional` data - -• **data**? : *undefined | string* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[data](#optional-data)* - -*Defined in [ethereum-types/src/index.ts:394](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L394)* - -___ - -### from - -• **from**: *string* - -*Defined in [ethereum-types/src/index.ts:399](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L399)* - -___ - -### `Optional` gas - -• **gas**? : *number | string | `BigNumber`* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[gas](#optional-gas)* - -*Defined in [ethereum-types/src/index.ts:392](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L392)* - -___ - -### `Optional` gasPrice - -• **gasPrice**? : *number | string | `BigNumber`* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[gasPrice](#optional-gasprice)* - -*Defined in [ethereum-types/src/index.ts:393](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L393)* - -___ - -### `Optional` nonce - -• **nonce**? : *undefined | number* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[nonce](#optional-nonce)* - -*Defined in [ethereum-types/src/index.ts:395](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L395)* - -___ - -### `Optional` to - -• **to**? : *undefined | string* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[to](#optional-to)* - -*Defined in [ethereum-types/src/index.ts:390](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L390)* - -___ - -### `Optional` value - -• **value**? : *number | string | `BigNumber`* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[value](#optional-value)* - -*Defined in [ethereum-types/src/index.ts:391](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L391)* - -
- -# Interface: TxDataPayable - - -## Properties - -### `Optional` data - -• **data**? : *undefined | string* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[data](#optional-data)* - -*Defined in [ethereum-types/src/index.ts:394](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L394)* - -___ - -### from - -• **from**: *string* - -*Inherited from [TxData](#interface-txdata).[from](#from)* - -*Defined in [ethereum-types/src/index.ts:399](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L399)* - -___ - -### `Optional` gas - -• **gas**? : *number | string | `BigNumber`* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[gas](#optional-gas)* - -*Defined in [ethereum-types/src/index.ts:392](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L392)* - -___ - -### `Optional` gasPrice - -• **gasPrice**? : *number | string | `BigNumber`* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[gasPrice](#optional-gasprice)* - -*Defined in [ethereum-types/src/index.ts:393](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L393)* - -___ - -### `Optional` nonce - -• **nonce**? : *undefined | number* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[nonce](#optional-nonce)* - -*Defined in [ethereum-types/src/index.ts:395](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L395)* - -___ - -### `Optional` to - -• **to**? : *undefined | string* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[to](#optional-to)* - -*Defined in [ethereum-types/src/index.ts:390](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L390)* - -___ - -### `Optional` value - -• **value**? : *`BigNumber`* - -*Overrides [CallTxDataBase](_ethereum_types_src_index_.calltxdatabase.md).[value](#optional-value)* - -*Defined in [ethereum-types/src/index.ts:452](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L452)* - -
- -# Interface: Web3JsV1Provider - -Web3.js version 1 provider interface -This provider interface was implemented in the pre-1.0Beta releases for Web3.js. -This interface allowed sending synchonous requests, support for which was later dropped. - - -## Methods - -### send - -▸ **send**(`payload`: [JSONRPCRequestPayload](_ethereum_types_src_index_.jsonrpcrequestpayload.md)): *[JSONRPCResponsePayload](#class-jsonrpcresponsepayload)* - -*Defined in [ethereum-types/src/index.ts:45](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L45)* - -**Parameters:** - -Name | Type | ------- | ------ | -`payload` | [JSONRPCRequestPayload](#class-jsonrpcrequestpayload) | - -**Returns:** *[JSONRPCResponsePayload](#class-jsonrpcresponsepayload)* - -___ - -### sendAsync - -▸ **sendAsync**(`payload`: [JSONRPCRequestPayload](_ethereum_types_src_index_.jsonrpcrequestpayload.md), `callback`: [JSONRPCErrorCallback](#jsonrpcerrorcallback)): *void* - -*Defined in [ethereum-types/src/index.ts:44](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L44)* - -**Parameters:** - -Name | Type | ------- | ------ | -`payload` | [JSONRPCRequestPayload](#class-jsonrpcrequestpayload) | -`callback` | [JSONRPCErrorCallback](#jsonrpcerrorcallback) | - -**Returns:** *void* - -
- -# Interface: Web3JsV2Provider - -Web3.js version 2 provider interface -This provider interface was used in a couple of Web3.js 1.0 beta releases -before the first attempts to conform to EIP1193 - - -## Methods - -### send - -▸ **send**(`payload`: [JSONRPCRequestPayload](_ethereum_types_src_index_.jsonrpcrequestpayload.md), `callback`: [JSONRPCErrorCallback](#jsonrpcerrorcallback)): *void* - -*Defined in [ethereum-types/src/index.ts:54](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L54)* - -**Parameters:** - -Name | Type | ------- | ------ | -`payload` | [JSONRPCRequestPayload](#class-jsonrpcrequestpayload) | -`callback` | [JSONRPCErrorCallback](#jsonrpcerrorcallback) | - -**Returns:** *void* - -
- -# Interface: Web3JsV3Provider - -Web3.js version 3 provider interface -This provider interface was implemented with the hopes for conforming to the EIP1193 spec, -however it does not conform entirely. - - -## Methods - -### send - -▸ **send**(`method`: string, `params?`: any[]): *`Promise`* - -*Defined in [ethereum-types/src/index.ts:63](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L63)* - -**Parameters:** - -Name | Type | ------- | ------ | -`method` | string | -`params?` | any[] | - -**Returns:** *`Promise`* - -
- -# Interface: ZeroExProvider - -The interface for the provider used internally by 0x libraries -Any property we use from any SupportedProvider should we explicitly -add here - - -## Properties - -### `Optional` isMetaMask - -• **isMetaMask**? : *undefined | false | true* - -*Defined in [ethereum-types/src/index.ts:31](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L31)* - -___ - -### `Optional` isParity - -• **isParity**? : *undefined | false | true* - -*Defined in [ethereum-types/src/index.ts:32](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L32)* - -___ - -### `Optional` isZeroExProvider - -• **isZeroExProvider**? : *undefined | false | true* - -*Defined in [ethereum-types/src/index.ts:30](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L30)* - -## Methods - -### `Optional` enable - -▸ **enable**(): *`Promise`* - -*Defined in [ethereum-types/src/index.ts:34](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L34)* - -**Returns:** *`Promise`* - -___ - -### sendAsync - -▸ **sendAsync**(`payload`: [JSONRPCRequestPayload](_ethereum_types_src_index_.jsonrpcrequestpayload.md), `callback`: [JSONRPCErrorCallback](#jsonrpcerrorcallback)): *void* - -*Defined in [ethereum-types/src/index.ts:35](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L35)* - -**Parameters:** - -Name | Type | ------- | ------ | -`payload` | [JSONRPCRequestPayload](#class-jsonrpcrequestpayload) | -`callback` | [JSONRPCErrorCallback](#jsonrpcerrorcallback) | - -**Returns:** *void* - -___ - -### `Optional` stop - -▸ **stop**(): *void* - -*Defined in [ethereum-types/src/index.ts:33](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L33)* - -**Returns:** *void* - -
- - - - - -# Class: DevUtilsContract - - -## Constructors - - - -\+ **new DevUtilsContract**(`address`: string, `supportedProvider`: [SupportedProvider](#supportedprovider), `txDefaults?`: `Partial`, `logDecodeDependencies?`: undefined | object, `deployedBytecode`: string | undefined): *[DevUtilsContract](#class-devutilscontract)* - -*Overrides void* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:3257](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L3257)* - -**Parameters:** - -Name | Type | Default | ------- | ------ | ------ | -`address` | string | - | -`supportedProvider` | [SupportedProvider](#supportedprovider) | - | -`txDefaults?` | `Partial` | - | -`logDecodeDependencies?` | undefined \| object | - | -`deployedBytecode` | string \| undefined | DevUtilsContract.deployedBytecode | - -**Returns:** *[DevUtilsContract](#class-devutilscontract)* - -## Properties - -### `Optional` _deployedBytecodeIfExists - -• **_deployedBytecodeIfExists**? : *`Buffer`* - - - -Defined in base-contract/lib/src/index.d.ts:34 - -___ - -### abi - -• **abi**: *[ContractAbi](#contractabi)* - - - -Defined in base-contract/lib/src/index.d.ts:30 - -___ - -### address - -• **address**: *string* - - - -Defined in base-contract/lib/src/index.d.ts:31 - -___ - -Args - -• **constructorArgs**: *any[]* - - - -Defined in base-contract/lib/src/index.d.ts:33 - -___ - -### contractName - -• **contractName**: *string* - - - -Defined in base-contract/lib/src/index.d.ts:32 - -___ - -### `Static` contractName - -▪ **contractName**: *string* = "DevUtils" - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:46](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L46)* - -## Methods - -### EIP712_EXCHANGE_DOMAIN_HASH - -▸ **EIP712_EXCHANGE_DOMAIN_HASH**(): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:1597](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L1597)* - -**Returns:** *`ContractFunctionObj`* - -___ - -### chaiBridgeAddress - -▸ **chaiBridgeAddress**(): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:1617](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L1617)* - -**Returns:** *`ContractFunctionObj`* - -___ - -### decodeAssetProxyId - -▸ **decodeAssetProxyId**(`assetData`: string): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:1643](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L1643)* - -Decode AssetProxy identifier - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`assetData` | string | AssetProxy-compliant asset data describing an ERC-20, ERC- 721, ERC1155, or MultiAsset asset. | - -**Returns:** *`ContractFunctionObj`* - -The AssetProxy identifier - -___ - -### decodeERC1155AssetData - -▸ **decodeERC1155AssetData**(`assetData`: string): *`ContractFunctionObj<[string, string, BigNumber[], BigNumber[], string]>`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:1675](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L1675)* - -Decode ERC-1155 asset data from the format described in the AssetProxy contract specification. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`assetData` | string | AssetProxy-compliant asset data describing an ERC-1155 set of assets. | - -**Returns:** *`ContractFunctionObj<[string, string, BigNumber[], BigNumber[], string]>`* - -The ERC-1155 AssetProxy identifier, the address of the ERC-1155 contract hosting the assets, an array of the identifiers of the assets to be traded, an array of asset amounts to be traded, and callback data. Each element of the arrays corresponds to the same-indexed element of the other array. Return values specified as `memory` are returned as pointers to locations within the memory of the input parameter `assetData`. - -___ - -### decodeERC20AssetData - -▸ **decodeERC20AssetData**(`assetData`: string): *`ContractFunctionObj<[string, string]>`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:1713](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L1713)* - -Decode ERC-20 asset data from the format described in the AssetProxy contract specification. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`assetData` | string | AssetProxy-compliant asset data describing an ERC-20 asset. | - -**Returns:** *`ContractFunctionObj<[string, string]>`* - -The AssetProxy identifier, and the address of the ERC-20 contract hosting this asset. - -___ - -### decodeERC20BridgeAssetData - -▸ **decodeERC20BridgeAssetData**(`assetData`: string): *`ContractFunctionObj<[string, string, string, string]>`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:1745](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L1745)* - -Decode ERC20Bridge asset data from the format described in the AssetProxy contract specification. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`assetData` | string | AssetProxy-compliant asset data describing an ERC20Bridge asset | - -**Returns:** *`ContractFunctionObj<[string, string, string, string]>`* - -The ERC20BridgeProxy identifier, the address of the ERC20 token to transfer, the address of the bridge contract, and extra data to be passed to the bridge contract. - -___ - -### decodeERC721AssetData - -▸ **decodeERC721AssetData**(`assetData`: string): *`ContractFunctionObj<[string, string, BigNumber]>`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:1780](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L1780)* - -Decode ERC-721 asset data from the format described in the AssetProxy contract specification. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`assetData` | string | AssetProxy-compliant asset data describing an ERC-721 asset. | - -**Returns:** *`ContractFunctionObj<[string, string, BigNumber]>`* - -The ERC-721 AssetProxy identifier, the address of the ERC-721 contract hosting this asset, and the identifier of the specific asset to be traded. - -___ - -### decodeMultiAssetData - -▸ **decodeMultiAssetData**(`assetData`: string): *`ContractFunctionObj<[string, BigNumber[], string[]]>`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:1814](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L1814)* - -Decode multi-asset data from the format described in the AssetProxy contract specification. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`assetData` | string | AssetProxy-compliant data describing a multi-asset basket. | - -**Returns:** *`ContractFunctionObj<[string, BigNumber[], string[]]>`* - -The Multi-Asset AssetProxy identifier, an array of the amounts of the assets to be traded, and an array of the AssetProxy-compliant data describing each asset to be traded. Each element of the arrays corresponds to the same-indexed element of the other array. - -___ - -### decodeStaticCallAssetData - -▸ **decodeStaticCallAssetData**(`assetData`: string): *`ContractFunctionObj<[string, string, string, string]>`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:1849](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L1849)* - -Decode StaticCall asset data from the format described in the AssetProxy contract specification. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`assetData` | string | AssetProxy-compliant asset data describing a StaticCall asset | - -**Returns:** *`ContractFunctionObj<[string, string, string, string]>`* - -The StaticCall AssetProxy identifier, the target address of the StaticCAll, the data to be passed to the target address, and the expected Keccak-256 hash of the static call return data. - -___ - -### decodeZeroExTransactionData - -▸ **decodeZeroExTransactionData**(`transactionData`: string): *`ContractFunctionObj<[string, Array, BigNumber[], string[]]>`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:1884](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L1884)* - -Decodes the call data for an Exchange contract method call. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`transactionData` | string | ABI-encoded calldata for an Exchange contract method call. | - -**Returns:** *`ContractFunctionObj<[string, Array, BigNumber[], string[]]>`* - -The name of the function called, and the parameters it was given. For single-order fills and cancels, the arrays will have just one element. - -___ - -### dydxBridgeAddress - -▸ **dydxBridgeAddress**(): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:1981](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L1981)* - -**Returns:** *`ContractFunctionObj`* - -___ - -### encodeERC1155AssetData - -▸ **encodeERC1155AssetData**(`tokenAddress`: string, `tokenIds`: `BigNumber`[], `tokenValues`: `BigNumber`[], `callbackData`: string): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:2011](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L2011)* - -Encode ERC-1155 asset data into the format described in the AssetProxy contract specification. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`tokenAddress` | string | The address of the ERC-1155 contract hosting the asset(s) to be traded. | -`tokenIds` | `BigNumber`[] | The identifiers of the specific assets to be traded. | -`tokenValues` | `BigNumber`[] | The amounts of each asset to be traded. | -`callbackData` | string | Data to be passed to receiving contracts when a transfer is performed. | - -**Returns:** *`ContractFunctionObj`* - -AssetProxy-compliant asset data describing the set of assets. - -___ - -### encodeERC20AssetData - -▸ **encodeERC20AssetData**(`tokenAddress`: string): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:2056](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L2056)* - -Encode ERC-20 asset data into the format described in the AssetProxy contract specification. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`tokenAddress` | string | The address of the ERC-20 contract hosting the asset to be traded. | - -**Returns:** *`ContractFunctionObj`* - -AssetProxy-compliant data describing the asset. - -___ - -### encodeERC721AssetData - -▸ **encodeERC721AssetData**(`tokenAddress`: string, `tokenId`: `BigNumber`): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:2089](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L2089)* - -Encode ERC-721 asset data into the format described in the AssetProxy specification. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`tokenAddress` | string | The address of the ERC-721 contract hosting the asset to be traded. | -`tokenId` | `BigNumber` | The identifier of the specific asset to be traded. | - -**Returns:** *`ContractFunctionObj`* - -AssetProxy-compliant asset data describing the asset. - -___ - -### encodeMultiAssetData - -▸ **encodeMultiAssetData**(`amounts`: `BigNumber`[], `nestedAssetData`: string[]): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:2123](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L2123)* - -Encode data for multiple assets, per the AssetProxy contract specification. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`amounts` | `BigNumber`[] | The amounts of each asset to be traded. | -`nestedAssetData` | string[] | AssetProxy-compliant data describing each asset to be traded. | - -**Returns:** *`ContractFunctionObj`* - -AssetProxy-compliant data describing the set of assets. - -___ - -### encodeStaticCallAssetData - -▸ **encodeStaticCallAssetData**(`staticCallTargetAddress`: string, `staticCallData`: string, `expectedReturnDataHash`: string): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:2159](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L2159)* - -Encode StaticCall asset data into the format described in the AssetProxy contract specification. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`staticCallTargetAddress` | string | Target address of StaticCall. | -`staticCallData` | string | Data that will be passed to staticCallTargetAddress in the StaticCall. | -`expectedReturnDataHash` | string | Expected Keccak-256 hash of the StaticCall return data. | - -**Returns:** *`ContractFunctionObj`* - -AssetProxy-compliant asset data describing the set of assets. - -___ - -### erc1155ProxyAddress - -▸ **erc1155ProxyAddress**(): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:2195](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L2195)* - -**Returns:** *`ContractFunctionObj`* - -___ - -### erc20ProxyAddress - -▸ **erc20ProxyAddress**(): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:2215](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L2215)* - -**Returns:** *`ContractFunctionObj`* - -___ - -### erc721ProxyAddress - -▸ **erc721ProxyAddress**(): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:2235](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L2235)* - -**Returns:** *`ContractFunctionObj`* - -___ - -### exchangeAddress - -▸ **exchangeAddress**(): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:2255](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L2255)* - -**Returns:** *`ContractFunctionObj`* - -___ - -### getABIDecodedReturnData - -▸ **getABIDecodedReturnData**<**T**>(`methodName`: string, `callData`: string): *`T`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:1582](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L1582)* - -**Type parameters:** - -▪ **T** - -**Parameters:** - -Name | Type | ------- | ------ | -`methodName` | string | -`callData` | string | - -**Returns:** *`T`* - -___ - -### getABIDecodedTransactionData - -▸ **getABIDecodedTransactionData**<**T**>(`methodName`: string, `callData`: string): *`T`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:1574](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L1574)* - -**Type parameters:** - -▪ **T** - -**Parameters:** - -Name | Type | ------- | ------ | -`methodName` | string | -`callData` | string | - -**Returns:** *`T`* - -___ - -### getAssetProxyAllowance - -▸ **getAssetProxyAllowance**(`ownerAddress`: string, `assetData`: string): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:2282](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L2282)* - -Returns the number of asset(s) (described by assetData) that the corresponding AssetProxy contract is authorized to spend. When the asset data contains multiple assets (eg for Multi-Asset), the return value indicates how many complete "baskets" of those assets may be spent by all of the corresponding AssetProxy contracts. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`ownerAddress` | string | Owner of the assets specified by assetData. | -`assetData` | string | Details of asset, encoded per the AssetProxy contract specification. | - -**Returns:** *`ContractTxFunctionObj`* - -Number of assets (or asset baskets) that the corresponding AssetProxy is authorized to spend. - -___ - -### getBalance - -▸ **getBalance**(`ownerAddress`: string, `assetData`: string): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:2337](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L2337)* - -Returns the owner's balance of the assets(s) specified in assetData. When the asset data contains multiple assets (eg in ERC1155 or Multi-Asset), the return value indicates how many complete "baskets" of those assets are owned by owner. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`ownerAddress` | string | Owner of the assets specified by assetData. | -`assetData` | string | Details of asset, encoded per the AssetProxy contract specification. | - -**Returns:** *`ContractTxFunctionObj`* - -Number of assets (or asset baskets) held by owner. - -___ - -### getBalanceAndAssetProxyAllowance - -▸ **getBalanceAndAssetProxyAllowance**(`ownerAddress`: string, `assetData`: string): *`ContractTxFunctionObj<[BigNumber, BigNumber]>`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:2392](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L2392)* - -Calls getBalance() and getAllowance() for assetData. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`ownerAddress` | string | Owner of the assets specified by assetData. | -`assetData` | string | Details of asset, encoded per the AssetProxy contract specification. | - -**Returns:** *`ContractTxFunctionObj<[BigNumber, BigNumber]>`* - -Number of assets (or asset baskets) held by owner, and number of assets (or asset baskets) that the corresponding AssetProxy is authorized to spend. - -___ - -### getBatchAssetProxyAllowances - -▸ **getBatchAssetProxyAllowances**(`ownerAddress`: string, `assetData`: string[]): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:2453](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L2453)* - -Calls getAssetProxyAllowance() for each element of assetData. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`ownerAddress` | string | Owner of the assets specified by assetData. | -`assetData` | string[] | Array of asset details, each encoded per the AssetProxy contract specification. | - -**Returns:** *`ContractTxFunctionObj`* - -An array of asset allowances from getAllowance(), with each element corresponding to the same-indexed element in the assetData input. - -___ - -### getBatchBalances - -▸ **getBatchBalances**(`ownerAddress`: string, `assetData`: string[]): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:2508](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L2508)* - -Calls getBalance() for each element of assetData. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`ownerAddress` | string | Owner of the assets specified by assetData. | -`assetData` | string[] | Array of asset details, each encoded per the AssetProxy contract specification. | - -**Returns:** *`ContractTxFunctionObj`* - -Array of asset balances from getBalance(), with each element corresponding to the same-indexed element in the assetData input. - -___ - -### getBatchBalancesAndAssetProxyAllowances - -▸ **getBatchBalancesAndAssetProxyAllowances**(`ownerAddress`: string, `assetData`: string[]): *`ContractTxFunctionObj<[BigNumber[], BigNumber[]]>`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:2563](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L2563)* - -Calls getBatchBalances() and getBatchAllowances() for each element of assetData. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`ownerAddress` | string | Owner of the assets specified by assetData. | -`assetData` | string[] | Array of asset details, each encoded per the AssetProxy contract specification. | - -**Returns:** *`ContractTxFunctionObj<[BigNumber[], BigNumber[]]>`* - -An array of asset balances from getBalance(), and an array of asset allowances from getAllowance(), with each element corresponding to the same-indexed element in the assetData input. - -___ - -### getEthBalances - -▸ **getEthBalances**(`addresses`: string[]): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:2622](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L2622)* - -Batch fetches ETH balances - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`addresses` | string[] | Array of addresses. | - -**Returns:** *`ContractFunctionObj`* - -Array of ETH balances. - -___ - -### getFunctionSignature - -▸ **getFunctionSignature**(`methodName`: string): *string* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:1567](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L1567)* - -**Parameters:** - -Name | Type | ------- | ------ | -`methodName` | string | - -**Returns:** *string* - -___ - -### getOrderHash - -▸ **getOrderHash**(`order`: object, `chainId`: `BigNumber`, `exchange`: string): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:2643](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L2643)* - -**Parameters:** - -Name | Type | ------- | ------ | -`order` | object | -`chainId` | `BigNumber` | -`exchange` | string | - -**Returns:** *`ContractFunctionObj`* - -___ - -### getOrderRelevantState - -▸ **getOrderRelevantState**(`order`: object, `signature`: string): *`ContractTxFunctionObj<[object, BigNumber, boolean]>`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:2699](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L2699)* - -Fetches all order-relevant information needed to validate if the supplied order is fillable. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`order` | object | The order structure. | -`signature` | string | Signature provided by maker that proves the order's authenticity. `0x01` can always be provided if the signature does not need to be validated. | - -**Returns:** *`ContractTxFunctionObj<[object, BigNumber, boolean]>`* - -The orderInfo (hash, status, and `takerAssetAmount` already filled for the given order), fillableTakerAssetAmount (amount of the order's `takerAssetAmount` that is fillable given all on-chain state), and isValidSignature (validity of the provided signature). NOTE: If the `takerAssetData` encodes data for multiple assets, `fillableTakerAssetAmount` will represent a "scaled" amount, meaning it must be multiplied by all the individual asset amounts within the `takerAssetData` to get the final amount of each asset that can be filled. - -___ - -### getOrderRelevantStates - -▸ **getOrderRelevantStates**(`orders`: `Array`, `signatures`: string[]): *`ContractTxFunctionObj<[Array, BigNumber[], boolean[]]>`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:2787](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L2787)* - -Fetches all order-relevant information needed to validate if the supplied orders are fillable. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`orders` | `Array` | Array of order structures. | -`signatures` | string[] | Array of signatures provided by makers that prove the authenticity of the orders. `0x01` can always be provided if a signature does not need to be validated. | - -**Returns:** *`ContractTxFunctionObj<[Array, BigNumber[], boolean[]]>`* - -The ordersInfo (array of the hash, status, and `takerAssetAmount` already filled for each order), fillableTakerAssetAmounts (array of amounts for each order's `takerAssetAmount` that is fillable given all on-chain state), and isValidSignature (array containing the validity of each provided signature). NOTE: If the `takerAssetData` encodes data for multiple assets, each element of `fillableTakerAssetAmounts` will represent a "scaled" amount, meaning it must be multiplied by all the individual asset amounts within the `takerAssetData` to get the final amount of each asset that can be filled. - -___ - -### getSelector - -▸ **getSelector**(`methodName`: string): *string* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:1590](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L1590)* - -**Parameters:** - -Name | Type | ------- | ------ | -`methodName` | string | - -**Returns:** *string* - -___ - -### getSimulatedOrderMakerTransferResults - -▸ **getSimulatedOrderMakerTransferResults**(`order`: object, `takerAddress`: string, `takerAssetFillAmount`: `BigNumber`): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:2883](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L2883)* - -Simulates the maker transfers within an order and returns the index of the first failed transfer. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`order` | object | The order to simulate transfers for. | -`takerAddress` | string | The address of the taker that will fill the order. | -`takerAssetFillAmount` | `BigNumber` | The amount of takerAsset that the taker wished to fill. | - -**Returns:** *`ContractTxFunctionObj`* - -The index of the first failed transfer (or 4 if all transfers are successful). - -___ - -### getSimulatedOrderTransferResults - -▸ **getSimulatedOrderTransferResults**(`order`: object, `takerAddress`: string, `takerAssetFillAmount`: `BigNumber`): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:2964](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L2964)* - -Simulates all of the transfers within an order and returns the index of the first failed transfer. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`order` | object | The order to simulate transfers for. | -`takerAddress` | string | The address of the taker that will fill the order. | -`takerAssetFillAmount` | `BigNumber` | The amount of takerAsset that the taker wished to fill. | - -**Returns:** *`ContractTxFunctionObj`* - -The index of the first failed transfer (or 4 if all transfers are successful). - -___ - -### getSimulatedOrdersTransferResults - -▸ **getSimulatedOrdersTransferResults**(`orders`: `Array`, `takerAddresses`: string[], `takerAssetFillAmounts`: `BigNumber`[]): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:3046](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L3046)* - -Simulates all of the transfers for each given order and returns the indices of each first failed transfer. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`orders` | `Array` | Array of orders to individually simulate transfers for. | -`takerAddresses` | string[] | Array of addresses of takers that will fill each order. | -`takerAssetFillAmounts` | `BigNumber`[] | Array of amounts of takerAsset that will be filled for each order. | - -**Returns:** *`ContractTxFunctionObj`* - -The indices of the first failed transfer (or 4 if all transfers are successful) for each order. - -___ - -### getTransactionHash - -▸ **getTransactionHash**(`transaction`: object, `chainId`: `BigNumber`, `exchange`: string): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:3115](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L3115)* - -**Parameters:** - -Name | Type | ------- | ------ | -`transaction` | object | -`chainId` | `BigNumber` | -`exchange` | string | - -**Returns:** *`ContractFunctionObj`* - -___ - -### getTransferableAssetAmount - -▸ **getTransferableAssetAmount**(`ownerAddress`: string, `assetData`: string): *`ContractTxFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:3160](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L3160)* - -Gets the amount of an asset transferable by the maker of an order. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`ownerAddress` | string | Address of the owner of the asset. | -`assetData` | string | Description of tokens, per the AssetProxy contract specification. | - -**Returns:** *`ContractTxFunctionObj`* - -The amount of the asset tranferable by the owner. NOTE: If the `assetData` encodes data for multiple assets, the `transferableAssetAmount` will represent the amount of times the entire `assetData` can be transferred. To calculate the total individual transferable amounts, this scaled `transferableAmount` must be multiplied by the individual asset amounts located within the `assetData`. - -___ - -### revertIfInvalidAssetData - -▸ **revertIfInvalidAssetData**(`assetData`: string): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:3212](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L3212)* - -Reverts if assetData is not of a valid format for its given proxy id. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`assetData` | string | AssetProxy compliant asset data. | - -**Returns:** *`ContractFunctionObj`* - -___ - -### staticCallProxyAddress - -▸ **staticCallProxyAddress**(): *`ContractFunctionObj`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:3238](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L3238)* - -**Returns:** *`ContractFunctionObj`* - -___ - -### `Static` ABI - -▸ **ABI**(): *[ContractAbi](#contractabi)* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:182](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L182)* - -**Returns:** *[ContractAbi](#contractabi)* - -The contract ABI - -___ - -### `Static` deployAsync - -▸ **deployAsync**(`bytecode`: string, `abi`: [ContractAbi](#contractabi), `supportedProvider`: [SupportedProvider](#supportedprovider), `txDefaults`: `Partial`, `logDecodeDependencies`: object, `exchange_`: string, `chaiBridge_`: string, `dydxBridge_`: string): *`Promise`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:131](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L131)* - -**Parameters:** - -Name | Type | ------- | ------ | -`bytecode` | string | -`abi` | [ContractAbi](#contractabi) | -`supportedProvider` | [SupportedProvider](#supportedprovider) | -`txDefaults` | `Partial` | -`logDecodeDependencies` | object | -`exchange_` | string | -`chaiBridge_` | string | -`dydxBridge_` | string | - -**Returns:** *`Promise`* - -___ - -### `Static` deployFrom0xArtifactAsync - -▸ **deployFrom0xArtifactAsync**(`artifact`: `ContractArtifact` | `SimpleContractArtifact`, `supportedProvider`: [SupportedProvider](#supportedprovider), `txDefaults`: `Partial`, `logDecodeDependencies`: object, `exchange_`: string, `chaiBridge_`: string, `dydxBridge_`: string): *`Promise`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:48](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L48)* - -**Parameters:** - -Name | Type | ------- | ------ | -`artifact` | `ContractArtifact` \| `SimpleContractArtifact` | -`supportedProvider` | [SupportedProvider](#supportedprovider) | -`txDefaults` | `Partial` | -`logDecodeDependencies` | object | -`exchange_` | string | -`chaiBridge_` | string | -`dydxBridge_` | string | - -**Returns:** *`Promise`* - -___ - -### `Static` deployWithLibrariesFrom0xArtifactAsync - -▸ **deployWithLibrariesFrom0xArtifactAsync**(`artifact`: `ContractArtifact`, `libraryArtifacts`: object, `supportedProvider`: [SupportedProvider](#supportedprovider), `txDefaults`: `Partial`, `logDecodeDependencies`: object, `exchange_`: string, `chaiBridge_`: string, `dydxBridge_`: string): *`Promise`* - -*Defined in [contract-wrappers/src/generated-wrappers/dev_utils.ts:86](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/dev_utils.ts#L86)* - -**Parameters:** - -Name | Type | ------- | ------ | -`artifact` | `ContractArtifact` | -`libraryArtifacts` | object | -`supportedProvider` | [SupportedProvider](#supportedprovider) | -`txDefaults` | `Partial` | -`logDecodeDependencies` | object | -`exchange_` | string | -`chaiBridge_` | string | -`dydxBridge_` | string | - -**Returns:** *`Promise`* - -___ - -### `Static` strictArgumentEncodingCheck - -▸ **strictArgumentEncodingCheck**(`inputAbi`: `DataItem`[], `args`: any[]): *string* - - - -Defined in base-contract/lib/src/index.d.ts:44 - -**Parameters:** - -Name | Type | ------- | ------ | -`inputAbi` | `DataItem`[] | -`args` | any[] | - -**Returns:** *string* - -
- -# Interface: JSONRPCRequestPayloadWithMethod - - -## Properties - -### id - -• **id**: *number* - - - -Defined in ethereum-types/lib/index.d.ts:268 - -___ - -### jsonrpc - -• **jsonrpc**: *string* - - - -Defined in ethereum-types/lib/index.d.ts:269 - -___ - -### method - -• **method**: *string* - -*Overrides void* - -*Defined in [subproviders/src/types.ts:136](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/subproviders/src/types.ts#L136)* - -___ - -### params - -• **params**: *any[]* - - - -Defined in ethereum-types/lib/index.d.ts:266 - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# Interface: DecodedLogEvent <**ArgsType**> - -## Type parameters - -▪ **ArgsType**: *`DecodedLogArgs`* - - -## Properties - -### isRemoved - -• **isRemoved**: *boolean* - -*Defined in [types/src/index.ts:872](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L872)* - -___ - -### log - -• **log**: *`LogWithDecodedArgs`* - -*Defined in [types/src/index.ts:873](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L873)* - -
- - - - - - - -# Interface: ECSignature - -Elliptic Curve signature - - -## Properties - -### r - -• **r**: *string* - -*Defined in [types/src/index.ts:86](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L86)* - -___ - -### s - -• **s**: *string* - -*Defined in [types/src/index.ts:87](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L87)* - -___ - -### v - -• **v**: *number* - -*Defined in [types/src/index.ts:85](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L85)* - -
- -# Interface: EIP712DomainWithDefaultSchema - - -## Properties - -### chainId - -• **chainId**: *number* - -*Defined in [types/src/index.ts:821](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L821)* - -___ - -### `Optional` name - -• **name**? : *undefined | string* - -*Defined in [types/src/index.ts:819](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L819)* - -___ - -### verifyingContract - -• **verifyingContract**: *string* - -*Defined in [types/src/index.ts:822](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L822)* - -___ - -### `Optional` version - -• **version**? : *undefined | string* - -*Defined in [types/src/index.ts:820](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L820)* - -
- - - - - - - -# Interface: ERC1155AssetData - - -## Properties - -### assetProxyId - -• **assetProxyId**: *string* - -*Defined in [types/src/index.ts:214](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L214)* - -___ - -### callbackData - -• **callbackData**: *string* - -*Defined in [types/src/index.ts:218](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L218)* - -___ - -### tokenAddress - -• **tokenAddress**: *string* - -*Defined in [types/src/index.ts:215](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L215)* - -___ - -### tokenIds - -• **tokenIds**: *`BigNumber`[]* - -*Defined in [types/src/index.ts:216](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L216)* - -___ - -### tokenValues - -• **tokenValues**: *`BigNumber`[]* - -*Defined in [types/src/index.ts:217](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L217)* - -
- - - -# Interface: ERC20AssetData - - -## Properties - -### assetProxyId - -• **assetProxyId**: *string* - -*Defined in [types/src/index.ts:196](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L196)* - -___ - -### tokenAddress - -• **tokenAddress**: *string* - -*Defined in [types/src/index.ts:197](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L197)* - -
- -# Interface: ERC20BridgeAssetData - - -## Properties - -### assetProxyId - -• **assetProxyId**: *string* - -*Defined in [types/src/index.ts:201](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L201)* - -___ - -### bridgeAddress - -• **bridgeAddress**: *string* - -*Defined in [types/src/index.ts:203](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L203)* - -___ - -### bridgeData - -• **bridgeData**: *string* - -*Defined in [types/src/index.ts:204](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L204)* - -___ - -### tokenAddress - -• **tokenAddress**: *string* - -*Defined in [types/src/index.ts:202](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L202)* - -
- -# Interface: ERC721AssetData - - -## Properties - -### assetProxyId - -• **assetProxyId**: *string* - -*Defined in [types/src/index.ts:208](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L208)* - -___ - -### tokenAddress - -• **tokenAddress**: *string* - -*Defined in [types/src/index.ts:209](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L209)* - -___ - -### tokenId - -• **tokenId**: *`BigNumber`* - -*Defined in [types/src/index.ts:210](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L210)* - -
- - - - - -# Interface: ExchangeProxyMetaTransaction - -Exchange Proxy meta transaction struct. - - -## Properties - -### callData - -• **callData**: *string* - -*Defined in [types/src/index.ts:67](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L67)* - -___ - -### domain - -• **domain**: *[EIP712DomainWithDefaultSchema](#class-eip712domainwithdefaultschema)* - -*Defined in [types/src/index.ts:71](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L71)* - -___ - -### expirationTimeSeconds - -• **expirationTimeSeconds**: *`BigNumber`* - -*Defined in [types/src/index.ts:65](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L65)* - -___ - -### feeAmount - -• **feeAmount**: *`BigNumber`* - -*Defined in [types/src/index.ts:70](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L70)* - -___ - -### feeToken - -• **feeToken**: *string* - -*Defined in [types/src/index.ts:69](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L69)* - -___ - -### maxGasPrice - -• **maxGasPrice**: *`BigNumber`* - -*Defined in [types/src/index.ts:64](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L64)* - -___ - -### minGasPrice - -• **minGasPrice**: *`BigNumber`* - -*Defined in [types/src/index.ts:63](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L63)* - -___ - -### salt - -• **salt**: *`BigNumber`* - -*Defined in [types/src/index.ts:66](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L66)* - -___ - -### sender - -• **sender**: *string* - -*Defined in [types/src/index.ts:62](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L62)* - -___ - -### signer - -• **signer**: *string* - -*Defined in [types/src/index.ts:61](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L61)* - -___ - -### value - -• **value**: *`BigNumber`* - -*Defined in [types/src/index.ts:68](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L68)* - -
- - - - - - - -# Interface: IndexedFilterValues - - -## Hierarchy - -* **IndexSignature** - - -## Properties - -### keyName - -• **keyName**: *string* - -*Defined in [types/src/index.ts:719](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L719)* - -___ - -### keyType - -• **keyType**: *[Type](#class-type)* - -*Defined in [types/src/index.ts:720](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L720)* - -___ - -### valueName - -• **valueName**: *string* - -*Defined in [types/src/index.ts:721](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L721)* - -
- - - - - -# Interface: MultiAssetData - - -## Properties - -### amounts - -• **amounts**: *`BigNumber`[]* - -*Defined in [types/src/index.ts:244](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L244)* - -___ - -### assetProxyId - -• **assetProxyId**: *string* - -*Defined in [types/src/index.ts:243](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L243)* - -___ - -### nestedAssetData - -• **nestedAssetData**: *string[]* - -*Defined in [types/src/index.ts:245](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L245)* - -
- -# Interface: MultiAssetDataWithRecursiveDecoding - - -## Properties - -### amounts - -• **amounts**: *`BigNumber`[]* - -*Defined in [types/src/index.ts:250](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L250)* - -___ - -### assetProxyId - -• **assetProxyId**: *string* - -*Defined in [types/src/index.ts:249](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L249)* - -___ - -### nestedAssetData - -• **nestedAssetData**: *[SingleAssetData](#singleassetdata)[]* - -*Defined in [types/src/index.ts:251](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L251)* - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# Interface: SignedExchangeProxyMetaTransaction - -`ExchangeProxyMetaTransaction` with `signature` field. - - -## Properties - -### callData - -• **callData**: *string* - -*Inherited from [ExchangeProxyMetaTransaction](#interface-exchangeproxymetatransaction).[callData](#calldata)* - -*Defined in [types/src/index.ts:67](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L67)* - -___ - -### domain - -• **domain**: *[EIP712DomainWithDefaultSchema](#class-eip712domainwithdefaultschema)* - -*Inherited from [ExchangeProxyMetaTransaction](#interface-exchangeproxymetatransaction).[domain](#domain)* - -*Defined in [types/src/index.ts:71](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L71)* - -___ - -### expirationTimeSeconds - -• **expirationTimeSeconds**: *`BigNumber`* - -*Inherited from [ExchangeProxyMetaTransaction](#interface-exchangeproxymetatransaction).[expirationTimeSeconds](#expirationtimeseconds)* - -*Defined in [types/src/index.ts:65](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L65)* - -___ - -### feeAmount - -• **feeAmount**: *`BigNumber`* - -*Inherited from [ExchangeProxyMetaTransaction](#interface-exchangeproxymetatransaction).[feeAmount](#feeamount)* - -*Defined in [types/src/index.ts:70](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L70)* - -___ - -### feeToken - -• **feeToken**: *string* - -*Inherited from [ExchangeProxyMetaTransaction](#interface-exchangeproxymetatransaction).[feeToken](#feetoken)* - -*Defined in [types/src/index.ts:69](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L69)* - -___ - -### maxGasPrice - -• **maxGasPrice**: *`BigNumber`* - -*Inherited from [ExchangeProxyMetaTransaction](#interface-exchangeproxymetatransaction).[maxGasPrice](#maxgasprice)* - -*Defined in [types/src/index.ts:64](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L64)* - -___ - -### minGasPrice - -• **minGasPrice**: *`BigNumber`* - -*Inherited from [ExchangeProxyMetaTransaction](#interface-exchangeproxymetatransaction).[minGasPrice](#mingasprice)* - -*Defined in [types/src/index.ts:63](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L63)* - -___ - -### salt - -• **salt**: *`BigNumber`* - -*Inherited from [ExchangeProxyMetaTransaction](#interface-exchangeproxymetatransaction).[salt](#salt)* - -*Defined in [types/src/index.ts:66](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L66)* - -___ - -### sender - -• **sender**: *string* - -*Inherited from [ExchangeProxyMetaTransaction](#interface-exchangeproxymetatransaction).[sender](#sender)* - -*Defined in [types/src/index.ts:62](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L62)* - -___ - -### signature - -• **signature**: *string* - -*Defined in [types/src/index.ts:78](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L78)* - -___ - -### signer - -• **signer**: *string* - -*Inherited from [ExchangeProxyMetaTransaction](#interface-exchangeproxymetatransaction).[signer](#signer)* - -*Defined in [types/src/index.ts:61](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L61)* - -___ - -### value - -• **value**: *`BigNumber`* - -*Inherited from [ExchangeProxyMetaTransaction](#interface-exchangeproxymetatransaction).[value](#value)* - -*Defined in [types/src/index.ts:68](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L68)* - -
- -# Interface: SignedOrder - - -## Properties - -### chainId - -• **chainId**: *number* - -*Inherited from [Order](#interface-order).[chainId](#chainid)* - -*Defined in [types/src/index.ts:14](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L14)* - -___ - -### exchangeAddress - -• **exchangeAddress**: *string* - -*Inherited from [Order](#interface-order).[exchangeAddress](#exchangeaddress)* - -*Defined in [types/src/index.ts:15](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L15)* - -___ - -### expirationTimeSeconds - -• **expirationTimeSeconds**: *`BigNumber`* - -*Inherited from [Order](#interface-order).[expirationTimeSeconds](#expirationtimeseconds)* - -*Defined in [types/src/index.ts:24](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L24)* - -___ - -### feeRecipientAddress - -• **feeRecipientAddress**: *string* - -*Inherited from [Order](#interface-order).[feeRecipientAddress](#feerecipientaddress)* - -*Defined in [types/src/index.ts:18](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L18)* - -___ - -### makerAddress - -• **makerAddress**: *string* - -*Inherited from [Order](#interface-order).[makerAddress](#makeraddress)* - -*Defined in [types/src/index.ts:16](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L16)* - -___ - -### makerAssetAmount - -• **makerAssetAmount**: *`BigNumber`* - -*Inherited from [Order](#interface-order).[makerAssetAmount](#makerassetamount)* - -*Defined in [types/src/index.ts:20](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L20)* - -___ - -### makerAssetData - -• **makerAssetData**: *string* - -*Inherited from [Order](#interface-order).[makerAssetData](#makerassetdata)* - -*Defined in [types/src/index.ts:26](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L26)* - -___ - -### makerFee - -• **makerFee**: *`BigNumber`* - -*Inherited from [Order](#interface-order).[makerFee](#makerfee)* - -*Defined in [types/src/index.ts:22](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L22)* - -___ - -### makerFeeAssetData - -• **makerFeeAssetData**: *string* - -*Inherited from [Order](#interface-order).[makerFeeAssetData](#makerfeeassetdata)* - -*Defined in [types/src/index.ts:28](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L28)* - -___ - -### salt - -• **salt**: *`BigNumber`* - -*Inherited from [Order](#interface-order).[salt](#salt)* - -*Defined in [types/src/index.ts:25](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L25)* - -___ - -### senderAddress - -• **senderAddress**: *string* - -*Inherited from [Order](#interface-order).[senderAddress](#senderaddress)* - -*Defined in [types/src/index.ts:19](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L19)* - -___ - -### signature - -• **signature**: *string* - -*Defined in [types/src/index.ts:33](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L33)* - -___ - -### takerAddress - -• **takerAddress**: *string* - -*Inherited from [Order](#interface-order).[takerAddress](#takeraddress)* - -*Defined in [types/src/index.ts:17](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L17)* - -___ - -### takerAssetAmount - -• **takerAssetAmount**: *`BigNumber`* - -*Inherited from [Order](#interface-order).[takerAssetAmount](#takerassetamount)* - -*Defined in [types/src/index.ts:21](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L21)* - -___ - -### takerAssetData - -• **takerAssetData**: *string* - -*Inherited from [Order](#interface-order).[takerAssetData](#takerassetdata)* - -*Defined in [types/src/index.ts:27](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L27)* - -___ - -### takerFee - -• **takerFee**: *`BigNumber`* - -*Inherited from [Order](#interface-order).[takerFee](#takerfee)* - -*Defined in [types/src/index.ts:23](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L23)* - -___ - -### takerFeeAssetData - -• **takerFeeAssetData**: *string* - -*Inherited from [Order](#interface-order).[takerFeeAssetData](#takerfeeassetdata)* - -*Defined in [types/src/index.ts:29](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L29)* - -
- -# Interface: SignedZeroExTransaction - - -## Properties - -### data - -• **data**: *string* - -*Inherited from [ZeroExTransaction](#interface-zeroextransaction).[data](#data)* - -*Defined in [types/src/index.ts:49](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L49)* - -___ - -### domain - -• **domain**: *[EIP712DomainWithDefaultSchema](#class-eip712domainwithdefaultschema)* - -*Inherited from [ZeroExTransaction](#interface-zeroextransaction).[domain](#domain)* - -*Defined in [types/src/index.ts:50](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L50)* - -___ - -### expirationTimeSeconds - -• **expirationTimeSeconds**: *`BigNumber`* - -*Inherited from [ZeroExTransaction](#interface-zeroextransaction).[expirationTimeSeconds](#expirationtimeseconds)* - -*Defined in [types/src/index.ts:46](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L46)* - -___ - -### gasPrice - -• **gasPrice**: *`BigNumber`* - -*Inherited from [ZeroExTransaction](#interface-zeroextransaction).[gasPrice](#gasprice)* - -*Defined in [types/src/index.ts:47](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L47)* - -___ - -### salt - -• **salt**: *`BigNumber`* - -*Inherited from [ZeroExTransaction](#interface-zeroextransaction).[salt](#salt)* - -*Defined in [types/src/index.ts:45](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L45)* - -___ - -### signature - -• **signature**: *string* - -*Defined in [types/src/index.ts:54](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L54)* - -___ - -### signerAddress - -• **signerAddress**: *string* - -*Inherited from [ZeroExTransaction](#interface-zeroextransaction).[signerAddress](#signeraddress)* - -*Defined in [types/src/index.ts:48](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L48)* - -
- -# Interface: SimpleContractArtifact - - -## Properties - -### chains - -• **chains**: *`ContractChains`* - -*Defined in [types/src/index.ts:889](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L889)* - -___ - -### compilerOutput - -• **compilerOutput**: *[SimpleStandardContractOutput](#class-simplestandardcontractoutput)* - -*Defined in [types/src/index.ts:888](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L888)* - -___ - -### contractName - -• **contractName**: *string* - -*Defined in [types/src/index.ts:887](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L887)* - -___ - -### schemaVersion - -• **schemaVersion**: *string* - -*Defined in [types/src/index.ts:886](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L886)* - -
- -# Interface: SimpleEvmBytecodeOutput - - -## Properties - -### object - -• **object**: *string* - -*Defined in [types/src/index.ts:903](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L903)* - -
- -# Interface: SimpleEvmOutput - - -## Properties - -### bytecode - -• **bytecode**: *[SimpleEvmBytecodeOutput](#class-simpleevmbytecodeoutput)* - -*Defined in [types/src/index.ts:899](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L899)* - -
- -# Interface: SimpleStandardContractOutput - - -## Properties - -### abi - -• **abi**: *[ContractAbi](#contractabi)* - -*Defined in [types/src/index.ts:893](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L893)* - -___ - -### `Optional` devdoc - -• **devdoc**? : *[DevdocOutput](#class-devdocoutput)* - -*Defined in [types/src/index.ts:895](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L895)* - -___ - -### evm - -• **evm**: *[SimpleEvmOutput](#class-simpleevmoutput)* - -*Defined in [types/src/index.ts:894](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L894)* - -
- - - - - -# Interface: StaticCallAssetData - - -## Properties - -### assetProxyId - -• **assetProxyId**: *string* - -*Defined in [types/src/index.ts:222](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L222)* - -___ - -### callResultHash - -• **callResultHash**: *string* - -*Defined in [types/src/index.ts:225](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L225)* - -___ - -### callTarget - -• **callTarget**: *string* - -*Defined in [types/src/index.ts:223](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L223)* - -___ - -### staticCallData - -• **staticCallData**: *string* - -*Defined in [types/src/index.ts:224](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L224)* - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -# Interface: ValidatorSignature - -Validator signature components - - -## Properties - -### signature - -• **signature**: *string* - -*Defined in [types/src/index.ts:95](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L95)* - -___ - -### validatorAddress - -• **validatorAddress**: *string* - -*Defined in [types/src/index.ts:94](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L94)* - -
- -# Interface: ZeroExTransaction - -ZeroExTransaction for use with 0x Exchange executeTransaction - - -## Properties - -### data - -• **data**: *string* - -*Defined in [types/src/index.ts:49](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L49)* - -___ - -### domain - -• **domain**: *[EIP712DomainWithDefaultSchema](#class-eip712domainwithdefaultschema)* - -*Defined in [types/src/index.ts:50](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L50)* - -___ - -### expirationTimeSeconds - -• **expirationTimeSeconds**: *`BigNumber`* - -*Defined in [types/src/index.ts:46](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L46)* - -___ - -### gasPrice - -• **gasPrice**: *`BigNumber`* - -*Defined in [types/src/index.ts:47](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L47)* - -___ - -### salt - -• **salt**: *`BigNumber`* - -*Defined in [types/src/index.ts:45](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L45)* - -___ - -### signerAddress - -• **signerAddress**: *string* - -*Defined in [types/src/index.ts:48](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L48)* - -
- - - - -## Type aliases - - - -### AssetData - -Ƭ **AssetData**: *[SingleAssetData](_types_src_index_.md#singleassetdata) | [MultiAssetData](#interface-multiassetdata) | [MultiAssetDataWithRecursiveDecoding](#interface-multiassetdatawithrecursivedecoding)* - -*Defined in [types/src/index.ts:260](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L260)* - -___ - - - - - - - -### EventCallback - -Ƭ **EventCallback**: *function* - -*Defined in [types/src/index.ts:876](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L876)* - -#### Type declaration: - -▸ (`err`: null | `Error`, `log?`: [DecodedLogEvent](#interface-decodedlogevent)‹*`ArgsType`*›): *void* - -**Parameters:** - -Name | Type | ------- | ------ | -`err` | null \| `Error` | -`log?` | [DecodedLogEvent](#interface-decodedlogevent)‹*`ArgsType`*› | - -___ - - - - - - - - - -### SingleAssetData - -Ƭ **SingleAssetData**: *[ERC20AssetData](#interface-erc20assetdata) | [ERC20BridgeAssetData](#interface-erc20bridgeassetdata) | [ERC721AssetData](#interface-erc721assetdata) | [ERC1155AssetData](#interface-erc1155assetdata) | [StaticCallAssetData](#interface-staticcallassetdata)* - -*Defined in [types/src/index.ts:235](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/types/src/index.ts#L235)* - -
- - - - -## Type aliases - - - - - - -## Functions - -### getContractAddressesForChainOrThrow - -▸ **getContractAddressesForChainOrThrow**(`chainId`: [ChainId](#enumeration-chainid)): *[ContractAddresses](#interface-contractaddresses)* - -*Defined in [contract-addresses/src/index.ts:67](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-addresses/src/index.ts#L67)* - -Used to get addresses of contracts that have been deployed to either the -Ethereum mainnet or a supported testnet. Throws if there are no known -contracts deployed on the corresponding chain. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`chainId` | [ChainId](#enumeration-chainid) | The desired chainId. | - -**Returns:** *[ContractAddresses](#interface-contractaddresses)* - -The set of addresses for contracts which have been deployed on the -given chainId. - -
- - - -
- - - - -## Type aliases - -### ERC20TokenEventArgs - -Ƭ **ERC20TokenEventArgs**: *[ERC20TokenApprovalEventArgs](#interface-erc20tokenapprovaleventargs) | [ERC20TokenTransferEventArgs](#interface-erc20tokentransfereventargs)* - -*Defined in [contract-wrappers/src/generated-wrappers/erc20_token.ts:38](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts#L38)* - -
- - - - -## Type aliases - -### ERC721TokenEventArgs - -Ƭ **ERC721TokenEventArgs**: *[ERC721TokenApprovalEventArgs](#interface-erc721tokenapprovaleventargs) | [ERC721TokenApprovalForAllEventArgs](#interface-erc721tokenapprovalforalleventargs) | [ERC721TokenTransferEventArgs](#interface-erc721tokentransfereventargs)* - -*Defined in [contract-wrappers/src/generated-wrappers/erc721_token.ts:38](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts#L38)* - -
- - - - -## Type aliases - -### ExchangeEventArgs - -Ƭ **ExchangeEventArgs**: *[ExchangeAssetProxyRegisteredEventArgs](#interface-exchangeassetproxyregisteredeventargs) | [ExchangeCancelEventArgs](#interface-exchangecanceleventargs) | [ExchangeCancelUpToEventArgs](#interface-exchangecanceluptoeventargs) | [ExchangeFillEventArgs](#interface-exchangefilleventargs) | [ExchangeOwnershipTransferredEventArgs](#interface-exchangeownershiptransferredeventargs) | [ExchangeProtocolFeeCollectorAddressEventArgs](#interface-exchangeprotocolfeecollectoraddresseventargs) | [ExchangeProtocolFeeMultiplierEventArgs](#interface-exchangeprotocolfeemultipliereventargs) | [ExchangeSignatureValidatorApprovalEventArgs](#interface-exchangesignaturevalidatorapprovaleventargs) | [ExchangeTransactionExecutionEventArgs](#interface-exchangetransactionexecutioneventargs)* - -*Defined in [contract-wrappers/src/generated-wrappers/exchange.ts:38](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/exchange.ts#L38)* - -
- - - - -## Type aliases - -### WETH9EventArgs - -Ƭ **WETH9EventArgs**: *[WETH9ApprovalEventArgs](#interface-weth9approvaleventargs) | [WETH9DepositEventArgs](#interface-weth9depositeventargs) | [WETH9TransferEventArgs](#interface-weth9transfereventargs) | [WETH9WithdrawalEventArgs](#interface-weth9withdrawaleventargs)* - -*Defined in [contract-wrappers/src/generated-wrappers/weth9.ts:38](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/contract-wrappers/src/generated-wrappers/weth9.ts#L38)* - -
- - - - -## Type aliases - -### AbiDefinition - -Ƭ **AbiDefinition**: *[FunctionAbi](_ethereum_types_src_index_.md#functionabi) | [EventAbi](#interface-eventabi) | [RevertErrorAbi](#interface-reverterrorabi)* - -*Defined in [ethereum-types/src/index.ts:80](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L80)* - -___ - -### BlockParam - -Ƭ **BlockParam**: *[BlockParamLiteral](#enumeration-blockparamliteral) | number* - -*Defined in [ethereum-types/src/index.ts:493](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L493)* - -___ - -### ConstructorStateMutability - -Ƭ **ConstructorStateMutability**: *"nonpayable" | "payable"* - -*Defined in [ethereum-types/src/index.ts:84](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L84)* - -___ - -### ContractAbi - -Ƭ **ContractAbi**: *[AbiDefinition](#abidefinition)[]* - -*Defined in [ethereum-types/src/index.ts:78](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L78)* - -___ - -### ContractEventArg - -Ƭ **ContractEventArg**: *any* - -*Defined in [ethereum-types/src/index.ts:478](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L478)* - -___ - - - -### EIP1193Event - -Ƭ **EIP1193Event**: *"accountsChanged" | "networkChanged" | "close" | "connect" | "notification"* - -*Defined in [ethereum-types/src/index.ts:70](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L70)* - -Interface for providers that conform to EIP 1193 -Source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md - -___ - - - - - -### FunctionAbi - -Ƭ **FunctionAbi**: *[MethodAbi](#interface-methodabi) | [ConstructorAbi](#interface-constructorabi) | [FallbackAbi](#interface-fallbackabi)* - -*Defined in [ethereum-types/src/index.ts:82](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L82)* - -___ - -### JSONRPCErrorCallback - -Ƭ **JSONRPCErrorCallback**: *function* - -*Defined in [ethereum-types/src/index.ts:3](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L3)* - -#### Type declaration: - -▸ (`err`: `Error` | null, `result?`: [JSONRPCResponsePayload](#interface-jsonrpcresponsepayload)): *void* - -**Parameters:** - -Name | Type | ------- | ------ | -`err` | `Error` \| null | -`result?` | [JSONRPCResponsePayload](#interface-jsonrpcresponsepayload) | - -___ - - - -### OutputField - -Ƭ **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"* - -*Defined in [ethereum-types/src/index.ts:535](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L535)* - -___ - -### ParamDescription - -Ƭ **ParamDescription**: *string* - -*Defined in [ethereum-types/src/index.ts:571](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L571)* - -___ - - - -### StateMutability - -Ƭ **StateMutability**: *"pure" | "view" | [ConstructorStateMutability](#constructorstatemutability)* - -*Defined in [ethereum-types/src/index.ts:85](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L85)* - -___ - -### SupportedProvider - -Ƭ **SupportedProvider**: *[Web3JsProvider](_ethereum_types_src_index_.md#web3jsprovider) | [GanacheProvider](#interface-ganacheprovider) | [EIP1193Provider](#interface-eip1193provider) | [ZeroExProvider](#interface-zeroexprovider)* - -*Defined in [ethereum-types/src/index.ts:9](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L9)* - -Do not create your own provider. Use an existing provider from a Web3 or ProviderEngine library -Read more about Providers in the guides section of the 0x docs. - -___ - - - - - -### Web3JsProvider - -Ƭ **Web3JsProvider**: *[Web3JsV1Provider](#interface-web3jsv1provider) | [Web3JsV2Provider](#interface-web3jsv2provider) | [Web3JsV3Provider](#interface-web3jsv3provider)* - -*Defined in [ethereum-types/src/index.ts:11](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/ethereum-types/src/index.ts#L11)* - -
- - - - -## Object literals - -### `Const` assetDataUtils - -#### ▪ **assetDataUtils**: *object* - -*Defined in [order-utils/src/asset_data_utils.ts:20](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/asset_data_utils.ts#L20)* - -#### decodeAssetDataOrThrow - -▸ **decodeAssetDataOrThrow**(`assetData`: string): *[AssetData](#assetdata)* - -*Defined in [order-utils/src/asset_data_utils.ts:57](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/asset_data_utils.ts#L57)* - -Decode any assetData into its corresponding assetData object - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`assetData` | string | Hex encoded assetData string to decode | - -**Returns:** *[AssetData](#assetdata)* - -Either a ERC20, ERC20Bridge, ERC721, ERC1155, StaticCall, or MultiAsset assetData object - -#### decodeMultiAssetDataRecursively - -▸ **decodeMultiAssetDataRecursively**(`assetData`: string): *`MultiAssetDataWithRecursiveDecoding`* - -*Defined in [order-utils/src/asset_data_utils.ts:138](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/asset_data_utils.ts#L138)* - -Decodes a MultiAsset assetData hex string into its corresponding amounts and decoded nestedAssetData elements (all nested elements are flattened) - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`assetData` | string | Hex encoded assetData string to decode | - -**Returns:** *`MultiAssetDataWithRecursiveDecoding`* - -An object containing the decoded amounts and nestedAssetData - -#### encodeERC1155AssetData - -▸ **encodeERC1155AssetData**(`tokenAddress`: string, `tokenIds`: `BigNumber`[], `tokenValues`: `BigNumber`[], `callbackData`: string): *string* - -*Defined in [order-utils/src/asset_data_utils.ts:30](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/asset_data_utils.ts#L30)* - -**Parameters:** - -Name | Type | ------- | ------ | -`tokenAddress` | string | -`tokenIds` | `BigNumber`[] | -`tokenValues` | `BigNumber`[] | -`callbackData` | string | - -**Returns:** *string* - -#### encodeERC20AssetData - -▸ **encodeERC20AssetData**(`tokenAddress`: string): *string* - -*Defined in [order-utils/src/asset_data_utils.ts:21](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/asset_data_utils.ts#L21)* - -**Parameters:** - -Name | Type | ------- | ------ | -`tokenAddress` | string | - -**Returns:** *string* - -#### encodeERC20BridgeAssetData - -▸ **encodeERC20BridgeAssetData**(`tokenAddress`: string, `bridgeAddress`: string, `bridgeData`: string): *string* - -*Defined in [order-utils/src/asset_data_utils.ts:24](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/asset_data_utils.ts#L24)* - -**Parameters:** - -Name | Type | ------- | ------ | -`tokenAddress` | string | -`bridgeAddress` | string | -`bridgeData` | string | - -**Returns:** *string* - -#### encodeERC721AssetData - -▸ **encodeERC721AssetData**(`tokenAddress`: string, `tokenId`: `BigNumber`): *string* - -*Defined in [order-utils/src/asset_data_utils.ts:27](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/asset_data_utils.ts#L27)* - -**Parameters:** - -Name | Type | ------- | ------ | -`tokenAddress` | string | -`tokenId` | `BigNumber` | - -**Returns:** *string* - -#### encodeMultiAssetData - -▸ **encodeMultiAssetData**(`values`: `BigNumber`[], `nestedAssetData`: string[]): *string* - -*Defined in [order-utils/src/asset_data_utils.ts:40](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/asset_data_utils.ts#L40)* - -**Parameters:** - -Name | Type | ------- | ------ | -`values` | `BigNumber`[] | -`nestedAssetData` | string[] | - -**Returns:** *string* - -#### encodeStaticCallAssetData - -▸ **encodeStaticCallAssetData**(`staticCallTargetAddress`: string, `staticCallData`: string, `expectedReturnDataHash`: string): *string* - -*Defined in [order-utils/src/asset_data_utils.ts:43](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/asset_data_utils.ts#L43)* - -**Parameters:** - -Name | Type | ------- | ------ | -`staticCallTargetAddress` | string | -`staticCallData` | string | -`expectedReturnDataHash` | string | - -**Returns:** *string* - -#### isERC1155TokenAssetData - -▸ **isERC1155TokenAssetData**(`assetData`: [AssetData](#assetdata)): *boolean* - -*Defined in [order-utils/src/asset_data_utils.ts:176](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/asset_data_utils.ts#L176)* - -**Parameters:** - -Name | Type | ------- | ------ | -`assetData` | [AssetData](#assetdata) | - -**Returns:** *boolean* - -#### isERC20BridgeAssetData - -▸ **isERC20BridgeAssetData**(`assetData`: [AssetData](#assetdata)): *boolean* - -*Defined in [order-utils/src/asset_data_utils.ts:173](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/asset_data_utils.ts#L173)* - -**Parameters:** - -Name | Type | ------- | ------ | -`assetData` | [AssetData](#assetdata) | - -**Returns:** *boolean* - -#### isERC20TokenAssetData - -▸ **isERC20TokenAssetData**(`assetData`: [AssetData](#assetdata)): *boolean* - -*Defined in [order-utils/src/asset_data_utils.ts:170](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/asset_data_utils.ts#L170)* - -**Parameters:** - -Name | Type | ------- | ------ | -`assetData` | [AssetData](#assetdata) | - -**Returns:** *boolean* - -#### isERC721TokenAssetData - -▸ **isERC721TokenAssetData**(`assetData`: [AssetData](#assetdata)): *boolean* - -*Defined in [order-utils/src/asset_data_utils.ts:179](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/asset_data_utils.ts#L179)* - -**Parameters:** - -Name | Type | ------- | ------ | -`assetData` | [AssetData](#assetdata) | - -**Returns:** *boolean* - -#### isMultiAssetData - -▸ **isMultiAssetData**(`assetData`: [AssetData](#assetdata)): *boolean* - -*Defined in [order-utils/src/asset_data_utils.ts:182](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/asset_data_utils.ts#L182)* - -**Parameters:** - -Name | Type | ------- | ------ | -`assetData` | [AssetData](#assetdata) | - -**Returns:** *boolean* - -#### isStaticCallAssetData - -▸ **isStaticCallAssetData**(`assetData`: [AssetData](#assetdata)): *boolean* - -*Defined in [order-utils/src/asset_data_utils.ts:185](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/asset_data_utils.ts#L185)* - -**Parameters:** - -Name | Type | ------- | ------ | -`assetData` | [AssetData](#assetdata) | - -**Returns:** *boolean* - -
- - - - -## Functions - -#### generatePseudoRandomSalt - -▸ **generatePseudoRandomSalt**(): *`BigNumber`* - -*Defined in [order-utils/src/salt.ts:9](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/salt.ts#L9)* - -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. - -**Returns:** *`BigNumber`* - -A pseudo-random 256-bit number that can be used as a salt. - -
- - - - -## Functions - -#### isValidECSignature - -▸ **isValidECSignature**(`data`: string, `signature`: `ECSignature`, `signerAddress`: string): *boolean* - -*Defined in [order-utils/src/signature_utils.ts:430](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/signature_utils.ts#L430)* - -Checks if the supplied elliptic curve signature corresponds to signing `data` with -the private key corresponding to `signerAddress` - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`data` | string | The hex encoded data signed by the supplied signature. | -`signature` | `ECSignature` | An object containing the elliptic curve signature parameters. | -`signerAddress` | string | The hex encoded address that signed the data, producing the supplied signature. | - -**Returns:** *boolean* - -Whether the ECSignature is valid. - -___ - -### parseSignatureHexAsVRS - -▸ **parseSignatureHexAsVRS**(`signatureHex`: string): *`ECSignature`* - -*Defined in [order-utils/src/signature_utils.ts:388](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/signature_utils.ts#L388)* - -Parses a signature hex string, which is assumed to be in the VRS format. - -**Parameters:** - -Name | Type | ------- | ------ | -`signatureHex` | string | - -**Returns:** *`ECSignature`* - -## Object literals - -### `Const` signatureUtils - -#### ▪ **signatureUtils**: *object* - -*Defined in [order-utils/src/signature_utils.ts:26](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/signature_utils.ts#L26)* - -#### addSignedMessagePrefix - -▸ **addSignedMessagePrefix**(`message`: string): *string* - -*Defined in [order-utils/src/signature_utils.ts:361](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/signature_utils.ts#L361)* - -Adds the relevant prefix to the message being signed. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`message` | string | Message to sign | - -**Returns:** *string* - -Prefixed message - -#### convertECSignatureToSignatureHex - -▸ **convertECSignatureToSignatureHex**(`ecSignature`: `ECSignature`): *string* - -*Defined in [order-utils/src/signature_utils.ts:340](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/signature_utils.ts#L340)* - -Combines ECSignature with V,R,S and the EthSign signature type for use in 0x protocol - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`ecSignature` | `ECSignature` | The ECSignature of the signed data | - -**Returns:** *string* - -Hex encoded string of signature (v,r,s) with Signature Type - -#### convertToSignatureWithType - -▸ **convertToSignatureWithType**(`signature`: string, `signatureType`: `SignatureType`): *string* - -*Defined in [order-utils/src/signature_utils.ts:351](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/signature_utils.ts#L351)* - -Combines the signature proof and the Signature Type. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`signature` | string | The hex encoded signature proof | -`signatureType` | `SignatureType` | The signature type, i.e EthSign, Wallet etc. | - -**Returns:** *string* - -Hex encoded string of signature proof with Signature Type - -#### ecSignExchangeProxyMetaTransactionAsync - -▸ **ecSignExchangeProxyMetaTransactionAsync**(`supportedProvider`: [SupportedProvider](#supportedprovider), `transaction`: `ExchangeProxyMetaTransaction`, `signerAddress`: string): *`Promise`* - -*Defined in [order-utils/src/signature_utils.ts:204](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/signature_utils.ts#L204)* - -Signs an Exchange Proxy meta-transaction and returns a SignedExchangeProxyMetaTransaction. -First `eth_signTypedData` is requested then a fallback to `eth_sign` if not -available on the supplied provider. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`supportedProvider` | [SupportedProvider](#supportedprovider) | Web3 provider to use for all JSON RPC requests | -`transaction` | `ExchangeProxyMetaTransaction` | The ExchangeProxyMetaTransaction to sign. | -`signerAddress` | string | The hex encoded Ethereum address you wish to sign it with. This address must be available via the supplied Provider. | - -**Returns:** *`Promise`* - -A SignedExchangeProxyMetaTransaction containing the order and - elliptic curve signature with Signature Type. - -#### ecSignHashAsync - -▸ **ecSignHashAsync**(`supportedProvider`: [SupportedProvider](#supportedprovider), `msgHash`: string, `signerAddress`: string): *`Promise`* - -*Defined in [order-utils/src/signature_utils.ts:291](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/signature_utils.ts#L291)* - -Signs a hash using `eth_sign` and returns its elliptic curve signature and signature type. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`supportedProvider` | [SupportedProvider](#supportedprovider) | Web3 provider to use for all JSON RPC requests | -`msgHash` | string | Hex encoded message to sign. | -`signerAddress` | string | The hex encoded Ethereum address you wish to sign it with. This address must be available via the supplied Provider. | - -**Returns:** *`Promise`* - -A hex encoded string containing the Elliptic curve signature generated by signing the msgHash and the Signature Type. - -#### ecSignOrderAsync - -▸ **ecSignOrderAsync**(`supportedProvider`: [SupportedProvider](#supportedprovider), `order`: `Order`, `signerAddress`: string): *`Promise`* - -*Defined in [order-utils/src/signature_utils.ts:36](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/signature_utils.ts#L36)* - -Signs an order and returns a SignedOrder. First `eth_signTypedData` is requested -then a fallback to `eth_sign` if not available on the supplied provider. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`supportedProvider` | [SupportedProvider](#supportedprovider) | Web3 provider to use for all JSON RPC requests | -`order` | `Order` | The Order to sign. | -`signerAddress` | string | The hex encoded Ethereum address you wish to sign it with. This address must be available via the supplied Provider. | - -**Returns:** *`Promise`* - -A SignedOrder containing the order and Elliptic curve signature with Signature Type. - -#### ecSignTransactionAsync - -▸ **ecSignTransactionAsync**(`supportedProvider`: [SupportedProvider](#supportedprovider), `transaction`: `ZeroExTransaction`, `signerAddress`: string): *`Promise`* - -*Defined in [order-utils/src/signature_utils.ts:115](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/signature_utils.ts#L115)* - -Signs a transaction and returns a SignedZeroExTransaction. First `eth_signTypedData` is requested -then a fallback to `eth_sign` if not available on the supplied provider. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`supportedProvider` | [SupportedProvider](#supportedprovider) | Web3 provider to use for all JSON RPC requests | -`transaction` | `ZeroExTransaction` | The ZeroExTransaction to sign. | -`signerAddress` | string | The hex encoded Ethereum address you wish to sign it with. This address must be available via the supplied Provider. | - -**Returns:** *`Promise`* - -A SignedTransaction containing the order and Elliptic curve signature with Signature Type. - -#### ecSignTypedDataExchangeProxyMetaTransactionAsync - -▸ **ecSignTypedDataExchangeProxyMetaTransactionAsync**(`supportedProvider`: [SupportedProvider](#supportedprovider), `transaction`: `ExchangeProxyMetaTransaction`, `signerAddress`: string): *`Promise`* - -*Defined in [order-utils/src/signature_utils.ts:249](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/signature_utils.ts#L249)* - -Signs an Exchange Proxy meta-transaction using `eth_signTypedData` and -returns a SignedZeroExTransaction. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`supportedProvider` | [SupportedProvider](#supportedprovider) | Web3 provider to use for all JSON RPC requests | -`transaction` | `ExchangeProxyMetaTransaction` | The Exchange Proxy transaction to sign. | -`signerAddress` | string | The hex encoded Ethereum address you wish to sign it with. This address must be available via the supplied Provider. | - -**Returns:** *`Promise`* - -A SignedExchangeProxyMetaTransaction containing the - ExchangeProxyMetaTransaction and elliptic curve signature with Signature Type. - -#### ecSignTypedDataOrderAsync - -▸ **ecSignTypedDataOrderAsync**(`supportedProvider`: [SupportedProvider](#supportedprovider), `order`: `Order`, `signerAddress`: string): *`Promise`* - -*Defined in [order-utils/src/signature_utils.ts:71](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/signature_utils.ts#L71)* - -Signs an order using `eth_signTypedData` and returns a SignedOrder. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`supportedProvider` | [SupportedProvider](#supportedprovider) | Web3 provider to use for all JSON RPC requests | -`order` | `Order` | The Order to sign. | -`signerAddress` | string | The hex encoded Ethereum address you wish to sign it with. This address must be available via the supplied Provider. | - -**Returns:** *`Promise`* - -A SignedOrder containing the order and Elliptic curve signature with Signature Type. - -#### ecSignTypedDataTransactionAsync - -▸ **ecSignTypedDataTransactionAsync**(`supportedProvider`: [SupportedProvider](#supportedprovider), `transaction`: `ZeroExTransaction`, `signerAddress`: string): *`Promise`* - -*Defined in [order-utils/src/signature_utils.ts:158](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/signature_utils.ts#L158)* - -Signs a ZeroExTransaction using `eth_signTypedData` and returns a SignedZeroExTransaction. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`supportedProvider` | [SupportedProvider](#supportedprovider) | Web3 provider to use for all JSON RPC requests | -`transaction` | `ZeroExTransaction` | The ZeroEx Transaction to sign. | -`signerAddress` | string | The hex encoded Ethereum address you wish to sign it with. This address must be available via the supplied Provider. | - -**Returns:** *`Promise`* - -A SignedZeroExTransaction containing the ZeroExTransaction and Elliptic curve signature with Signature Type. - -#### parseValidatorSignature - -▸ **parseValidatorSignature**(`signature`: string): *`ValidatorSignature`* - -*Defined in [order-utils/src/signature_utils.ts:373](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/order-utils/src/signature_utils.ts#L373)* - -Parse a hex-encoded Validator signature into validator address and signature components - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`signature` | string | A hex encoded Validator 0x Protocol signature | - -**Returns:** *`ValidatorSignature`* - -A ValidatorSignature with validatorAddress and signature parameters - -
- - - -
- - - -
- - - - -## Type aliases - -#### Callback - -Ƭ **Callback**: *function* - -*Defined in [subproviders/src/types.ts:131](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/subproviders/src/types.ts#L131)* - -##### Type declaration: - -▸ (): *void* - -___ - - - -### ErrorCallback - -Ƭ **ErrorCallback**: *function* - -*Defined in [subproviders/src/types.ts:130](https://github.com/0xProject/0x-monorepo/blob/762e0aec2/packages/subproviders/src/types.ts#L130)* - -#### Type declaration: - -▸ (`err`: `Error` | null, `data?`: any): *void* - -**Parameters:** - -Name | Type | ------- | ------ | -`err` | `Error` \| null | -`data?` | any | - -___ - - - - - - - diff --git a/packages/0x.js/package.json b/packages/0x.js/package.json deleted file mode 100644 index 33b3a51e9a..0000000000 --- a/packages/0x.js/package.json +++ /dev/null @@ -1,101 +0,0 @@ -{ - "name": "0x.js", - "version": "9.2.0", - "engines": { - "node": ">=6.12" - }, - "description": "A javascript library for interacting with the 0x protocol", - "keywords": [ - "0x.js", - "0xproject", - "ethereum", - "tokens", - "exchange" - ], - "main": "lib/index.js", - "types": "lib/index.d.ts", - "scripts": { - "build": "yarn build:all", - "build:ci": "yarn build:commonjs", - "build:all": "run-p build:umd:prod build:commonjs", - "lint": "tslint --format stylish --project .", - "fix": "tslint --fix --format stylish --project .", - "test:circleci": "run-s test:coverage", - "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 src/generated_contract_wrappers generated_docs", - "build:umd:prod": "NODE_ENV=production node --max_old_space_size=8192 ../../node_modules/.bin/webpack --mode production", - "build:commonjs": "tsc -b", - "diff_docs": "git diff --exit-code ./docs", - "s3:sync_md_docs": "aws s3 sync ./docs s3://docs-markdown/${npm_package_name}/v${npm_package_version} --profile 0xproject --region us-east-1 --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers", - "docs:md": "ts-doc-gen --sourceDir='$PROJECT_FILES' --output=$MD_FILE_DIR --fileExtension=mdx --tsconfig=./typedoc-tsconfig.json", - "docs:json": "typedoc --excludePrivate --excludeExternals --excludeProtected --ignoreCompilerErrors --target ES5 --tsconfig typedoc-tsconfig.json --json $JSON_FILE_PATH $PROJECT_FILES" - }, - "config": { - "postpublish": { - "assets": [ - "packages/0x.js/_bundles/index.js", - "packages/0x.js/_bundles/index.min.js" - ] - } - }, - "repository": { - "type": "git", - "url": "https://github.com/0xProject/0x-monorepo" - }, - "license": "Apache-2.0", - "devDependencies": { - "@0x/contract-addresses": "^4.11.0", - "@0x/dev-utils": "^3.3.0", - "@0x/migrations": "^6.4.0", - "@0x/ts-doc-gen": "^0.0.22", - "@0x/tslint-config": "^4.1.0", - "@types/lodash": "4.14.104", - "@types/mocha": "^5.2.7", - "@types/sinon": "^2.2.2", - "awesome-typescript-loader": "^5.2.1", - "chai": "^4.0.1", - "chai-as-promised": "^7.1.0", - "chai-bignumber": "^3.0.0", - "copyfiles": "^2.0.0", - "dirty-chai": "^2.0.1", - "make-promises-safe": "^1.1.0", - "mocha": "^6.2.0", - "npm-run-all": "^4.1.2", - "nyc": "^11.0.1", - "opn-cli": "^3.1.0", - "shx": "^0.2.2", - "sinon": "^4.0.0", - "source-map-support": "^0.5.0", - "terser-webpack-plugin": "^2.0.1", - "tslint": "5.11.0", - "typedoc": "^0.15.0", - "typescript": "3.0.1", - "uglifyjs-webpack-plugin": "^2.0.1", - "webpack": "^4.20.2" - }, - "dependencies": { - "@0x/abi-gen-wrappers": "^5.4.0-beta.3", - "@0x/assert": "^3.0.9", - "@0x/asset-swapper": "^4.6.0", - "@0x/base-contract": "^6.2.3", - "@0x/contract-wrappers": "^13.8.0", - "@0x/order-utils": "^10.3.0", - "@0x/subproviders": "^6.1.1", - "@0x/types": "^3.2.0", - "@0x/typescript-typings": "^5.1.1", - "@0x/utils": "^5.5.1", - "@0x/web3-wrapper": "^7.2.0", - "@types/node": "12.12.54", - "@types/web3-provider-engine": "^14.0.0", - "ethereum-types": "^3.2.0", - "ethers": "~4.0.4", - "lodash": "^4.17.11", - "web3-provider-engine": "14.0.6" - }, - "publishConfig": { - "access": "public" - }, - "gitHead": "4f91bfd907996b2f4dd383778b50c479c2602b56" -} diff --git a/packages/0x.js/src/index.ts b/packages/0x.js/src/index.ts deleted file mode 100644 index 00582a0310..0000000000 --- a/packages/0x.js/src/index.ts +++ /dev/null @@ -1,140 +0,0 @@ -export { getContractAddressesForChainOrThrow, ChainId, ContractAddresses } from '@0x/contract-addresses'; - -export { signatureUtils, generatePseudoRandomSalt, assetDataUtils } from '@0x/order-utils'; - -export { - ExchangeEventArgs, - ExchangeEvents, - ExchangeSignatureValidatorApprovalEventArgs, - ExchangeFillEventArgs, - ExchangeCancelEventArgs, - ExchangeCancelUpToEventArgs, - ExchangeAssetProxyRegisteredEventArgs, - ExchangeContract, - DevUtilsContract, - WETH9EventArgs, - WETH9Events, - WETH9ApprovalEventArgs, - WETH9TransferEventArgs, - WETH9DepositEventArgs, - WETH9WithdrawalEventArgs, - WETH9Contract, - ERC20TokenEventArgs, - ERC20TokenEvents, - ERC20TokenTransferEventArgs, - ERC20TokenApprovalEventArgs, - ERC20TokenContract, - ERC721TokenEventArgs, - ERC721TokenEvents, - ERC721TokenTransferEventArgs, - ERC721TokenApprovalEventArgs, - ERC721TokenApprovalForAllEventArgs, - ERC721TokenContract, - ExchangeOwnershipTransferredEventArgs, - ExchangeProtocolFeeCollectorAddressEventArgs, - ExchangeProtocolFeeMultiplierEventArgs, - ExchangeTransactionExecutionEventArgs, -} from '@0x/contract-wrappers'; - -export { - ContractEvent, - SendTransactionOpts, - AwaitTransactionSuccessOpts, - ContractFunctionObj, - ContractTxFunctionObj, - SubscriptionErrors, -} from '@0x/base-contract'; - -export import Web3ProviderEngine = require('web3-provider-engine'); - -export { - RPCSubprovider, - Callback, - JSONRPCRequestPayloadWithMethod, - ErrorCallback, - MetamaskSubprovider, -} from '@0x/subproviders'; - -export { DecodedCalldata, BigNumber } from '@0x/utils'; - -export { - Order, - SignedOrder, - ECSignature, - AssetData, - SingleAssetData, - ERC20AssetData, - ERC20BridgeAssetData, - ERC721AssetData, - ERC1155AssetData, - MultiAssetData, - StaticCallAssetData, - MultiAssetDataWithRecursiveDecoding, - SignatureType, - ZeroExTransaction, - SignedZeroExTransaction, - ValidatorSignature, - SimpleContractArtifact, - SimpleStandardContractOutput, - SimpleEvmOutput, - SimpleEvmBytecodeOutput, - EIP712DomainWithDefaultSchema, - EventCallback, - IndexedFilterValues, - DecodedLogEvent, - ExchangeProxyMetaTransaction, - SignedExchangeProxyMetaTransaction, -} from '@0x/types'; - -export { - BlockRange, - ContractAbi, - ContractEventArg, - SupportedProvider, - JSONRPCRequestPayload, - JSONRPCResponsePayload, - JSONRPCResponseError, - AbiDefinition, - FunctionAbi, - EventAbi, - EventParameter, - MethodAbi, - ConstructorAbi, - FallbackAbi, - DataItem, - TupleDataItem, - ConstructorStateMutability, - StateMutability, - Web3JsProvider, - GanacheProvider, - EIP1193Provider, - ZeroExProvider, - EIP1193Event, - JSONRPCErrorCallback, - Web3JsV1Provider, - Web3JsV2Provider, - Web3JsV3Provider, - TxData, - ContractArtifact, - CallData, - GethCallOverrides, - BlockParam, - CompilerOpts, - StandardContractOutput, - ContractChains, - TxDataPayable, - BlockParamLiteral, - CompilerSettings, - ContractChainData, - DevdocOutput, - EvmOutput, - CompilerSettingsMetadata, - OptimizerSettings, - OutputField, - ParamDescription, - EvmBytecodeOutput, - EvmBytecodeOutputLinkReferences, - RevertErrorAbi, - DecodedLogArgs, - LogWithDecodedArgs, -} from 'ethereum-types'; diff --git a/packages/0x.js/tsconfig.json b/packages/0x.js/tsconfig.json deleted file mode 100644 index a96536716c..0000000000 --- a/packages/0x.js/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../tsconfig", - "compilerOptions": { - "outDir": "lib", - "rootDir": "src" - }, - "include": ["./src/**/*"] -} diff --git a/packages/0x.js/tslint.json b/packages/0x.js/tslint.json deleted file mode 100644 index dd9053357e..0000000000 --- a/packages/0x.js/tslint.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": ["@0x/tslint-config"] -} diff --git a/packages/0x.js/typedoc-tsconfig.json b/packages/0x.js/typedoc-tsconfig.json deleted file mode 100644 index a4c669cb6d..0000000000 --- a/packages/0x.js/typedoc-tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "../../typedoc-tsconfig", - "compilerOptions": { - "outDir": "lib" - }, - "include": ["./src/**/*"] -} diff --git a/packages/0x.js/webpack.config.js b/packages/0x.js/webpack.config.js deleted file mode 100644 index fbdc404121..0000000000 --- a/packages/0x.js/webpack.config.js +++ /dev/null @@ -1,70 +0,0 @@ -/** - * This is to generate the umd bundle only - */ -const _ = require('lodash'); -const TerserPlugin = require('terser-webpack-plugin'); -const path = require('path'); -const production = process.env.NODE_ENV === 'production'; - -let entry = { - index: './src/index.ts', -}; -if (production) { - entry = _.assign({}, entry, { 'index.min': './src/index.ts' }); -} - -module.exports = { - entry, - mode: 'production', - output: { - path: path.resolve(__dirname, '_bundles'), - filename: '[name].js', - libraryTarget: 'umd', - library: 'ZeroEx', - umdNamedDefine: true, - }, - resolve: { - extensions: ['.ts', '.js', '.json'], - }, - devtool: 'source-map', - optimization: { - minimizer: [ - new TerserPlugin({ - sourceMap: true, - terserOptions: { - mangle: { - reserved: ['BigNumber'], - }, - }, - }), - ], - }, - // This supports the ethereumjs-vm dependency in `@0x/base-contract` - // The .wasm 'glue' code generated by Emscripten requires these node builtins, - // but won't actually use them in a web environment. We tell Webpack to not resolve those - // require statements since we know we won't need them. - externals: { - fs: true, - }, - module: { - rules: [ - { - test: /\.ts$/, - use: [ - { - loader: 'awesome-typescript-loader', - // tsconfig.json contains some options required for - // project references which do not work with webback. - // We override those options here. - query: { - declaration: false, - declarationMap: false, - composite: false, - }, - }, - ], - exclude: /node_modules/, - }, - ], - }, -}; diff --git a/packages/abi-gen/.npmignore b/packages/abi-gen/.npmignore deleted file mode 100644 index 8053fd5d11..0000000000 --- a/packages/abi-gen/.npmignore +++ /dev/null @@ -1,10 +0,0 @@ -# Blacklist all files -.* -* -# Whitelist lib -!lib/**/* -# Blacklist tests and publish scripts -/lib/test/* -/lib/monorepo_scripts/ -# Package specific ignore -!bin/**/* diff --git a/packages/abi-gen/CHANGELOG.json b/packages/abi-gen/CHANGELOG.json deleted file mode 100644 index 4350d22d58..0000000000 --- a/packages/abi-gen/CHANGELOG.json +++ /dev/null @@ -1,928 +0,0 @@ -[ - { - "version": "5.4.0", - "changes": [ - { - "note": "Allow overriding of `data` with contract calls and transactions", - "pr": 2626 - } - ] - }, - { - "timestamp": 1594788383, - "version": "5.3.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "5.3.0", - "changes": [ - { - "note": "Allow identifiers with leading underscores in python wrappers", - "pr": 2591 - } - ], - "timestamp": 1592969527 - }, - { - "version": "5.2.2", - "changes": [ - { - "note": "Include `bin` files" - } - ], - "timestamp": 1582677073 - }, - { - "timestamp": 1582623685, - "version": "5.2.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "5.2.0", - "changes": [ - { - "note": "Support deploying contracts with unliked libraries through `deployWithLibrariesFrom0xArtifactAsync()`", - "pr": 2463 - }, - { - "note": "Update reference outputs", - "pr": 2466 - } - ], - "timestamp": 1581204851 - }, - { - "timestamp": 1580988106, - "version": "5.1.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1580811564, - "version": "5.1.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "5.1.0", - "changes": [ - { - "note": "Catch empty call reverts on live networks.", - "pr": 2433 - }, - { - "note": "Regenerate test outputs.", - "pr": 2433 - } - ], - "timestamp": 1579682890 - }, - { - "timestamp": 1578272714, - "version": "5.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1576540892, - "version": "5.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1575931811, - "version": "5.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "5.0.0", - "changes": [ - { - "note": "Refactored TS wrapper templates to result in a more succint interface. See https://github.com/0xProject/0x-monorepo/pull/2325 for details.", - "pr": 2284 - }, - { - "note": "Python: Corrected return types and values for call() interface to generated method wrappers. (Fixes #2298)", - "pr": 2345 - }, - { - "note": "Python: Stopped generating send_transaction() interface for constant (view/pure) methods", - "pr": 2345 - }, - { - "note": "Python: Added a build_transaction() interface to contract method classes", - "pr": 2345 - }, - { - "note": "Python: Removed `validator` argument to contract method classes for methods that don't have any inputs", - "pr": 2345 - }, - { - "note": "Python: Changed the names of generated tuples to use the `internalType` field in the ABI, if it's present, resulting in human readable struct names rather than hashes of component field names.", - "pr": 2345 - }, - { - "note": "Moved shared logic into `BaseContract` helpers to reduce size.", - "pr": 2343 - }, - { - "note": "Re-enable gas estimation when `gas` is not provided.", - "pr": 2343 - }, - { - "note": "In Python wrappers, accept string arguments to bytes parameters", - "pr": 2284 - }, - { - "note": "In Python wrappers, support module-local, Web3.py-compatible middleware", - "pr": 2284 - }, - { - "note": "In Python wrappers, allow contracts to be instantiated with EITHER a Web3.py BaseProvider OR a Web3 client object", - "pr": 2284 - }, - { - "note": "In Python wrappers, fix bug with casting some bytes objects using bytes.fromhex()", - "pr": 2284 - }, - { - "note": "Add `getSelector` method to all functions", - "pr": 2224 - }, - { - "note": "Command-line argument network-id has changed to chain-id", - "pr": 2313 - }, - { - "note": "Fix templates not being included in published tarball", - "pr": 2315 - } - ], - "timestamp": 1575296764 - }, - { - "version": "4.4.0-beta.4", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1575290197 - }, - { - "version": "4.4.0-beta.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1574238768 - }, - { - "version": "4.4.0-beta.2", - "changes": [ - { - "note": "Refactored TS wrapper templates to result in a more succint interface. See https://github.com/0xProject/0x-monorepo/pull/2325 for details.", - "pr": 2284 - }, - { - "note": "Python: Corrected return types and values for call() interface to generated method wrappers. (Fixes #2298)", - "pr": 2345 - }, - { - "note": "Python: Stopped generating send_transaction() interface for constant (view/pure) methods", - "pr": 2345 - }, - { - "note": "Python: Added a build_transaction() interface to contract method classes", - "pr": 2345 - }, - { - "note": "Python: Removed `validator` argument to contract method classes for methods that don't have any inputs", - "pr": 2345 - }, - { - "note": "Python: Changed the names of generated tuples to use the `internalType` field in the ABI, if it's present, resulting in human readable struct names rather than hashes of component field names.", - "pr": 2345 - }, - { - "note": "Moved shared logic into `BaseContract` helpers to reduce size.", - "pr": 2343 - }, - { - "note": "Re-enable gas estimation when `gas` is not provided.", - "pr": 2343 - } - ], - "timestamp": 1574030254 - }, - { - "version": "4.4.0-beta.1", - "changes": [ - { - "note": "In Python wrappers, accept string arguments to bytes parameters", - "pr": 2284 - }, - { - "note": "In Python wrappers, support module-local, Web3.py-compatible middleware", - "pr": 2284 - }, - { - "note": "In Python wrappers, allow contracts to be instantiated with EITHER a Web3.py BaseProvider OR a Web3 client object", - "pr": 2284 - }, - { - "note": "In Python wrappers, fix bug with casting some bytes objects using bytes.fromhex()", - "pr": 2284 - }, - { - "note": "Add `getSelector` method to all functions", - "pr": 2224 - }, - { - "note": "Command-line argument network-id has changed to chain-id", - "pr": 2313 - }, - { - "note": "Fix templates not being included in published tarball", - "pr": 2315 - } - ], - "timestamp": 1573159180 - }, - { - "version": "4.3.0-beta.0", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1570135330 - }, - { - "version": "4.2.1", - "changes": [ - { - "note": "Redirect to `evmExecAsync` to use local EVM instead of eth_call for pure functions", - "pr": 2108 - } - ], - "timestamp": 1568744790 - }, - { - "version": "4.2.0", - "changes": [ - { - "note": "Provide a default set of templates for code generation, used when --template and --partials are left unspecified", - "pr": 2082 - } - ], - "timestamp": 1567521715 - }, - { - "timestamp": 1566446343, - "version": "4.1.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "4.1.0", - "changes": [ - { - "note": "Updated expected typescript output for cli tests to include `getABIDecodedTransactionData` and `getABIDecodedReturnData`", - "pr": 2018 - }, - { - "note": "Added tests for`getABIDecodedTransactionData` and `getABIDecodedReturnData` in contract wrappers.", - "pr": 2018 - } - ], - "timestamp": 1565296576 - }, - { - "version": "4.0.0", - "changes": [ - { - "note": "whitespace changes to generated Python code", - "pr": 1996 - }, - { - "note": "move Python Validator base class from generated code to common package", - "pr": 1996 - }, - { - "note": "Changed fundamental thing-to-be-wrapped from the contract to the contract method. That is, now there is a base contract method wrapper class rather than a base contract wrapper class, and individual contract methods are represented by named classes inheriting from that base, and the different operations on a method are now represented by a nested-object dot notation, ie, WrappedContract.ContractMethod.call() and WrappedContract.ContractMethod.send_transaction().", - "pr": 1996 - }, - { - "note": "added gas estimation functionality to contract methods", - "pr": 1996 - }, - { - "note": "Python: fixed bug with methods returning multiple values", - "pr": 1996 - }, - { - "note": "Python: fixed bug with methods returning arrays of structs", - "pr": 1996 - }, - { - "note": "Python: fixed bug with methods that return a struct that contains another struct where the inner struct was not otherwise directly referenced by any method", - "pr": 1996 - }, - { - "note": "Python: fixed bug with tuples sometimes being used before they were declared", - "pr": 1996 - }, - { - "note": "Python: fixed bug with supporting overloaded methods", - "pr": 1996 - } - ] - }, - { - "version": "3.1.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1564604963 - }, - { - "version": "3.1.1", - "changes": [ - { - "note": "Python method parameters are now in snake case", - "pr": 1919 - }, - { - "note": "Python wrappers now support tuples in method parameters", - "pr": 1919 - }, - { - "note": "document Python method's bytes params as requiring UTF-8", - "pr": 1919 - }, - { - "note": "generate Python output into a contract-named folder, not a file (eg exchange/__init__.py rather than exchange.py) leaving space for user-defined additions to the same module, such as for custom types, as used by the Exchange wrapper's manually-written type aliases in the contract_wrappers.exchange.types Python module", - "pr": 1919 - }, - { - "note": "support for customizable parameter validation for Python wrappers", - "pr": 1919 - }, - { - "note": "wrap Python docstrings better, for pydocstyle compliance", - "pr": 1919 - }, - { - "note": "lots of fixes to satisfy linters of generated Python code", - "pr": 1919 - } - ], - "timestamp": 1563957393 - }, - { - "timestamp": 1563047529, - "version": "2.1.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.1.0", - "changes": [ - { - "note": "Initial support for Python", - "pr": 1878 - } - ], - "timestamp": 1563006338 - }, - { - "version": "2.0.11", - "changes": [ - { - "note": "Watch template files for changes", - "pr": 1875 - } - ] - }, - { - "timestamp": 1557507213, - "version": "2.0.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1554997931 - }, - { - "timestamp": 1553183790, - "version": "2.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1553091633, - "version": "2.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551479279, - "version": "2.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551220833, - "version": "2.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551130135, - "version": "2.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1549733923, - "version": "2.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1549547375 - }, - { - "timestamp": 1549452781, - "version": "2.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.0", - "changes": [ - { - "note": "Upgrade the bignumber.js to v8.0.2", - "pr": 1517 - } - ], - "timestamp": 1549373905 - }, - { - "timestamp": 1547561734, - "version": "1.0.22", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547225310, - "version": "1.0.21", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547040760, - "version": "1.0.20", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.19", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544739608 - }, - { - "version": "1.0.18", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544570656 - }, - { - "timestamp": 1542821676, - "version": "1.0.17", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542208198, - "version": "1.0.16", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.15", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1541740904 - }, - { - "timestamp": 1539871071, - "version": "1.0.14", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.13", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1538693146 - }, - { - "timestamp": 1538157789, - "version": "1.0.12", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537907159, - "version": "1.0.11", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537875740, - "version": "1.0.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537541580, - "version": "1.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1536142250, - "version": "1.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1535377027, - "version": "1.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1535133899, - "version": "1.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1534210131, - "version": "1.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532619515, - "version": "1.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532614997, - "version": "1.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532605697, - "version": "1.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.1", - "changes": [ - { - "note": "Fix the abi-gen entry point in package.json", - "pr": 901 - } - ], - "timestamp": 1532357734 - }, - { - "timestamp": 1532043000, - "version": "1.0.0", - "changes": [ - { - "note": "Convert e_r_c to erc in generated file names", - "pr": 822 - }, - { - "note": "Remove the output directory before writing to it", - "pr": 822 - }, - { - "note": "skip generation of wrappers that are already up to date", - "pr": 788 - } - ] - }, - { - "timestamp": 1531919263, - "version": "0.3.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1531149657, - "version": "0.3.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1529397769, - "version": "0.3.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.3.1", - "changes": [ - { - "note": "Incorrect publish that was unpublished" - } - ], - "timestamp": 1527810075 - }, - { - "version": "0.3.0", - "changes": [ - { - "note": "Properly export the executable binary", - "pr": 588 - } - ], - "timestamp": 1527008270 - }, - { - "timestamp": 1525477860, - "version": "0.2.13", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1525428773, - "version": "0.2.12", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1524044013, - "version": "0.2.11", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1523462196, - "version": "0.2.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1522673609, - "version": "0.2.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1522658513, - "version": "0.2.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.2.5", - "changes": [ - { - "note": "Consolidate all `console.log` calls into `logUtils` in the `@0xproject/utils` package", - "pr": 452 - } - ], - "timestamp": 1521298800 - }, - { - "version": "0.2.4", - "changes": [ - { - "note": "Add a `backend` parameter that allows you to specify the Ethereum library you use in your templates (`web3` or `ethers`). Ethers auto-converts small ints to numbers whereas Web3 doesn't. Defaults to `web3`", - "pr": 413 - }, - { - "note": "Add support for [tuple types](https://solidity.readthedocs.io/en/develop/abi-spec.html#handling-tuple-types)", - "pr": 413 - }, - { - "note": "Add `hasReturnValue` to context data", - "pr": 413 - } - ], - "timestamp": 1520089200 - }, - { - "version": "0.2.1", - "changes": [ - { - "note": "Fix publishing issue where .npmignore was not properly excluding undesired content", - "pr": 389 - } - ], - "timestamp": 1518102000 - }, - { - "version": "0.2.0", - "changes": [ - { - "note": "Added CLI options for explicit specifying location of partials and main template", - "pr": 346 - }, - { - "note": "Added CLI option to specify networkId, adding support for the JSON artifact format found in @0xproject/contracts", - "pr": 388 - } - ], - "timestamp": 1517929200 - }, - { - "version": "0.1.0", - "changes": [ - { - "note": "Fixed array typings with union types", - "pr": 295 - }, - { - "note": "Add event ABIs to context data passed to templates", - "pr": 302 - }, - { - "note": "Add constructor ABIs to context data passed to templates", - "pr": 304 - } - ], - "timestamp": 1515596400 - } -] diff --git a/packages/abi-gen/CHANGELOG.md b/packages/abi-gen/CHANGELOG.md deleted file mode 100644 index 8723b299c1..0000000000 --- a/packages/abi-gen/CHANGELOG.md +++ /dev/null @@ -1,365 +0,0 @@ - - -CHANGELOG - -## v5.3.1 - _July 15, 2020_ - - * Dependencies updated - -## v5.3.0 - _June 24, 2020_ - - * Allow identifiers with leading underscores in python wrappers (#2591) - -## v5.2.2 - _February 26, 2020_ - - * Include `bin` files - -## v5.2.1 - _February 25, 2020_ - - * Dependencies updated - -## v5.2.0 - _February 8, 2020_ - - * Support deploying contracts with unliked libraries through `deployWithLibrariesFrom0xArtifactAsync()` (#2463) - * Update reference outputs (#2466) - -## v5.1.2 - _February 6, 2020_ - - * Dependencies updated - -## v5.1.1 - _February 4, 2020_ - - * Dependencies updated - -## v5.1.0 - _January 22, 2020_ - - * Catch empty call reverts on live networks. (#2433) - * Regenerate test outputs. (#2433) - -## v5.0.3 - _January 6, 2020_ - - * Dependencies updated - -## v5.0.2 - _December 17, 2019_ - - * Dependencies updated - -## v5.0.1 - _December 9, 2019_ - - * Dependencies updated - -## v5.0.0 - _December 2, 2019_ - - * Refactored TS wrapper templates to result in a more succint interface. See https://github.com/0xProject/0x-monorepo/pull/2325 for details. (#2284) - * Python: Corrected return types and values for call() interface to generated method wrappers. (Fixes #2298) (#2345) - * Python: Stopped generating send_transaction() interface for constant (view/pure) methods (#2345) - * Python: Added a build_transaction() interface to contract method classes (#2345) - * Python: Removed `validator` argument to contract method classes for methods that don't have any inputs (#2345) - * Python: Changed the names of generated tuples to use the `internalType` field in the ABI, if it's present, resulting in human readable struct names rather than hashes of component field names. (#2345) - * Moved shared logic into `BaseContract` helpers to reduce size. (#2343) - * Re-enable gas estimation when `gas` is not provided. (#2343) - * In Python wrappers, accept string arguments to bytes parameters (#2284) - * In Python wrappers, support module-local, Web3.py-compatible middleware (#2284) - * In Python wrappers, allow contracts to be instantiated with EITHER a Web3.py BaseProvider OR a Web3 client object (#2284) - * In Python wrappers, fix bug with casting some bytes objects using bytes.fromhex() (#2284) - * Add `getSelector` method to all functions (#2224) - * Command-line argument network-id has changed to chain-id (#2313) - * Fix templates not being included in published tarball (#2315) - -## v4.4.0-beta.4 - _December 2, 2019_ - - * Dependencies updated - -## v4.4.0-beta.3 - _November 20, 2019_ - - * Dependencies updated - -## v4.4.0-beta.2 - _November 17, 2019_ - - * Refactored TS wrapper templates to result in a more succint interface. See https://github.com/0xProject/0x-monorepo/pull/2325 for details. (#2284) - * Python: Corrected return types and values for call() interface to generated method wrappers. (Fixes #2298) (#2345) - * Python: Stopped generating send_transaction() interface for constant (view/pure) methods (#2345) - * Python: Added a build_transaction() interface to contract method classes (#2345) - * Python: Removed `validator` argument to contract method classes for methods that don't have any inputs (#2345) - * Python: Changed the names of generated tuples to use the `internalType` field in the ABI, if it's present, resulting in human readable struct names rather than hashes of component field names. (#2345) - * Moved shared logic into `BaseContract` helpers to reduce size. (#2343) - * Re-enable gas estimation when `gas` is not provided. (#2343) - -## v4.4.0-beta.1 - _November 7, 2019_ - - * In Python wrappers, accept string arguments to bytes parameters (#2284) - * In Python wrappers, support module-local, Web3.py-compatible middleware (#2284) - * In Python wrappers, allow contracts to be instantiated with EITHER a Web3.py BaseProvider OR a Web3 client object (#2284) - * In Python wrappers, fix bug with casting some bytes objects using bytes.fromhex() (#2284) - * Add `getSelector` method to all functions (#2224) - * Command-line argument network-id has changed to chain-id (#2313) - * Fix templates not being included in published tarball (#2315) - -## v4.3.0-beta.0 - _October 3, 2019_ - - * Dependencies updated - -## v4.2.1 - _September 17, 2019_ - - * Redirect to `evmExecAsync` to use local EVM instead of eth_call for pure functions (#2108) - -## v4.2.0 - _September 3, 2019_ - - * Provide a default set of templates for code generation, used when --template and --partials are left unspecified (#2082) - -## v4.1.1 - _August 22, 2019_ - - * Dependencies updated - -## v4.1.0 - _August 8, 2019_ - - * Updated expected typescript output for cli tests to include `getABIDecodedTransactionData` and `getABIDecodedReturnData` (#2018) - * Added tests for`getABIDecodedTransactionData` and `getABIDecodedReturnData` in contract wrappers. (#2018) - -## v4.0.0 - _Invalid date_ - - * whitespace changes to generated Python code (#1996) - * move Python Validator base class from generated code to common package (#1996) - * Changed fundamental thing-to-be-wrapped from the contract to the contract method. That is, now there is a base contract method wrapper class rather than a base contract wrapper class, and individual contract methods are represented by named classes inheriting from that base, and the different operations on a method are now represented by a nested-object dot notation, ie, WrappedContract.ContractMethod.call() and WrappedContract.ContractMethod.send_transaction(). (#1996) - * added gas estimation functionality to contract methods (#1996) - * Python: fixed bug with methods returning multiple values (#1996) - * Python: fixed bug with methods returning arrays of structs (#1996) - * Python: fixed bug with methods that return a struct that contains another struct where the inner struct was not otherwise directly referenced by any method (#1996) - * Python: fixed bug with tuples sometimes being used before they were declared (#1996) - * Python: fixed bug with supporting overloaded methods (#1996) - -## v3.1.2 - _July 31, 2019_ - - * Dependencies updated - -## v3.1.1 - _July 24, 2019_ - - * Python method parameters are now in snake case (#1919) - * Python wrappers now support tuples in method parameters (#1919) - * document Python method's bytes params as requiring UTF-8 (#1919) - * generate Python output into a contract-named folder, not a file (eg exchange/__init__.py rather than exchange.py) leaving space for user-defined additions to the same module, such as for custom types, as used by the Exchange wrapper's manually-written type aliases in the contract_wrappers.exchange.types Python module (#1919) - * support for customizable parameter validation for Python wrappers (#1919) - * wrap Python docstrings better, for pydocstyle compliance (#1919) - * lots of fixes to satisfy linters of generated Python code (#1919) - -## v2.1.1 - _July 13, 2019_ - - * Dependencies updated - -## v2.1.0 - _July 13, 2019_ - - * Initial support for Python (#1878) - -## v2.0.11 - _Invalid date_ - - * Watch template files for changes (#1875) - -## v2.0.10 - _May 10, 2019_ - - * Dependencies updated - -## v2.0.9 - _April 11, 2019_ - - * Dependencies updated - -## v2.0.8 - _March 21, 2019_ - - * Dependencies updated - -## v2.0.7 - _March 20, 2019_ - - * Dependencies updated - -## v2.0.6 - _March 1, 2019_ - - * Dependencies updated - -## v2.0.5 - _February 26, 2019_ - - * Dependencies updated - -## v2.0.4 - _February 25, 2019_ - - * Dependencies updated - -## v2.0.3 - _February 9, 2019_ - - * Dependencies updated - -## v2.0.2 - _February 7, 2019_ - - * Dependencies updated - -## v2.0.1 - _February 6, 2019_ - - * Dependencies updated - -## v2.0.0 - _February 5, 2019_ - - * Upgrade the bignumber.js to v8.0.2 (#1517) - -## v1.0.22 - _January 15, 2019_ - - * Dependencies updated - -## v1.0.21 - _January 11, 2019_ - - * Dependencies updated - -## v1.0.20 - _January 9, 2019_ - - * Dependencies updated - -## v1.0.19 - _December 13, 2018_ - - * Dependencies updated - -## v1.0.18 - _December 11, 2018_ - - * Dependencies updated - -## v1.0.17 - _November 21, 2018_ - - * Dependencies updated - -## v1.0.16 - _November 14, 2018_ - - * Dependencies updated - -## v1.0.15 - _November 9, 2018_ - - * Dependencies updated - -## v1.0.14 - _October 18, 2018_ - - * Dependencies updated - -## v1.0.13 - _October 4, 2018_ - - * Dependencies updated - -## v1.0.12 - _September 28, 2018_ - - * Dependencies updated - -## v1.0.11 - _September 25, 2018_ - - * Dependencies updated - -## v1.0.10 - _September 25, 2018_ - - * Dependencies updated - -## v1.0.9 - _September 21, 2018_ - - * Dependencies updated - -## v1.0.8 - _September 5, 2018_ - - * Dependencies updated - -## v1.0.7 - _August 27, 2018_ - - * Dependencies updated - -## v1.0.6 - _August 24, 2018_ - - * Dependencies updated - -## v1.0.5 - _August 14, 2018_ - - * Dependencies updated - -## v1.0.4 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.3 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.2 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.1 - _July 23, 2018_ - - * Fix the abi-gen entry point in package.json (#901) - -## v1.0.0 - _July 19, 2018_ - - * Convert e_r_c to erc in generated file names (#822) - * Remove the output directory before writing to it (#822) - * skip generation of wrappers that are already up to date (#788) - -## v0.3.4 - _July 18, 2018_ - - * Dependencies updated - -## v0.3.3 - _July 9, 2018_ - - * Dependencies updated - -## v0.3.2 - _June 19, 2018_ - - * Dependencies updated - -## v0.3.1 - _May 31, 2018_ - - * Incorrect publish that was unpublished - -## v0.3.0 - _May 22, 2018_ - - * Properly export the executable binary (#588) - -## v0.2.13 - _May 4, 2018_ - - * Dependencies updated - -## v0.2.12 - _May 4, 2018_ - - * Dependencies updated - -## v0.2.11 - _April 18, 2018_ - - * Dependencies updated - -## v0.2.10 - _April 11, 2018_ - - * Dependencies updated - -## v0.2.9 - _April 2, 2018_ - - * Dependencies updated - -## v0.2.8 - _April 2, 2018_ - - * Dependencies updated - -## v0.2.5 - _March 17, 2018_ - - * Consolidate all `console.log` calls into `logUtils` in the `@0xproject/utils` package (#452) - -## v0.2.4 - _March 3, 2018_ - - * Add a `backend` parameter that allows you to specify the Ethereum library you use in your templates (`web3` or `ethers`). Ethers auto-converts small ints to numbers whereas Web3 doesn't. Defaults to `web3` (#413) - * Add support for [tuple types](https://solidity.readthedocs.io/en/develop/abi-spec.html#handling-tuple-types) (#413) - * Add `hasReturnValue` to context data (#413) - -## v0.2.1 - _February 8, 2018_ - - * Fix publishing issue where .npmignore was not properly excluding undesired content (#389) - -## v0.2.0 - _February 6, 2018_ - - * Added CLI options for explicit specifying location of partials and main template (#346) - * Added CLI option to specify networkId, adding support for the JSON artifact format found in @0xproject/contracts (#388) - -## v0.1.0 - _January 10, 2018_ - - * Fixed array typings with union types (#295) - * Add event ABIs to context data passed to templates (#302) - * Add constructor ABIs to context data passed to templates (#304) diff --git a/packages/abi-gen/README.md b/packages/abi-gen/README.md deleted file mode 100644 index edefb74bd4..0000000000 --- a/packages/abi-gen/README.md +++ /dev/null @@ -1,152 +0,0 @@ -# ABI Gen - -This package allows you to generate TypeScript or Python contract wrappers from ABI files. -It's heavily inspired by [Geth abigen](https://github.com/ethereum/go-ethereum/wiki/Native-DApps:-Go-bindings-to-Ethereum-contracts) but takes a different approach. -You can write your custom handlebars templates which will allow you to seamlessly integrate the generated code into your existing codebase with existing conventions. - -[Here](https://github.com/0xProject/0x-monorepo/tree/development/packages/0x.js/abi-gen-templates) are the templates used to generate the contract wrappers used by 0x.js. - -## Installation - -`yarn add -g @0x/abi-gen` - -## Usage - -``` -$ abi-gen --help -Options: - --help Show help [boolean] - --version Show version number [boolean] - --abis Glob pattern to search for ABI JSON files - [string] [required] - --output, -o, --out Folder where to put the output files [string] [required] - --partials Glob pattern for the partial template files [string] - --template Path for the main template file that will be used to - generate each contract [string] [required] - --backend The backing Ethereum library your app uses. For - TypeScript, either 'web3' or 'ethers'. Ethers - auto-converts small ints to numbers whereas Web3 doesn't. - For Python, the only possibility is Web3.py - [string] [choices: "web3", "ethers"] [default: "web3"] - --network-id ID of the network where contract ABIs are nested in - artifacts [number] [default: 50] - --language Language of output file to generate - [string] [choices: "TypeScript", "Python"] [default: "TypeScript"] - -Examples: - abi-gen --abis 'src/artifacts/**/*.json' Full usage example - --out 'src/contracts/generated/' - --partials - 'src/templates/partials/**/*.handlebars' - --template - 'src/templates/contract.handlebars' - -``` - -You're required to pass a [glob]() template where your abi files are located. -TL;DR - here is the example from 0x.js. - -`--abis 'src/artifacts/@(Exchange|Token|TokenTransferProxy|EtherToken|TokenRegistry).json` - -We could've just used `--abis 'src/artifacts/*.json` but we wanted to exclude some of the abi files. - -The abi file should be either a [Truffle](http://truffleframework.com/) contract artifact (a JSON object with an abi key) or a JSON abi array. - -You need to also specify the location of your main template used for every contract `--template` as well as the partial templates `--partials` that can later be used from the main one. - -## How to write custom templates? - -The best way to get started is to copy [0x.js templates](https://github.com/0xProject/0x-monorepo/tree/development/packages/abi-gen-templates) and start adjusting them for your needs. -We use [handlebars](http://handlebarsjs.com/) template engine under the hood. -You need to have a master template called `contract.mustache`. it will be used to generate each contract wrapper. Although - you don't need and probably shouldn't write all your logic in a single template file. You can write [partial templates](http://handlebarsjs.com/partials.html) and as long as they are within a partials folder - they will be registered and available. - -## Which data/context do I get in my templates? - -For now you don't get much on top of methods abi, some useful helpers and a contract name because it was enough for our use-case, but if you need something else - create a PR. -See the [type definition](https://github.com/0xProject/0x-monorepo/tree/development/packages/abi-gen/src/types.ts) of what we pass to the render method. - -## Output files - -Output files will be generated within the specified output folder. If you already have some files in that folder they will be overwritten. - -Names of files, classes and methods will be converted to the standard naming conventions for the given target language. - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install dependencies - -If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: - -```bash -yarn config set workspaces-experimental true -``` - -Then install dependencies - -```bash -yarn install -``` - -You will also need to have Python 3 installed in order to build and run the tests of the command-line interface, which is integrated with the `yarn build`, `yarn test`, and `yarn lint` commands described below. More specifically, your local `pip` should resolve to the Python 3 version of `pip`, not a Python 2.x version. - -### Build - -To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory: - -```bash -PKG=@0x/abi-gen yarn build -``` - -Or continuously rebuild on change: - -```bash -PKG=@0x/abi-gen yarn watch -``` - -### Clean - -```bash -yarn clean -``` - -### Lint - -```bash -yarn lint -``` - -### CLI tests - -The files in `test-cli/` are used to test the output generated by running the command-line tool against a set of fixture contracts. These tests are integrated with `yarn build`, `yarn test`, etc, but can be run independently per the instructions below. - -Compile fixture contracts: - -``` -yarn compile:sol -``` - -Compiling the fixture contracts into ABI is done ahead of time, and the ABI is checked in to `git`, in order to speed up test run time. Therefore, this compilation does not happen automatically as part of `yarn build`, and must be run explicitly after making any changes to the fixture contracts; and, any proposed changes to the fixture contracts should be accompanied by changes to the corresponding compilation artifacts. - -Generate wrappers (and build them, in the case of TypeScript), and build unit tests: - -``` -yarn test_cli:build -``` - -Run unit tests and check diffs of generated wrappers vs known wrappers: - -``` -yarn test_cli -``` - -Known-good wrappers have been previously committed and are kept in `test-cli/expected-output/{language}`. They are intended to provide sample output and should be kept in sync with the generating code. When making changes to this project or `@0x/abi-gen-templates`, run `yarn test_cli:prebuild` to generate fresh code into `test-cli/output/{language}`, and then manually copy it to `test-cli/expected-output/{language}`. - -Run linters against generated code: - -``` -yarn test_cli:lint -``` diff --git a/packages/abi-gen/bin/abi-gen.js b/packages/abi-gen/bin/abi-gen.js deleted file mode 100755 index 73ffe76ed4..0000000000 --- a/packages/abi-gen/bin/abi-gen.js +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/env node -require('../lib/src/index.js'); diff --git a/packages/abi-gen/compiler.json b/packages/abi-gen/compiler.json deleted file mode 100644 index 29e890fc01..0000000000 --- a/packages/abi-gen/compiler.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "artifactsDir": "./test-cli/fixtures/artifacts", - "contractsDir": "./test-cli/fixtures/contracts", - "useDockerisedSolc": false, - "isOfflineMode": false, - "shouldSaveStandardInput": true, - "compilerSettings": { - "evmVersion": "constantinople", - "optimizer": { - "enabled": true, - "runs": 1000000, - "details": { "yul": true, "deduplicate": true, "cse": true, "constantOptimizer": true } - }, - "outputSelection": { - "*": { - "*": [ - "abi", - "evm.bytecode.object", - "evm.bytecode.sourceMap", - "evm.deployedBytecode.object", - "evm.deployedBytecode.sourceMap", - "devdoc" - ] - } - } - }, - "contracts": ["AbiGenDummy.sol", "LibDummy.sol", "TestLibDummy.sol"] -} diff --git a/packages/abi-gen/coverage/.gitkeep b/packages/abi-gen/coverage/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/abi-gen/package.json b/packages/abi-gen/package.json deleted file mode 100644 index 100470720a..0000000000 --- a/packages/abi-gen/package.json +++ /dev/null @@ -1,123 +0,0 @@ -{ - "name": "@0x/abi-gen", - "version": "5.3.1", - "engines": { - "node": ">=6.12" - }, - "description": "Generate contract wrappers from ABI and handlebars templates", - "main": "lib/src/index.js", - "types": "lib/src/index.d.ts", - "scripts": { - "lint": "tslint --format stylish --project .", - "fix": "tslint --fix --format stylish --project . && yarn lint-contracts", - "clean": "shx rm -rf lib && yarn test_cli:clean", - "build": "tsc -b && yarn generate_contract_wrappers && yarn prettier_contract_wrappers && yarn test_cli:build", - "build:ci": "yarn build", - "test": "run-p run_mocha && yarn test_cli", - "test:circleci": "yarn test:coverage && yarn test_cli", - "run_mocha": "(uname -s | grep -q Darwin && echo 'HACK! skipping mocha run due to https://github.com/0xProject/0x-monorepo/issues/2000') || mocha --require source-map-support/register --require make-promises-safe lib/test/*_test.js --timeout 100000 --bail --exit", - "test:coverage": "nyc npm run test --all && yarn coverage:report:lcov", - "coverage:report:lcov": "nyc report --reporter=text-lcov > coverage/lcov.info", - "test_cli": "run-p test_cli:test_typescript diff_contract_wrappers test_cli:lint", - "test_cli:clean": "rm -rf test-cli/test_typescript/lib", - "test_cli:build": "tsc --project test-cli/tsconfig.json", - "test_cli:test_typescript": "mocha --require source-map-support/register --require make-promises-safe test-cli/test_typescript/lib/**/*_test.js --timeout 100000 --bail --exit", - "test_cli:lint": "run-p test_cli:lint_solidity # test_cli:lint_python test_cli:lint_typescript # HACK: typescript and python lint disabled because formatterr fails", - "test_cli:lint_solidity": "solhint -c ../../contracts/.solhint.json test-cli/fixtures/contracts/*.sol", - "test_cli:lint_typescript": "prettier --check ./test-cli/output/typescript/* --config ../../.prettierrc", - "test_cli:lint_python": "pip install -r test-cli/fixtures/python-requirements.txt && run-p test_cli:lint_python:black test_cli:lint_python:mypy test_cli:lint_python:pylint", - "test_cli:lint_python:black": "black --line-length=79 --check ./test-cli/output/python/*", - "test_cli:lint_python:mypy": "MYPYPATH=./stubs mypy ./test-cli/output/python", - "test_cli:lint_python:pylint": "PYTHONPATH=../../python-packages/contract_wrappers/src pylint --rcfile=test-cli/fixtures/pylintrc ./test-cli/output/python/*", - "rebuild_and_test": "run-s build test", - "test:profiler": "SOLIDITY_PROFILER=true run-s build run_mocha profiler:report:html", - "test:trace": "SOLIDITY_REVERT_TRACE=true run-s build run_mocha", - "clean:sol": "rm -rf test-cli/artifacts", - "compile:sol": "sol-compiler", - "watch:sol": "sol-compiler -w", - "prettier_contract_wrappers": "prettier --write ./test-cli/output/typescript/* --config ../../.prettierrc", - "generate_contract_wrappers": "run-p gen_typescript gen_python", - "gen_typescript": "abi-gen --abis ${npm_package_config_abis} --debug --output ./test-cli/output/typescript --backend ethers", - "gen_python": "pip install regex==2019.11.1 && pip install black && abi-gen --abis ${npm_package_config_abis} --output ./test-cli/output/python --language Python", - "diff_contract_wrappers": "git diff --exit-code ./test-cli/output", - "coverage:report:text": "istanbul report text", - "coverage:report:html": "istanbul report html && open coverage/index.html", - "profiler:report:html": "istanbul report html && open coverage/index.html", - "contracts:gen": "contracts-gen generate" - }, - "config": { - "abis": "./test-cli/fixtures/artifacts/@(AbiGenDummy|LibDummy|TestLibDummy).json", - "abis:comment": "This list is auto-generated by contracts-gen. Don't edit manually." - }, - "bin": { - "abi-gen": "bin/abi-gen.js" - }, - "repository": { - "type": "git", - "url": "https://github.com/0xProject/0x-monorepo.git" - }, - "license": "Apache-2.0", - "bugs": { - "url": "https://github.com/0xProject/0x-monorepo/issues" - }, - "homepage": "https://github.com/0xProject/0x-monorepo/packages/abi-gen/README.md", - "dependencies": { - "@0x/types": "^3.2.0", - "@0x/typescript-typings": "^5.1.1", - "@0x/utils": "^5.5.1", - "@types/toposort": "^2.0.1", - "chalk": "^2.3.0", - "change-case": "^3.0.2", - "cli-format": "^3.0.9", - "ethereum-types": "^3.2.0", - "glob": "^7.1.2", - "handlebars": "^4.1.2", - "lodash": "^4.17.11", - "mkdirp": "^0.5.1", - "tmp": "^0.0.33", - "to-snake-case": "^1.0.0", - "toposort": "^2.0.2", - "yargs": "^10.0.3" - }, - "devDependencies": { - "@0x/assert": "^3.0.9", - "@0x/base-contract": "^6.2.3", - "@0x/contracts-gen": "^2.0.10", - "@0x/dev-utils": "^3.3.0", - "@0x/json-schemas": "^5.1.0", - "@0x/sol-compiler": "^4.1.1", - "@0x/subproviders": "^6.1.1", - "@0x/tslint-config": "^4.1.0", - "@0x/web3-wrapper": "^7.2.0", - "@types/glob": "5.0.35", - "@types/mkdirp": "^0.5.2", - "@types/mocha": "^5.2.7", - "@types/node": "12.12.54", - "@types/tmp": "^0.0.33", - "@types/yargs": "^11.0.0", - "chai": "^4.0.1", - "chai-as-promised": "^7.1.0", - "chai-bignumber": "^3.0.0", - "dirty-chai": "^2.0.1", - "ethers": "~4.0.4", - "make-promises-safe": "^1.1.0", - "mocha": "^6.2.0", - "npm-run-all": "^4.1.2", - "shx": "^0.2.2", - "sinon": "^4.0.0", - "solhint": "^1.4.1", - "tslint": "5.11.0", - "typescript": "3.0.1" - }, - "publishConfig": { - "access": "public" - }, - "files": [ - "bin/*", - "templates/*", - "*.js", - "*.ts", - "*.map" - ], - "gitHead": "4f91bfd907996b2f4dd383778b50c479c2602b56" -} diff --git a/packages/abi-gen/src/globals.d.ts b/packages/abi-gen/src/globals.d.ts deleted file mode 100644 index 94e63a32de..0000000000 --- a/packages/abi-gen/src/globals.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -declare module '*.json' { - const json: any; - /* tslint:disable */ - export default json; - /* tslint:enable */ -} diff --git a/packages/abi-gen/src/index.ts b/packages/abi-gen/src/index.ts deleted file mode 100644 index 8d89354072..0000000000 --- a/packages/abi-gen/src/index.ts +++ /dev/null @@ -1,303 +0,0 @@ -#!/usr/bin/env node -import { AbiEncoder, abiUtils, logUtils } from '@0x/utils'; -import chalk from 'chalk'; -import * as changeCase from 'change-case'; -import { execSync } from 'child_process'; -import * as cliFormat from 'cli-format'; -import { AbiDefinition, ConstructorAbi, ContractAbi, DevdocOutput, EventAbi, MethodAbi } from 'ethereum-types'; -import { sync as globSync } from 'glob'; -import * as Handlebars from 'handlebars'; -import * as _ from 'lodash'; -import * as mkdirp from 'mkdirp'; -import * as yargs from 'yargs'; - -import { registerPythonHelpers } from './python_handlebars_helpers'; -import { ContextData, ContractsBackend, ParamKind } from './types'; -import { utils } from './utils'; - -const ABI_TYPE_CONSTRUCTOR = 'constructor'; -const ABI_TYPE_METHOD = 'function'; -const ABI_TYPE_EVENT = 'event'; -const DEFAULT_CHAIN_ID = 1337; -const DEFAULT_BACKEND = 'web3'; - -const args = yargs - .option('abis', { - describe: 'Glob pattern to search for ABI JSON files', - type: 'string', - demandOption: true, - }) - .option('output', { - alias: ['o', 'out'], - describe: 'Folder where to put the output files', - type: 'string', - normalize: true, - demandOption: true, - }) - .option('partials', { - describe: 'Glob pattern for the partial template files', - type: 'string', - implies: 'template', - }) - .option('template', { - describe: - 'Path for the main template file that will be used to generate each contract. Default templates are used based on the --language parameter.', - type: 'string', - normalize: true, - }) - .option('backend', { - describe: `The backing Ethereum library your app uses. For TypeScript, either 'web3' or 'ethers'. Ethers auto-converts small ints to numbers whereas Web3 doesn't. For Python, the only possibility is Web3.py`, - type: 'string', - choices: [ContractsBackend.Web3, ContractsBackend.Ethers], - default: DEFAULT_BACKEND, - }) - .option('chain-id', { - describe: 'ID of the chain where contract ABIs are nested in artifacts', - type: 'number', - default: DEFAULT_CHAIN_ID, - }) - .option('language', { - describe: 'Language of output file to generate', - type: 'string', - choices: ['TypeScript', 'Python'], - default: 'TypeScript', - }) - .example( - "$0 --abis 'src/artifacts/**/*.json' --out 'src/contracts/generated/' --debug --partials 'src/templates/partials/**/*.handlebars' --template 'src/templates/contract.handlebars'", - 'Full usage example', - ).argv; - -const templateFilename = args.template || `${__dirname}/../../templates/${args.language}/contract.handlebars`; -const mainTemplate = utils.getNamedContent(templateFilename); -const template = Handlebars.compile(mainTemplate.content); -const abiFileNames = globSync(args.abis); -const partialTemplateFileNames = globSync( - args.partials || `${__dirname}/../../templates/${args.language}/partials/**/*.handlebars`, -); - -function registerPartials(): void { - logUtils.log(`Found ${chalk.green(`${partialTemplateFileNames.length}`)} ${chalk.bold('partial')} templates`); - for (const partialTemplateFileName of partialTemplateFileNames) { - const namedContent = utils.getNamedContent(partialTemplateFileName); - Handlebars.registerPartial(namedContent.name, namedContent.content); - } -} - -function registerTypeScriptHelpers(): void { - Handlebars.registerHelper('parameterType', utils.solTypeToTsType.bind(utils, ParamKind.Input, args.backend)); - Handlebars.registerHelper('assertionType', utils.solTypeToAssertion.bind(utils)); - Handlebars.registerHelper('returnType', utils.solTypeToTsType.bind(utils, ParamKind.Output, args.backend)); - - Handlebars.registerHelper('ifEquals', function(this: typeof Handlebars, arg1: any, arg2: any, options: any): void { - return arg1 === arg2 ? options.fn(this) : options.inverse(this); // tslint:disable-line:no-invalid-this - }); - - // Check if 0 or false exists - Handlebars.registerHelper( - 'isDefined', - (context: any): boolean => { - return context !== undefined; - }, - ); - - // Format docstring for method description - Handlebars.registerHelper( - 'formatDocstringForMethodTs', - (docString: string): Handlebars.SafeString => { - // preserve newlines - const regex = /([ ]{4,})+/gi; - const formatted = docString.replace(regex, '\n * '); - return new Handlebars.SafeString(formatted); - }, - ); - // Get docstring for method param - Handlebars.registerHelper( - 'getDocstringForParamTs', - (paramName: string, devdocParamsObj: { [name: string]: string }): Handlebars.SafeString | undefined => { - if (devdocParamsObj === undefined || devdocParamsObj[paramName] === undefined) { - return undefined; - } - return new Handlebars.SafeString(`${devdocParamsObj[paramName]}`); - }, - ); - - // Format docstring for method param - Handlebars.registerHelper( - 'formatDocstringForParamTs', - (paramName: string, desc: Handlebars.SafeString): Handlebars.SafeString => { - const docString = `@param ${paramName} ${desc}`; - const hangingIndentLength = 4; - const config = { - width: 80, - paddingLeft: ' * ', - hangingIndent: ' '.repeat(hangingIndentLength), - ansi: false, - }; - return new Handlebars.SafeString(`${cliFormat.wrap(docString, config)}`); - }, - ); -} - -if (args.language === 'TypeScript') { - registerTypeScriptHelpers(); -} else if (args.language === 'Python') { - registerPythonHelpers(); -} -registerPartials(); - -function makeLanguageSpecificName(methodName: string): string { - if (args.language === 'Python') { - let snakeCased = changeCase.snake(methodName); - // Move leading underscores to the end. - const m = /^(_*).+?(_*)$/.exec(methodName); - if (m) { - snakeCased = `${snakeCased}${m[1] || m[2]}`; - } - return snakeCased; - } - return methodName; -} - -if (_.isEmpty(abiFileNames)) { - logUtils.log(`${chalk.red(`No ABI files found.`)}`); - logUtils.log(`Please make sure you've passed the correct folder name and that the files have - ${chalk.bold('*.json')} extensions`); - process.exit(1); -} else { - logUtils.log(`Found ${chalk.green(`${abiFileNames.length}`)} ${chalk.bold('ABI')} files`); - mkdirp.sync(args.output); -} -for (const abiFileName of abiFileNames) { - const namedContent = utils.getNamedContent(abiFileName); - logUtils.log(`Processing: ${chalk.bold(namedContent.name)}...`); - const parsedContent = JSON.parse(namedContent.content); - let ABI; - let devdoc: DevdocOutput; - if (_.isArray(parsedContent)) { - ABI = parsedContent; // ABI file - } else if (parsedContent.abi !== undefined) { - ABI = parsedContent.abi; // Truffle artifact - } else if (parsedContent.compilerOutput.abi !== undefined) { - ABI = parsedContent.compilerOutput.abi; // 0x artifact - if (parsedContent.compilerOutput.devdoc !== undefined) { - devdoc = parsedContent.compilerOutput.devdoc; - } - } - if (ABI === undefined) { - logUtils.log(`${chalk.red(`ABI not found in ${abiFileName}.`)}`); - logUtils.log( - `Please make sure your ABI file is either an array with ABI entries or a truffle artifact or 0x sol-compiler artifact`, - ); - process.exit(1); - } - - const outFileName = utils.makeOutputFileName(namedContent.name); - const outFilePath = (() => { - if (args.language === 'TypeScript') { - return `${args.output}/${outFileName}.ts`; - } else if (args.language === 'Python') { - const directory = `${args.output}/${outFileName}`; - mkdirp.sync(directory); - return `${directory}/__init__.py`; - } else { - throw new Error(`Unexpected language '${args.language}'`); - } - })(); - - if (utils.isOutputFileUpToDate(outFilePath, [abiFileName, templateFilename, ...partialTemplateFileNames])) { - logUtils.log(`Already up to date: ${chalk.bold(outFilePath)}`); - continue; - } - - let deployedBytecode; - try { - deployedBytecode = parsedContent.compilerOutput.evm.deployedBytecode.object; - if ( - deployedBytecode === '' || - deployedBytecode === undefined || - deployedBytecode === '0x' || - deployedBytecode === '0x00' - ) { - throw new Error(); - } - } catch (err) { - logUtils.log( - `Couldn't find deployedBytecode for ${chalk.bold( - namedContent.name, - )}, using undefined. Found [${deployedBytecode}]`, - ); - deployedBytecode = undefined; - } - let ctor = ABI.find((abi: AbiDefinition) => abi.type === ABI_TYPE_CONSTRUCTOR) as ConstructorAbi; - if (ctor === undefined) { - ctor = utils.getEmptyConstructor(); // The constructor exists, but it's implicit in JSON's ABI definition - } - - const methodAbis = ABI.filter((abi: AbiDefinition) => abi.type === ABI_TYPE_METHOD) as MethodAbi[]; - const sanitizedMethodAbis = abiUtils.renameOverloadedMethods(methodAbis) as MethodAbi[]; - const methodsData = _.map(methodAbis, (methodAbi, methodAbiIndex: number) => { - _.forEach(methodAbi.inputs, (input, inputIndex: number) => { - if (_.isEmpty(input.name)) { - // Auto-generated getters don't have parameter names - input.name = `index_${inputIndex}`; - } - }); - const functionSignature = new AbiEncoder.Method(methodAbi).getSignature(); - const languageSpecificName: string = makeLanguageSpecificName(sanitizedMethodAbis[methodAbiIndex].name); - // This will make templates simpler - const methodData = { - ...methodAbi, - singleReturnValue: methodAbi.outputs.length === 1, - hasReturnValue: methodAbi.outputs.length !== 0, - languageSpecificName, - functionSignature, - devdoc: devdoc ? devdoc.methods[functionSignature] : undefined, - }; - return methodData; - }); - - const eventAbis = ABI.filter((abi: AbiDefinition) => abi.type === ABI_TYPE_EVENT) as EventAbi[]; - const eventsData = _.map(eventAbis, (eventAbi, eventAbiIndex: number) => { - const languageSpecificName = makeLanguageSpecificName(eventAbi.name); - - const eventData = { - ...eventAbi, - languageSpecificName, - }; - return eventData; - }); - - const shouldIncludeBytecode = methodsData.find(methodData => methodData.stateMutability === 'pure') !== undefined; - - const contextData = { - contractName: namedContent.name, - ctor, - deployedBytecode: shouldIncludeBytecode ? deployedBytecode : undefined, - ABI: ABI as ContractAbi, - ABIString: JSON.stringify(ABI), - methods: methodsData, - events: eventsData, - debug: args.debug, - }; - const renderedCode = template(contextData); - utils.writeOutputFile(outFilePath, renderedCode); - - if (args.language === 'Python') { - // use command-line tool black to reformat, if its available - try { - execSync(`black --line-length 79 ${outFilePath}`); - } catch (e) { - const BLACK_RC_CANNOT_PARSE = 123; // empirical black exit code - if (e.status === BLACK_RC_CANNOT_PARSE) { - logUtils.warn( - 'Failed to reformat generated Python with black. Exception thrown by execSync("black ...") follows.', - ); - throw e; - } else { - logUtils.warn('Failed to invoke black. Do you have it installed? Proceeding anyways...'); - } - } - } - - logUtils.log(`Created: ${chalk.bold(outFilePath)}`); -} diff --git a/packages/abi-gen/src/python_handlebars_helpers.ts b/packages/abi-gen/src/python_handlebars_helpers.ts deleted file mode 100644 index b64164bfc1..0000000000 --- a/packages/abi-gen/src/python_handlebars_helpers.ts +++ /dev/null @@ -1,210 +0,0 @@ -import * as changeCase from 'change-case'; -import * as cliFormat from 'cli-format'; -import * as Handlebars from 'handlebars'; -import toposort = require('toposort'); - -import { AbiDefinition, DataItem, MethodAbi } from 'ethereum-types'; - -import { utils } from './utils'; - -/** - * Register all Python-related Handlebars helpers - */ -export function registerPythonHelpers(): void { - Handlebars.registerHelper('equal', (lhs: any, rhs: any) => { - return lhs === rhs; - }); - Handlebars.registerHelper('safeString', (str: string) => new Handlebars.SafeString(str)); - Handlebars.registerHelper('parameterType', utils.solTypeToPyType.bind(utils)); - Handlebars.registerHelper('returnType', utils.solTypeToPyType.bind(utils)); - Handlebars.registerHelper('toPythonIdentifier', utils.toPythonIdentifier.bind(utils)); - Handlebars.registerHelper('sanitizeDevdocDetails', (_methodName: string, devdocDetails: string, indent: number) => { - // wrap to 80 columns, assuming given indent, so that generated - // docstrings can pass pycodestyle checks. also, replace repeated - // spaces, likely caused by leading indents in the Solidity, because - // they cause repeated spaces in the output, and in particular they may - // cause repeated spaces at the beginning of a line in the docstring, - // which leads to "unexpected indent" errors when generating - // documentation. - if (devdocDetails === undefined || devdocDetails.length === 0) { - return ''; - } - const columnsPerRow = 80; - return new Handlebars.SafeString( - `\n${cliFormat.wrap(devdocDetails.replace(/ +/g, ' ') || '', { - paddingLeft: ' '.repeat(indent), - width: columnsPerRow, - ansi: false, - })}\n`, - ); - }); - Handlebars.registerHelper('makeParameterDocstringRole', (name: string, description: string, indent: number) => { - let docstring = `:param ${name}:`; - if (description && description.length > 0) { - docstring = `${docstring} ${description}`; - } - return new Handlebars.SafeString(utils.wrapPythonDocstringRole(docstring, indent)); - }); - Handlebars.registerHelper( - 'makeReturnDocstringRole', - (description: string, indent: number) => - new Handlebars.SafeString( - utils.wrapPythonDocstringRole(`:returns: ${description.replace(/ +/g, ' ')}`, indent), - ), - ); - Handlebars.registerHelper( - 'makeEventParameterDocstringRole', - (eventName: string, indent: number) => - new Handlebars.SafeString( - utils.wrapPythonDocstringRole( - `:param tx_hash: hash of transaction emitting ${eventName} event`, - indent, - ), - ), - ); - Handlebars.registerHelper('tupleDefinitions', (abisJSON: string) => { - const abis: AbiDefinition[] = JSON.parse(abisJSON); - // build an array of objects, each of which has one key, the Python - // name of a tuple, with a string value holding the body of a Python - // class representing that tuple. Using a key-value object conveniently - // filters duplicate references to the same tuple. - const tupleBodies: { [pythonTupleName: string]: string } = {}; - // build an array of tuple dependencies, whose format conforms to the - // expected input to toposort, a function to do a topological sort, - // which will help us declare tuples in the proper order, avoiding - // references to tuples that haven't been declared yet. - const tupleDependencies: Array<[string, string]> = []; - for (const abi of abis) { - let parameters: DataItem[] = []; - if (abi.hasOwnProperty('inputs')) { - // HACK(feuGeneA): using "as MethodAbi" below, but abi - // could just as well be ConstructorAbi, EventAbi, etc. We - // just need to tell the TypeScript compiler that it's NOT - // FallbackAbi, or else it would complain, "Property - // 'inputs' does not exist on type 'AbiDefinition'. - // Property 'inputs' does not exist on type - // 'FallbackAbi'.", despite the enclosing if statement. - // tslint:disable:no-unnecessary-type-assertion - parameters = parameters.concat((abi as MethodAbi).inputs); - } - if (abi.hasOwnProperty('outputs')) { - // HACK(feuGeneA): same as described above, except here we - // KNOW that it's a MethodAbi, given the enclosing if - // statement, because that's the only AbiDefinition subtype - // that actually has an outputs field. - parameters = parameters.concat((abi as MethodAbi).outputs); - } - for (const parameter of parameters) { - utils.extractTuples(parameter, tupleBodies, tupleDependencies); - } - } - // build up a list of tuples to declare. the order they're pushed into - // this array is the order they will be declared. - const tuplesToDeclare = []; - // first push the ones that have dependencies - tuplesToDeclare.push(...toposort(tupleDependencies)); - // then push any remaining bodies (the ones that DON'T have - // dependencies) - for (const pythonTupleName in tupleBodies) { - if (!tuplesToDeclare.includes(pythonTupleName)) { - tuplesToDeclare.push(pythonTupleName); - } - } - // now iterate over those ordered tuples-to-declare, and prefix the - // corresponding class bodies with their class headers, to form full - // class declarations. - const tupleDeclarations = []; - for (const pythonTupleName of tuplesToDeclare) { - if (tupleBodies[pythonTupleName]) { - tupleDeclarations.push( - `class ${pythonTupleName}(TypedDict):\n """Python representation of a tuple or struct.\n\n Solidity compiler output does not include the names of structs that appear\n in method definitions. A tuple found in an ABI may have been written in\n Solidity as a literal, anonymous tuple, or it may have been written as a\n named \`struct\`:code:, but there is no way to tell from the compiler\n output. This class represents a tuple that appeared in a method\n definition. Its name is derived from a hash of that tuple's field names,\n and every method whose ABI refers to a tuple with that same list of field\n names will have a generated wrapper method that refers to this class.\n\n Any members of type \`bytes\`:code: should be encoded as UTF-8, which can be\n accomplished via \`str.encode("utf_8")\`:code:\n """${ - tupleBodies[pythonTupleName] - }`, - ); - } - } - // finally, join the class declarations together for the output file - return new Handlebars.SafeString(tupleDeclarations.join('\n\n\n')); - }); - Handlebars.registerHelper('docBytesIfNecessary', (abisJSON: string) => { - const abis: AbiDefinition[] = JSON.parse(abisJSON); - // see if any ABIs accept params of type bytes, and if so then emit - // explanatory documentation string. - for (const abi of abis) { - if (abi.hasOwnProperty('inputs')) { - // HACK(feuGeneA): using "as MethodAbi" below, but abi - // could just as well be ConstructorAbi, EventAbi, etc. We - // just need to tell the TypeScript compiler that it's NOT - // FallbackAbi, or else it would complain, "Property - // 'inputs' does not exist on type 'AbiDefinition'. - // Property 'inputs' does not exist on type - // 'FallbackAbi'.", despite the enclosing if statement. - // tslint:disable:no-unnecessary-type-assertion - if ((abi as MethodAbi).inputs) { - for (const input of (abi as MethodAbi).inputs) { - if (input.type === 'bytes') { - return new Handlebars.SafeString( - '\n\n All method parameters of type `bytes`:code: should be encoded as UTF-8,\n which can be accomplished via `str.encode("utf_8")`:code:.\n ', - ); - } - } - } - } - } - return ''; - }); - Handlebars.registerHelper('toPythonClassname', (sourceName: string) => { - let pascalCased = changeCase.pascal(sourceName); - // Retain trailing underscores. - const m = /^.+?(_*)$/.exec(sourceName); - if (m) { - pascalCased = `${pascalCased}${m[1]}`; - } - return new Handlebars.SafeString(pascalCased); - }); - Handlebars.registerHelper( - 'makeOutputsValue', - /** - * Produces a Python expression representing the return value from a - * Solidity function. - * @param pythonVariable the name of the Python variable holding the value - * to be used to populate the output expression. - * @param abiOutputs the "outputs" object of the function's ABI. - */ - (pythonVariable: string, abiOutputs: DataItem[]) => { - if (abiOutputs.length === 1) { - return new Handlebars.SafeString(solValueToPyValue(pythonVariable, abiOutputs[0])); - } else { - let tupleValue = '('; - for (let i = 0; i < abiOutputs.length; i++) { - tupleValue += `${pythonVariable}[${i}],`; - } - tupleValue += ')'; - return new Handlebars.SafeString(tupleValue); - } - }, - ); -} - -function solValueToPyValue(pythonVariable: string, abiItem: DataItem): string { - const pythonTypeName = utils.solTypeToPyType(abiItem); - if (pythonTypeName.match(/List\[.*\]/) !== null) { - return `[${solValueToPyValue('element', { - ...abiItem, - type: abiItem.type.replace('[]', ''), - })} for element in ${pythonVariable}]`; - } else { - let pyValue = `${pythonTypeName}(`; - if (abiItem.components) { - let i = 0; - for (const component of abiItem.components) { - pyValue += `${component.name}=${pythonVariable}[${i}],`; - i++; - } - } else { - pyValue += pythonVariable; - } - pyValue += ')'; - return pyValue; - } -} diff --git a/packages/abi-gen/src/types.ts b/packages/abi-gen/src/types.ts deleted file mode 100644 index b02259f754..0000000000 --- a/packages/abi-gen/src/types.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { ContractAbi, EventAbi, MethodAbi } from 'ethereum-types'; -export enum ParamKind { - Input = 'input', - Output = 'output', -} - -export enum ContractsBackend { - Web3 = 'web3', - Ethers = 'ethers', -} - -export interface Method extends MethodAbi { - singleReturnValue: boolean; - hasReturnValue: boolean; - languageSpecificName: string; - functionSignature: string; -} - -export interface ContextData { - contractName: string; - ABI: ContractAbi; - methods: Method[]; - events: EventAbi[]; -} diff --git a/packages/abi-gen/src/utils.ts b/packages/abi-gen/src/utils.ts deleted file mode 100644 index b5623014c9..0000000000 --- a/packages/abi-gen/src/utils.ts +++ /dev/null @@ -1,386 +0,0 @@ -import { createHash } from 'crypto'; - -import * as changeCase from 'change-case'; -import * as cliFormat from 'cli-format'; -import { AbiType, ConstructorAbi, DataItem, TupleDataItem } from 'ethereum-types'; -import * as fs from 'fs'; -import * as _ from 'lodash'; -import * as path from 'path'; -import toSnakeCase = require('to-snake-case'); - -import { ContractsBackend, ParamKind } from './types'; - -export const utils = { - solTypeToAssertion(solName: string, solType: string): string { - const trailingArrayRegex = /\[\d*\]$/; - if (solType.match(trailingArrayRegex)) { - const assertion = `assert.isArray('${solName}', ${solName});`; - return assertion; - } else { - const solTypeRegexToTsType = [ - { - regex: '^u?int(8|16|32)?$', - assertion: `assert.isNumberOrBigNumber('${solName}', ${solName});`, - }, - { regex: '^string$', assertion: `assert.isString('${solName}', ${solName});` }, - { regex: '^address$', assertion: `assert.isString('${solName}', ${solName});` }, - { regex: '^bool$', assertion: `assert.isBoolean('${solName}', ${solName});` }, - { regex: '^u?int\\d*$', assertion: `assert.isBigNumber('${solName}', ${solName});` }, - { regex: '^bytes\\d*$', assertion: `assert.isString('${solName}', ${solName});` }, - ]; - for (const regexAndTxType of solTypeRegexToTsType) { - const { regex, assertion } = regexAndTxType; - if (solType.match(regex)) { - return assertion; - } - } - const TUPLE_TYPE_REGEX = '^tuple$'; - if (solType.match(TUPLE_TYPE_REGEX)) { - // NOTE(fabio): Omit assertions for complex types since this would require taking a type - // definition and generating an instance of that type programmatically and checking it - // against a list of know json-schemas in order to discover the correct schema assertion - // to use. This approach is brittle and error-prone. - const assertion = ''; - return assertion; - } - throw new Error(`Unknown Solidity type found: ${solType}`); - } - }, - solTypeToTsType(paramKind: ParamKind, backend: ContractsBackend, solType: string, components?: DataItem[]): string { - const trailingArrayRegex = /\[\d*\]$/; - if (solType.match(trailingArrayRegex)) { - const arrayItemSolType = solType.replace(trailingArrayRegex, ''); - const arrayItemTsType = utils.solTypeToTsType(paramKind, backend, arrayItemSolType, components); - const arrayTsType = - utils.isUnionType(arrayItemTsType) || utils.isObjectType(arrayItemTsType) - ? `Array<${arrayItemTsType}>` - : `${arrayItemTsType}[]`; - return arrayTsType; - } else { - const solTypeRegexToTsType = [ - { regex: '^string$', tsType: 'string' }, - { regex: '^address$', tsType: 'string' }, - { regex: '^bool$', tsType: 'boolean' }, - { regex: '^u?int\\d*$', tsType: 'BigNumber' }, - { regex: '^bytes\\d*$', tsType: 'string' }, - ]; - if (paramKind === ParamKind.Input) { - // web3 and ethers allow to pass those as numbers instead of bignumbers - solTypeRegexToTsType.unshift({ - regex: '^u?int(8|16|32)?$', - tsType: 'number|BigNumber', - }); - } - if (backend === ContractsBackend.Ethers && paramKind === ParamKind.Output) { - // ethers-contracts automatically converts small BigNumbers to numbers - solTypeRegexToTsType.unshift({ - regex: '^u?int(8|16|32|48)?$', - tsType: 'number', - }); - } - for (const regexAndTxType of solTypeRegexToTsType) { - const { regex, tsType } = regexAndTxType; - if (solType.match(regex)) { - return tsType; - } - } - const TUPLE_TYPE_REGEX = '^tuple$'; - if (solType.match(TUPLE_TYPE_REGEX)) { - const componentsType = _.map(components, component => { - const componentValueType = utils.solTypeToTsType( - paramKind, - backend, - component.type, - component.components, - ); - const componentType = `${component.name}: ${componentValueType}`; - return componentType; - }); - const tsType = `{${componentsType.join(';')}}`; - return tsType; - } - throw new Error(`Unknown Solidity type found: ${solType}`); - } - }, - solTypeToPyType(dataItem: DataItem): string { - const solType = dataItem.type; - const trailingArrayRegex = /\[\d*\]$/; - if (solType.match(trailingArrayRegex)) { - const arrayItemPyType = utils.solTypeToPyType({ - ...dataItem, - type: dataItem.type.replace(trailingArrayRegex, ''), - }); - const arrayPyType = `List[${arrayItemPyType}]`; - return arrayPyType; - } else { - const solTypeRegexToPyType = [ - { regex: '^string$', pyType: 'str' }, - { regex: '^address$', pyType: 'str' }, - { regex: '^bool$', pyType: 'bool' }, - { regex: '^u?int\\d*$', pyType: 'int' }, - { regex: '^bytes\\d*$', pyType: 'Union[bytes, str]' }, - ]; - for (const regexAndTxType of solTypeRegexToPyType) { - const { regex, pyType } = regexAndTxType; - if (solType.match(regex)) { - return pyType; - } - } - const TUPLE_TYPE_REGEX = '^tuple$'; - if (solType.match(TUPLE_TYPE_REGEX)) { - return utils.makePythonTupleName(dataItem); - } - throw new Error(`Unknown Solidity type found: ${solType}`); - } - }, - isUnionType(tsType: string): boolean { - return tsType === 'number|BigNumber'; - }, - isObjectType(tsType: string): boolean { - return /^{.*}$/.test(tsType); - }, - getPartialNameFromFileName(filename: string): string { - const name = path.parse(filename).name; - return name; - }, - getNamedContent(filename: string): { name: string; content: string } { - const name = utils.getPartialNameFromFileName(filename); - try { - const content = fs.readFileSync(filename).toString(); - return { - name, - content, - }; - } catch (err) { - throw new Error(`Failed to read ${filename}: ${err}`); - } - }, - getEmptyConstructor(): ConstructorAbi { - return { - type: AbiType.Constructor, - stateMutability: 'nonpayable', - payable: false, - inputs: [], - }; - }, - makeOutputFileName(name: string): string { - let fileName = toSnakeCase(name); - // HACK: Snake case doesn't make a lot of sense for abbreviated names but we can't reliably detect abbreviations - // so we special-case the abbreviations we use. - fileName = fileName.replace('z_r_x', 'zrx').replace('e_r_c', 'erc'); - return fileName; - }, - writeOutputFile(filePath: string, renderedTsCode: string): void { - fs.writeFileSync(filePath, renderedTsCode); - }, - isOutputFileUpToDate(outputFile: string, sourceFiles: string[]): boolean { - const sourceFileModTimeMs = sourceFiles.map(file => fs.statSync(file).mtimeMs); - try { - const outFileModTimeMs = fs.statSync(outputFile).mtimeMs; - return sourceFileModTimeMs.find(sourceMs => sourceMs > outFileModTimeMs) === undefined; - } catch (err) { - if (err.code === 'ENOENT') { - return false; - } else { - throw err; - } - } - }, - /** - * simply concatenate all of the names of the components, and convert that - * concatenation into PascalCase to conform to Python convention. - */ - makePythonTupleName(tuple: DataItem): string { - if (tuple.internalType !== undefined) { - return tuple.internalType - .replace('struct ', '') - .replace('.', '') - .replace(/\[\]/g, ''); - } else { - const tupleComponents = tuple.components; - const lengthOfHashSuffix = 8; - return `Tuple0x${createHash('MD5') - .update(_.map(tupleComponents, component => component.name).join('_')) - .digest() - .toString('hex') - .substring(0, lengthOfHashSuffix)}`; - } - }, - /** - * @returns a string that is a Python code snippet that's intended to be - * used as the second parameter to a TypedDict() instantiation; value - * looks like "{ 'python_dict_key': python_type, ... }". - */ - makePythonTupleClassBody(tupleComponents: DataItem[]): string { - let toReturn: string = ''; - for (const tupleComponent of tupleComponents) { - toReturn = `${toReturn}\n\n ${tupleComponent.name}: ${utils.solTypeToPyType(tupleComponent)}`; - } - toReturn = `${toReturn}`; - return toReturn; - }, - /** - * used to generate Python-parseable identifier names for parameters to - * contract methods. - */ - toPythonIdentifier(input: string): string { - let snakeCased = changeCase.snake(input); - const pythonReservedWords = [ - 'False', - 'None', - 'True', - 'and', - 'as', - 'assert', - 'break', - 'class', - 'continue', - 'def', - 'del', - 'elif', - 'else', - 'except', - 'finally', - 'for', - 'from', - 'global', - 'if', - 'import', - 'in', - 'is', - 'lambda', - 'nonlocal', - 'not', - 'or', - 'pass', - 'raise', - 'return', - 'try', - 'while', - 'with', - 'yield', - ]; - const pythonBuiltins = [ - 'abs', - 'delattr', - 'hash', - 'memoryview', - 'set', - 'all', - 'dict', - 'help', - 'min', - 'setattr', - 'any', - 'dir', - 'hex', - 'next', - 'slice', - 'ascii', - 'divmod', - 'id', - 'object', - 'sorted', - 'bin', - 'enumerate', - 'input', - 'oct', - 'staticmethod', - 'bool', - 'eval', - 'int', - 'open', - 'str', - 'breakpoint', - 'exec', - 'isinstance', - 'ord', - 'sum', - 'bytearray', - 'filter', - 'issubclass', - 'pow', - 'super', - 'bytes', - 'float', - 'iter', - 'print', - 'tuple', - 'callable', - 'format', - 'len', - 'property', - 'type', - 'chr', - 'frozenset', - 'list', - 'range', - 'vars', - 'classmethod', - 'getattr', - 'locals', - 'repr', - 'zip', - 'compile', - 'globals', - 'map', - 'reversed', - '__import__', - 'complex', - 'hasattr', - 'max', - 'round', - ]; - if (pythonReservedWords.includes(snakeCased) || pythonBuiltins.includes(snakeCased)) { - snakeCased = `_${snakeCased}`; - } - // Retain trailing underscores. - const m = /^.+?(_*)$/.exec(input); - if (m) { - snakeCased = `${snakeCased}${m[1]}`; - } - return snakeCased; - }, - /** - * Python docstrings are used to generate documentation, and that - * transformation supports annotation of parameters, return types, etc, via - * re-Structured Text "interpreted text roles". Per the pydocstyle linter, - * such annotations should be line-wrapped at 80 columns, with a hanging - * indent of 4 columns. This function simply returns an accordingly - * wrapped and hanging-indented `role` string. - */ - wrapPythonDocstringRole(docstring: string, indent: number): string { - const columnsPerIndent = 4; - const columnsPerRow = 80; - return cliFormat.wrap(docstring, { - paddingLeft: ' '.repeat(indent), - width: columnsPerRow, - ansi: false, - hangingIndent: ' '.repeat(columnsPerIndent), - }); - }, - extractTuples( - parameter: DataItem, - tupleBodies: { [pythonTupleName: string]: string }, // output - tupleDependencies: Array<[string, string]>, // output - ): void { - if (parameter.type === 'tuple' || parameter.type === 'tuple[]') { - const tupleDataItem = parameter as TupleDataItem; // tslint:disable-line:no-unnecessary-type-assertion - // without the above cast (which tslint complains about), tsc says - // Argument of type 'DataItem[] | undefined' is not assignable to parameter of type 'DataItem[]'. - // Type 'undefined' is not assignable to type 'DataItem[]' - // when the code below tries to access tupleDataItem.components. - const pythonTupleName = utils.makePythonTupleName(tupleDataItem); - tupleBodies[pythonTupleName] = utils.makePythonTupleClassBody(tupleDataItem.components); - for (const component of tupleDataItem.components) { - if (component.type === 'tuple' || component.type === 'tuple[]') { - tupleDependencies.push([ - utils.makePythonTupleName(component as TupleDataItem), // tslint:disable-line:no-unnecessary-type-assertion - pythonTupleName, - ]); - utils.extractTuples(component, tupleBodies, tupleDependencies); - } - } - } - }, -}; diff --git a/packages/abi-gen/stubs/eth_account/__init__.pyi b/packages/abi-gen/stubs/eth_account/__init__.pyi deleted file mode 100644 index 5caed9e96f..0000000000 --- a/packages/abi-gen/stubs/eth_account/__init__.pyi +++ /dev/null @@ -1 +0,0 @@ -class Account: ... diff --git a/packages/abi-gen/stubs/eth_account/local.pyi b/packages/abi-gen/stubs/eth_account/local.pyi deleted file mode 100644 index d0b3515699..0000000000 --- a/packages/abi-gen/stubs/eth_account/local.pyi +++ /dev/null @@ -1,3 +0,0 @@ -class LocalAccount: - address: str - ... diff --git a/packages/abi-gen/stubs/hexbytes/__init__.pyi b/packages/abi-gen/stubs/hexbytes/__init__.pyi deleted file mode 100644 index bc88efe52a..0000000000 --- a/packages/abi-gen/stubs/hexbytes/__init__.pyi +++ /dev/null @@ -1 +0,0 @@ -class HexBytes: ... diff --git a/packages/abi-gen/stubs/web3/__init__.pyi b/packages/abi-gen/stubs/web3/__init__.pyi deleted file mode 100644 index 1dfa4bb5f5..0000000000 --- a/packages/abi-gen/stubs/web3/__init__.pyi +++ /dev/null @@ -1,67 +0,0 @@ -from typing import Any, Callable, Dict, List, Optional, Union - -from hexbytes import HexBytes -from eth_account.local import LocalAccount -from web3 import datastructures -from web3.contract import Contract -from web3.providers.base import BaseProvider - - -class Web3: - class HTTPProvider(BaseProvider): - ... - - def __init__(self, provider: BaseProvider) -> None: ... - - @staticmethod - def sha3( - primitive: Optional[Union[bytes, int, None]] = None, - text: Optional[str] = None, - hexstr: Optional[str] = None - ) -> bytes: ... - - @staticmethod - def isAddress(address: str) -> bool: ... - - class middleware_stack: - @staticmethod - def get(key: str) -> Callable: ... - - def inject( - self, middleware_func: object, layer: object - ) -> None: ... - - ... - - middleware_onion: middleware_stack - - class net: - version: str - ... - - - class Eth: - defaultAccount: str - accounts: List[str] - chainId: int - ... - - class account: - @staticmethod - def privateKeyToAccount(private_key: str) -> LocalAccount: ... - ... - - @staticmethod - def getTransactionReceipt(tx_hash: Union[HexBytes, bytes]) -> Any: ... - - @staticmethod - def contract(address: str, abi: Dict) -> Contract: ... - ... - - @staticmethod - def isAddress(address: str) -> bool: ... - ... - - eth: Eth - - ... diff --git a/packages/abi-gen/stubs/web3/contract.pyi b/packages/abi-gen/stubs/web3/contract.pyi deleted file mode 100644 index 6f575e5b39..0000000000 --- a/packages/abi-gen/stubs/web3/contract.pyi +++ /dev/null @@ -1,17 +0,0 @@ -from typing import Any - - -class Contract: - def call(self): ... - - functions: Any - - events: Any - ... - - -class ContractFunction: - def __call__(self, *args, **kwargs): - ... - - ... diff --git a/packages/abi-gen/stubs/web3/datastructures.pyi b/packages/abi-gen/stubs/web3/datastructures.pyi deleted file mode 100644 index fac8f29268..0000000000 --- a/packages/abi-gen/stubs/web3/datastructures.pyi +++ /dev/null @@ -1,5 +0,0 @@ -class NamedElementOnion: - ... - -class AttributeDict: - ... \ No newline at end of file diff --git a/packages/abi-gen/stubs/web3/exceptions.pyi b/packages/abi-gen/stubs/web3/exceptions.pyi deleted file mode 100644 index 83abf973d1..0000000000 --- a/packages/abi-gen/stubs/web3/exceptions.pyi +++ /dev/null @@ -1,2 +0,0 @@ -class BadFunctionCallOutput(Exception): - ... diff --git a/packages/abi-gen/stubs/web3/providers/__init__.pyi b/packages/abi-gen/stubs/web3/providers/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/abi-gen/stubs/web3/providers/base.pyi b/packages/abi-gen/stubs/web3/providers/base.pyi deleted file mode 100644 index 82ca9e3da1..0000000000 --- a/packages/abi-gen/stubs/web3/providers/base.pyi +++ /dev/null @@ -1,2 +0,0 @@ -class BaseProvider: - ... diff --git a/packages/abi-gen/templates/Python/contract.handlebars b/packages/abi-gen/templates/Python/contract.handlebars deleted file mode 100644 index 8e2d38231c..0000000000 --- a/packages/abi-gen/templates/Python/contract.handlebars +++ /dev/null @@ -1,133 +0,0 @@ -"""Generated wrapper for {{contractName}} Solidity contract.""" - -# pylint: disable=too-many-arguments - -import json -from typing import ( # pylint: disable=unused-import - Any, - List, - Optional, - Tuple, - Union, -) - -from eth_utils import to_checksum_address -from mypy_extensions import TypedDict # pylint: disable=unused-import -from hexbytes import HexBytes -from web3 import Web3 -from web3.contract import ContractFunction -from web3.datastructures import AttributeDict -from web3.providers.base import BaseProvider - -from zero_ex.contract_wrappers.bases import ContractMethod, Validator -from zero_ex.contract_wrappers.tx_params import TxParams - - -# Try to import a custom validator class definition; if there isn't one, -# declare one that we can instantiate for the default argument to the -# constructor for {{contractName}} below. -try: - # both mypy and pylint complain about what we're doing here, but this - # works just fine, so their messages have been disabled here. - from . import ( # type: ignore # pylint: disable=import-self - {{contractName}}Validator, - ) -except ImportError: - - class {{contractName}}Validator( # type: ignore - Validator - ): - """No-op input validator.""" - - -try: - from .middleware import MIDDLEWARE # type: ignore -except ImportError: - pass - - -{{tupleDefinitions ABIString}} - -{{#each methods}} -{{> method_class contractName=../contractName}} -{{/each}} - -# pylint: disable=too-many-public-methods,too-many-instance-attributes -class {{contractName}}: - """Wrapper class for {{contractName}} Solidity contract.{{docBytesIfNecessary ABIString}}""" -{{#each methods}} - {{toPythonIdentifier this.languageSpecificName}}: {{toPythonClassname this.languageSpecificName}}Method - """Constructor-initialized instance of - :class:`{{toPythonClassname this.languageSpecificName}}Method`. - """ - -{{/each}} - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - validator: {{contractName}}Validator = None, - ): - """Get an instance of wrapper for smart contract. - - :param web3_or_provider: Either an instance of `web3.Web3`:code: or - `web3.providers.base.BaseProvider`:code: - :param contract_address: where the contract has been deployed - :param validator: for validation of method inputs. - """ - # pylint: disable=too-many-statements - - self.contract_address = contract_address - - if not validator: - validator = {{contractName}}Validator(web3_or_provider, contract_address) - - web3 = None - if isinstance(web3_or_provider, BaseProvider): - web3 = Web3(web3_or_provider) - elif isinstance(web3_or_provider, Web3): - web3 = web3_or_provider - else: - raise TypeError( - "Expected parameter 'web3_or_provider' to be an instance of either" - + " Web3 or BaseProvider" - ) - - # if any middleware was imported, inject it - try: - MIDDLEWARE - except NameError: - pass - else: - try: - for middleware in MIDDLEWARE: - web3.middleware_onion.inject( - middleware['function'], layer=middleware['layer'], - ) - except ValueError as value_error: - if value_error.args == ("You can't add the same un-named instance twice",): - pass - - self._web3_eth = web3.eth - - {{#if methods}} - functions = self._web3_eth.contract(address=to_checksum_address(contract_address), abi={{contractName}}.abi()).functions - - {{#each methods}} - self.{{toPythonIdentifier this.languageSpecificName}} = {{toPythonClassname this.languageSpecificName}}Method(web3_or_provider, contract_address, functions.{{this.name}}{{#if this.inputs}}, validator{{/if}}) - - {{/each}} - {{/if}} -{{#each events}} -{{> event contractName=../contractName}} -{{/each}} - - @staticmethod - def abi(): - """Return the ABI to the underlying contract.""" - return json.loads( - '{{{ABIString}}}' # noqa: E501 (line-too-long) - ) - -# pylint: disable=too-many-lines diff --git a/packages/abi-gen/templates/Python/partials/call_return_type.handlebars b/packages/abi-gen/templates/Python/partials/call_return_type.handlebars deleted file mode 100644 index 6c6f7092a4..0000000000 --- a/packages/abi-gen/templates/Python/partials/call_return_type.handlebars +++ /dev/null @@ -1,11 +0,0 @@ -{{~#if outputs~}} -{{#if outputs.length}} -{{#singleReturnValue}} -{{#returnType outputs.[0]}}{{~/returnType~}} -{{/singleReturnValue}} -{{^singleReturnValue}} -Tuple[{{#each outputs}}{{#returnType this}}{{/returnType}}{{#unless @last}}, {{/unless}}{{/each}}] -{{~/singleReturnValue}} -{{else}}None -{{/if}} -{{else}}None{{/if~}} diff --git a/packages/abi-gen/templates/Python/partials/event.handlebars b/packages/abi-gen/templates/Python/partials/event.handlebars deleted file mode 100644 index c33d9ce1b2..0000000000 --- a/packages/abi-gen/templates/Python/partials/event.handlebars +++ /dev/null @@ -1,9 +0,0 @@ - def get_{{languageSpecificName}}_event( - self, tx_hash: Union[HexBytes, bytes] - ) -> Tuple[AttributeDict]: - """Get log entry for {{name}} event. - -{{makeEventParameterDocstringRole name 8}} - """ - tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) - return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi={{contractName}}.abi()).events.{{name}}().processReceipt(tx_receipt) diff --git a/packages/abi-gen/templates/Python/partials/method_class.handlebars b/packages/abi-gen/templates/Python/partials/method_class.handlebars deleted file mode 100644 index 9bdf47c61f..0000000000 --- a/packages/abi-gen/templates/Python/partials/method_class.handlebars +++ /dev/null @@ -1,78 +0,0 @@ - -class {{toPythonClassname this.languageSpecificName}}Method(ContractMethod): # pylint: disable=invalid-name - """Various interfaces to the {{this.name}} method.""" - - def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction{{#if inputs}}, validator: Validator=None{{/if}}): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address{{#if inputs}}, validator{{/if}}) - self._underlying_method = contract_function - - {{#if inputs}} - def validate_and_normalize_inputs(self, {{> typed_params inputs=inputs}}): - """Validate the inputs to the {{this.name}} method.""" - {{#each this.inputs}} - self.validator.assert_valid( - method_name='{{../name}}', - parameter_name='{{name}}', - argument_value={{toPythonIdentifier name}}, - ) - {{#if (equal type 'address')}} - {{toPythonIdentifier this.name}} = self.validate_and_checksum_address({{toPythonIdentifier this.name}}) - {{else if (equal type 'uint256')}} - # safeguard against fractional inputs - {{toPythonIdentifier this.name}} = int({{toPythonIdentifier this.name}}) -{{/if}} -{{/each}} - return ({{> params }}) - - {{/if}} - def call(self, {{#if inputs}}{{> typed_params inputs=inputs}}, {{/if}}tx_params: Optional[TxParams] = None) -> {{> call_return_type outputs=outputs type='call'~}}: - """Execute underlying contract method via eth_call. -{{sanitizeDevdocDetails this.name this.devdoc.details 8}}{{~#if this.devdoc.params~}}{{#each this.devdoc.params}} -{{makeParameterDocstringRole @key this 8}}{{/each}}{{/if}} - :param tx_params: transaction parameters - {{#if this.constant~}} - {{#if this.devdoc.return}} -{{makeReturnDocstringRole this.devdoc.return 8}}{{/if}} - {{else}} - :returns: the return value of the underlying method. - {{/if}} - """ - {{#if inputs}} - ({{> params }}) = self.validate_and_normalize_inputs({{> params}}) - {{/if}} - tx_params = super().normalize_tx_params(tx_params) - {{#hasReturnValue}}returned = {{/hasReturnValue}}self._underlying_method({{> params}}).call(tx_params.as_dict()) - {{#hasReturnValue}} - return {{makeOutputsValue 'returned' outputs}} - {{/hasReturnValue}} - -{{^if this.constant}} - def send_transaction(self, {{#if inputs}}{{> typed_params inputs=inputs}}, {{/if}}tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: - """Execute underlying contract method via eth_sendTransaction. -{{sanitizeDevdocDetails this.name this.devdoc.details 8}}{{~#if this.devdoc.params~}}{{#each this.devdoc.params}} -{{makeParameterDocstringRole @key this 8}}{{/each}}{{/if}} - :param tx_params: transaction parameters - """ - {{#if inputs}} - ({{> params }}) = self.validate_and_normalize_inputs({{> params}}) - {{/if}} - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method({{> params}}).transact(tx_params.as_dict()) - - def build_transaction(self, {{#if inputs}}{{> typed_params inputs=inputs}}, {{/if}}tx_params: Optional[TxParams] = None) -> dict: - """Construct calldata to be used as input to the method.""" - {{#if inputs}} - ({{> params }}) = self.validate_and_normalize_inputs({{> params}}) - {{/if}} - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method({{> params}}).buildTransaction(tx_params.as_dict()) - -{{/if}} - def estimate_gas(self, {{#if inputs}}{{> typed_params inputs=inputs}}, {{/if}}tx_params: Optional[TxParams] = None) -> int: - """Estimate gas consumption of method call.""" - {{#if inputs}} - ({{> params }}) = self.validate_and_normalize_inputs({{> params}}) - {{/if}} - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method({{> params}}).estimateGas(tx_params.as_dict()) diff --git a/packages/abi-gen/templates/Python/partials/params.handlebars b/packages/abi-gen/templates/Python/partials/params.handlebars deleted file mode 100644 index 98b3dfa702..0000000000 --- a/packages/abi-gen/templates/Python/partials/params.handlebars +++ /dev/null @@ -1,3 +0,0 @@ -{{#each inputs}} -{{toPythonIdentifier name}}{{#if @last}}{{else}}, {{/if~}} -{{/each~}} diff --git a/packages/abi-gen/templates/Python/partials/return_type.handlebars b/packages/abi-gen/templates/Python/partials/return_type.handlebars deleted file mode 100644 index 787121d413..0000000000 --- a/packages/abi-gen/templates/Python/partials/return_type.handlebars +++ /dev/null @@ -1,14 +0,0 @@ -{{~#if outputs~}} -{{^if this.constant}} -Union[ -{{~/if~}} -{{#if outputs.length}} -{{#singleReturnValue}} -{{#returnType outputs.[0]}}{{~/returnType~}} -{{/singleReturnValue}} -{{^singleReturnValue}} -Tuple[{{#each outputs}}{{#returnType this}}{{/returnType}}{{#unless @last}}, {{/unless}}{{/each}}] -{{~/singleReturnValue}} -{{else}}None -{{/if}}{{^if this.constant}}, Union[HexBytes, bytes]]{{/if~}} -{{else}}{{#if this.constant}}None{{else}}Union[None, Union[HexBytes, bytes]]{{/if}}{{/if~}} diff --git a/packages/abi-gen/templates/Python/partials/typed_params.handlebars b/packages/abi-gen/templates/Python/partials/typed_params.handlebars deleted file mode 100644 index d7bc663777..0000000000 --- a/packages/abi-gen/templates/Python/partials/typed_params.handlebars +++ /dev/null @@ -1,3 +0,0 @@ -{{#each inputs}} -{{toPythonIdentifier name}}: {{#parameterType this}}{{/parameterType}}{{^if @last}}, {{/if~}} -{{/each~}} diff --git a/packages/abi-gen/templates/TypeScript/contract.handlebars b/packages/abi-gen/templates/TypeScript/contract.handlebars deleted file mode 100644 index c7c4db38e1..0000000000 --- a/packages/abi-gen/templates/TypeScript/contract.handlebars +++ /dev/null @@ -1,416 +0,0 @@ -// tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma enum-naming -// tslint:disable:whitespace no-unbound-method no-trailing-whitespace -// tslint:disable:no-unused-variable -import { - AwaitTransactionSuccessOpts, - ContractFunctionObj, - ContractTxFunctionObj, - SendTransactionOpts, - BaseContract, - {{#if events~}}SubscriptionManager,{{/if~}} - PromiseWithTransactionHash, - methodAbiToFunctionSignature, - linkLibrariesInBytecode, -} from '@0x/base-contract'; -import { schemas } from '@0x/json-schemas'; -import { - BlockParam, - BlockParamLiteral, - BlockRange, - CallData, - ContractAbi, - ContractArtifact, - DecodedLogArgs,{{#if events}} - LogWithDecodedArgs,{{/if}} - MethodAbi, - TransactionReceiptWithDecodedLogs, - TxData, - TxDataPayable, - SupportedProvider, -} from 'ethereum-types'; -import { BigNumber, classUtils, hexUtils, logUtils, providerUtils } from '@0x/utils'; -import { EventCallback, IndexedFilterValues, SimpleContractArtifact } from '@0x/types'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import { assert } from '@0x/assert'; -import * as ethers from 'ethers'; -// tslint:enable:no-unused-variable - - -{{#if events}} -export type {{contractName}}EventArgs = -{{#each events}} - | {{@root.contractName}}{{name}}EventArgs{{#if @last}};{{/if}} -{{/each}} - -export enum {{contractName}}Events { - {{#each events}} - {{name}} = '{{name}}', - {{/each}} -} - -{{#each events}} -{{> event}} - -{{/each}} -{{/if}} - -/* istanbul ignore next */ -// tslint:disable:array-type -// tslint:disable:no-parameter-reassignment -// tslint:disable-next-line:class-name -export class {{contractName}}Contract extends BaseContract { - /** - * @ignore - */ - {{#ifEquals this.deployedBytecode undefined~}} - public static deployedBytecode: string | undefined; - {{else~}} - public static deployedBytecode = '{{this.deployedBytecode}}'; - {{/ifEquals~}} - public static contractName = '{{contractName}}'; - private readonly _methodABIIndex: { [name: string]: number } = {}; - {{#if events~}} - private readonly _subscriptionManager: SubscriptionManager<{{contractName}}EventArgs, {{contractName}}Events>; - {{/if~}} - - public static async deployFrom0xArtifactAsync( - artifact: ContractArtifact | SimpleContractArtifact, - supportedProvider: SupportedProvider, - txDefaults: Partial, - logDecodeDependencies: { [contractName: string]: (ContractArtifact | SimpleContractArtifact) }, - {{> typed_params inputs=ctor.inputs}} - ): Promise<{{contractName}}Contract> { - assert.doesConformToSchema('txDefaults', txDefaults, schemas.txDataSchema, [ - schemas.addressSchema, - schemas.numberSchema, - schemas.jsNumber, - ]); - if (artifact.compilerOutput === undefined) { - throw new Error('Compiler output not found in the artifact file'); - } - const provider = providerUtils.standardizeOrThrow(supportedProvider); - const bytecode = artifact.compilerOutput.evm.bytecode.object; - const abi = artifact.compilerOutput.abi; - const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - if (Object.keys(logDecodeDependencies) !== undefined) { - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; - } - } - return {{contractName}}Contract.deployAsync(bytecode, abi, provider, txDefaults, logDecodeDependenciesAbiOnly, {{> params inputs=ctor.inputs}}); - } - - public static async deployWithLibrariesFrom0xArtifactAsync( - artifact: ContractArtifact, - libraryArtifacts: { [libraryName: string]: ContractArtifact }, - supportedProvider: SupportedProvider, - txDefaults: Partial, - logDecodeDependencies: { [contractName: string]: (ContractArtifact | SimpleContractArtifact) }, - {{> typed_params inputs=ctor.inputs}} - ): Promise<{{contractName}}Contract> { - assert.doesConformToSchema('txDefaults', txDefaults, schemas.txDataSchema, [ - schemas.addressSchema, - schemas.numberSchema, - schemas.jsNumber, - ]); - if (artifact.compilerOutput === undefined) { - throw new Error('Compiler output not found in the artifact file'); - } - const provider = providerUtils.standardizeOrThrow(supportedProvider); - const abi = artifact.compilerOutput.abi; - const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - if (Object.keys(logDecodeDependencies) !== undefined) { - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; - } - } - const libraryAddresses = await {{contractName}}Contract._deployLibrariesAsync( - artifact, - libraryArtifacts, - new Web3Wrapper(provider), - txDefaults - ); - const bytecode = linkLibrariesInBytecode( - artifact, - libraryAddresses, - ); - return {{contractName}}Contract.deployAsync(bytecode, abi, provider, txDefaults, logDecodeDependenciesAbiOnly, {{> params inputs=ctor.inputs}}); - } - - public static async deployAsync( - bytecode: string, - abi: ContractAbi, - supportedProvider: SupportedProvider, - txDefaults: Partial, - logDecodeDependencies: { [contractName: string]: ContractAbi }, - {{> typed_params inputs=ctor.inputs}} - ): Promise<{{contractName}}Contract> { - assert.isHexString('bytecode', bytecode); - assert.doesConformToSchema('txDefaults', txDefaults, schemas.txDataSchema, [ - schemas.addressSchema, - schemas.numberSchema, - schemas.jsNumber, - ]); - const provider = providerUtils.standardizeOrThrow(supportedProvider); - const constructorAbi = BaseContract._lookupConstructorAbi(abi); - [{{> params inputs=ctor.inputs}}] = BaseContract._formatABIDataItemList( - constructorAbi.inputs, - [{{> params inputs=ctor.inputs}}], - BaseContract._bigNumberToString, - ); - const iface = new ethers.utils.Interface(abi); - const deployInfo = iface.deployFunction; - const txData = deployInfo.encode(bytecode, [{{> params inputs=ctor.inputs}}]); - const web3Wrapper = new Web3Wrapper(provider); - const txDataWithDefaults = await BaseContract._applyDefaultsToContractTxDataAsync( - { - data: txData, - ...txDefaults, - }, - web3Wrapper.estimateGasAsync.bind(web3Wrapper), - ); - const txHash = await web3Wrapper.sendTransactionAsync(txDataWithDefaults); - logUtils.log(`transactionHash: ${txHash}`); - const txReceipt = await web3Wrapper.awaitTransactionSuccessAsync(txHash); - logUtils.log(`{{contractName}} successfully deployed at ${txReceipt.contractAddress}`); - const contractInstance = new {{contractName}}Contract(txReceipt.contractAddress as string, provider, txDefaults, logDecodeDependencies); - contractInstance.constructorArgs = [{{> params inputs=ctor.inputs}}]; - return contractInstance; - } - - /** - * @returns The contract ABI - */ - public static ABI(): ContractAbi { - const abi = [ - {{#each ABI}} - { {{#if (isDefined this.constant)}} - constant: {{constant}},{{/if}}{{#if (isDefined this.anonymous)}} - anonymous: {{anonymous}},{{/if}} - inputs: [ - {{#each inputs}} - {{> abi_type this}} - {{/each}} - ],{{#this.name}} - name: '{{{this}}}',{{/this.name}} - outputs: [ - {{#each outputs}} - {{> abi_type this}} - {{/each}} - ],{{#if (isDefined this.payable)}} - payable: {{payable}},{{/if}}{{#this.stateMutability}} - stateMutability: '{{this}}',{{/this.stateMutability}} - type: '{{type}}', - }, - {{/each}} - ] as ContractAbi; - return abi; - } - - protected static async _deployLibrariesAsync( - artifact: ContractArtifact, - libraryArtifacts: { [libraryName: string]: ContractArtifact }, - web3Wrapper: Web3Wrapper, - txDefaults: Partial, - libraryAddresses: { [libraryName: string]: string } = {}, - ): Promise<{ [libraryName: string]: string }> { - const links = artifact.compilerOutput.evm.bytecode.linkReferences; - // Go through all linked libraries, recursively deploying them if necessary. - for (const link of Object.values(links)) { - for (const libraryName of Object.keys(link)) { - if (!libraryAddresses[libraryName]) { - // Library not yet deployed. - const libraryArtifact = libraryArtifacts[libraryName]; - if (!libraryArtifact) { - throw new Error(`Missing artifact for linked library "${libraryName}"`); - } - // Deploy any dependent libraries used by this library. - await {{contractName}}Contract._deployLibrariesAsync( - libraryArtifact, - libraryArtifacts, - web3Wrapper, - txDefaults, - libraryAddresses, - ); - // Deploy this library. - const linkedLibraryBytecode = linkLibrariesInBytecode( - libraryArtifact, - libraryAddresses, - ); - const txDataWithDefaults = await BaseContract._applyDefaultsToContractTxDataAsync( - { - data: linkedLibraryBytecode, - ...txDefaults, - }, - web3Wrapper.estimateGasAsync.bind(web3Wrapper), - ); - const txHash = await web3Wrapper.sendTransactionAsync(txDataWithDefaults); - logUtils.log(`transactionHash: ${txHash}`); - const { contractAddress } = await web3Wrapper.awaitTransactionSuccessAsync(txHash); - logUtils.log(`${libraryArtifact.contractName} successfully deployed at ${contractAddress}`); - libraryAddresses[libraryArtifact.contractName] = contractAddress as string; - } - } - } - return libraryAddresses; - } - - public getFunctionSignature(methodName: string): string { - const index = this._methodABIIndex[methodName]; - const methodAbi = {{contractName}}Contract.ABI()[index] as MethodAbi; // tslint:disable-line:no-unnecessary-type-assertion - const functionSignature = methodAbiToFunctionSignature(methodAbi); - return functionSignature; - } - - public getABIDecodedTransactionData(methodName: string, callData: string): T { - const functionSignature = this.getFunctionSignature(methodName); - const self = (this as any) as {{contractName}}Contract; - const abiEncoder = self._lookupAbiEncoder(functionSignature); - const abiDecodedCallData = abiEncoder.strictDecode(callData); - return abiDecodedCallData; - } - - public getABIDecodedReturnData(methodName: string, callData: string): T { - const functionSignature = this.getFunctionSignature(methodName); - const self = (this as any) as {{contractName}}Contract; - const abiEncoder = self._lookupAbiEncoder(functionSignature); - const abiDecodedCallData = abiEncoder.strictDecodeReturnValue(callData); - return abiDecodedCallData; - } - - public getSelector(methodName: string): string { - const functionSignature = this.getFunctionSignature(methodName); - const self = (this as any) as {{contractName}}Contract; - const abiEncoder = self._lookupAbiEncoder(functionSignature); - return abiEncoder.getSelector(); - } - - {{#each methods}} - {{#if this.devdoc.details}} - /** - * {{formatDocstringForMethodTs this.devdoc.details}} - {{> params_docstring inputs=inputs docstrings=devdoc.params}} - {{#if devdoc.return}} - * @returns {{devdoc.return}} - {{/if}} - */ - {{/if}} - public {{languageSpecificName}}( - {{> typed_params inputs=this.inputs}} - ): Contract{{^this.constant}}Tx{{/this.constant}}FunctionObj<{{> return_type outputs=outputs ~}}> { - const self = this as any as {{../contractName}}Contract; - {{#each inputs}} - {{#assertionType name type}}{{/assertionType}} - {{/each}} - const functionSignature = '{{this.functionSignature}}'; - - return { - {{^this.constant}} - {{> method_tx}} - {{/this.constant}} - {{> method_call stateMutability=this.stateMutability}} - } - }; - {{/each}} - - {{#if events}} - /** - * Subscribe to an event type emitted by the {{contractName}} contract. - * @param eventName The {{contractName}} contract event you would like to subscribe to. - * @param indexFilterValues An object where the keys are indexed args returned by the event and - * the value is the value you are interested in. E.g `{maker: aUserAddressHex}` - * @param callback Callback that gets called when a log is added/removed - * @param isVerbose Enable verbose subscription warnings (e.g recoverable network issues encountered) - * @return Subscription token used later to unsubscribe - */ - public subscribe( - eventName: {{contractName}}Events, - indexFilterValues: IndexedFilterValues, - callback: EventCallback, - isVerbose: boolean = false, - blockPollingIntervalMs?: number, - ): string { - assert.doesBelongToStringEnum('eventName', eventName, {{contractName}}Events); - assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); - assert.isFunction('callback', callback); - const subscriptionToken = this._subscriptionManager.subscribe( - this.address, - eventName, - indexFilterValues, - {{contractName}}Contract.ABI(), - callback, - isVerbose, - blockPollingIntervalMs, - ); - return subscriptionToken; - } - - /** - * Cancel a subscription - * @param subscriptionToken Subscription token returned by `subscribe()` - */ - public unsubscribe(subscriptionToken: string): void { - this._subscriptionManager.unsubscribe(subscriptionToken); - } - - /** - * Cancels all existing subscriptions - */ - public unsubscribeAll(): void { - this._subscriptionManager.unsubscribeAll(); - } - - /** - * Gets historical logs without creating a subscription - * @param eventName The {{contractName}} contract event you would like to subscribe to. - * @param blockRange Block range to get logs from. - * @param indexFilterValues An object where the keys are indexed args returned by the event and - * the value is the value you are interested in. E.g `{_from: aUserAddressHex}` - * @return Array of logs that match the parameters - */ - public async getLogsAsync( - eventName: {{contractName}}Events, - blockRange: BlockRange, - indexFilterValues: IndexedFilterValues, - ): Promise>> { - assert.doesBelongToStringEnum('eventName', eventName, {{contractName}}Events); - assert.doesConformToSchema('blockRange', blockRange, schemas.blockRangeSchema); - assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); - const logs = await this._subscriptionManager.getLogsAsync( - this.address, - eventName, - blockRange, - indexFilterValues, - {{contractName}}Contract.ABI(), - ); - return logs; - }{{/if}} - - constructor( - address: string, - supportedProvider: SupportedProvider, - txDefaults?: Partial, - logDecodeDependencies?: { [contractName: string]: ContractAbi }, - deployedBytecode: string | undefined = {{contractName}}Contract.deployedBytecode, - ) { - super('{{contractName}}', {{contractName}}Contract.ABI(), address, supportedProvider, txDefaults, logDecodeDependencies, deployedBytecode); - classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); - {{#if events~}} - this._subscriptionManager = new SubscriptionManager<{{contractName}}EventArgs, {{contractName}}Events>( - {{contractName}}Contract.ABI(), - this._web3Wrapper, - ); - {{/if~}} - - {{contractName}}Contract.ABI().forEach((item, index) => { - if (item.type === 'function') { - const methodAbi = item as MethodAbi; - this._methodABIIndex[methodAbi.name] = index; - } - }); - } -} - -// tslint:disable:max-file-line-count -// tslint:enable:no-unbound-method no-parameter-reassignment no-consecutive-blank-lines ordered-imports align -// tslint:enable:trailing-comma whitespace no-trailing-whitespace diff --git a/packages/abi-gen/templates/TypeScript/partials/abi_type.handlebars b/packages/abi-gen/templates/TypeScript/partials/abi_type.handlebars deleted file mode 100644 index bfaad988a8..0000000000 --- a/packages/abi-gen/templates/TypeScript/partials/abi_type.handlebars +++ /dev/null @@ -1,10 +0,0 @@ -{ - name: '{{name}}', - type: '{{type}}',{{#if (isDefined indexed)}} - indexed: {{indexed}},{{/if}}{{#if components}} - components: [ - {{#each components}} - {{> abi_type this}} - {{/each}} - ]{{/if}} -}, diff --git a/packages/abi-gen/templates/TypeScript/partials/event.handlebars b/packages/abi-gen/templates/TypeScript/partials/event.handlebars deleted file mode 100644 index 61d523ca22..0000000000 --- a/packages/abi-gen/templates/TypeScript/partials/event.handlebars +++ /dev/null @@ -1,5 +0,0 @@ -export interface {{@root.contractName}}{{name}}EventArgs extends DecodedLogArgs { - {{#each inputs}} - {{name}}: {{#returnType type components}}{{/returnType}}; - {{/each}} -} diff --git a/packages/abi-gen/templates/TypeScript/partials/method_call.handlebars b/packages/abi-gen/templates/TypeScript/partials/method_call.handlebars deleted file mode 100644 index 757906711b..0000000000 --- a/packages/abi-gen/templates/TypeScript/partials/method_call.handlebars +++ /dev/null @@ -1,22 +0,0 @@ -async callAsync( - callData: Partial = {}, - defaultBlock?: BlockParam, -): Promise<{{> return_type outputs=outputs}}> { - BaseContract._assertCallParams(callData, defaultBlock); - {{#ifEquals this.stateMutability "pure" }} - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync({ data: this.getABIEncodedTransactionData(), ...callData }, defaultBlock); - } - {{else}} - const rawCallResult = await self._performCallAsync({ data: this.getABIEncodedTransactionData(), ...callData }, defaultBlock); - {{/ifEquals}} - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue<{{> return_type outputs=outputs}}>(rawCallResult); -}, -getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, [{{> normalized_params inputs=inputs}}]); -}, diff --git a/packages/abi-gen/templates/TypeScript/partials/method_tx.handlebars b/packages/abi-gen/templates/TypeScript/partials/method_tx.handlebars deleted file mode 100644 index 763bf740bc..0000000000 --- a/packages/abi-gen/templates/TypeScript/partials/method_tx.handlebars +++ /dev/null @@ -1,27 +0,0 @@ -async sendTransactionAsync( - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, -): Promise { - const txDataWithDefaults = await self._applyDefaultsToTxDataAsync( - { data: this.getABIEncodedTransactionData(), ...txData }, - this.estimateGasAsync.bind(this), - ); - if (opts.shouldValidate !== false) { - await this.callAsync(txDataWithDefaults); - } - return self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); -}, -awaitTransactionSuccessAsync( - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, -): PromiseWithTransactionHash { - return self._promiseWithTransactionHash(this.sendTransactionAsync(txData, opts), opts); -}, -async estimateGasAsync( - txData?: Partial | undefined, -): Promise { - const txDataWithDefaults = await self._applyDefaultsToTxDataAsync( - { data: this.getABIEncodedTransactionData(), ...txData } - ); - return self._web3Wrapper.estimateGasAsync(txDataWithDefaults); -}, diff --git a/packages/abi-gen/templates/TypeScript/partials/normalized_params.handlebars b/packages/abi-gen/templates/TypeScript/partials/normalized_params.handlebars deleted file mode 100644 index e6c180bda5..0000000000 --- a/packages/abi-gen/templates/TypeScript/partials/normalized_params.handlebars +++ /dev/null @@ -1,3 +0,0 @@ -{{#each inputs}} -{{name}}{{#ifEquals 'address' type}}.toLowerCase(){{/ifEquals}}{{#if @last}}{{else}},{{/if}} -{{/each}} diff --git a/packages/abi-gen/templates/TypeScript/partials/params.handlebars b/packages/abi-gen/templates/TypeScript/partials/params.handlebars deleted file mode 100644 index 2d9bb8ed96..0000000000 --- a/packages/abi-gen/templates/TypeScript/partials/params.handlebars +++ /dev/null @@ -1,3 +0,0 @@ -{{#each inputs}} -{{name}}{{#if @last}}{{else}},{{/if}} -{{/each}} diff --git a/packages/abi-gen/templates/TypeScript/partials/params_docstring.handlebars b/packages/abi-gen/templates/TypeScript/partials/params_docstring.handlebars deleted file mode 100644 index 86aa1d0aeb..0000000000 --- a/packages/abi-gen/templates/TypeScript/partials/params_docstring.handlebars +++ /dev/null @@ -1,5 +0,0 @@ -{{#each inputs}} - {{#if (getDocstringForParamTs name ../docstrings)}} - {{formatDocstringForParamTs name (getDocstringForParamTs name ../docstrings)}} - {{/if}} -{{/each}} diff --git a/packages/abi-gen/templates/TypeScript/partials/return_type.handlebars b/packages/abi-gen/templates/TypeScript/partials/return_type.handlebars deleted file mode 100644 index 77d96e8c48..0000000000 --- a/packages/abi-gen/templates/TypeScript/partials/return_type.handlebars +++ /dev/null @@ -1,10 +0,0 @@ -{{#if outputs.length}} -{{#singleReturnValue}} -{{#returnType outputs.0.type outputs.0.components}}{{/returnType}} -{{/singleReturnValue}} -{{^singleReturnValue}} -[{{#each outputs}}{{#returnType type components}}{{/returnType}}{{#unless @last}}, {{/unless}}{{/each}}] -{{/singleReturnValue}} -{{else}} -void -{{/if}} diff --git a/packages/abi-gen/templates/TypeScript/partials/typed_params.handlebars b/packages/abi-gen/templates/TypeScript/partials/typed_params.handlebars deleted file mode 100644 index c100e58f71..0000000000 --- a/packages/abi-gen/templates/TypeScript/partials/typed_params.handlebars +++ /dev/null @@ -1,3 +0,0 @@ -{{#each inputs}} - {{name}}: {{#parameterType type components}}{{/parameterType}}, -{{/each}} diff --git a/packages/abi-gen/test-cli/fixtures/artifacts/AbiGenDummy.json b/packages/abi-gen/test-cli/fixtures/artifacts/AbiGenDummy.json deleted file mode 100644 index 868bef22bb..0000000000 --- a/packages/abi-gen/test-cli/fixtures/artifacts/AbiGenDummy.json +++ /dev/null @@ -1,924 +0,0 @@ -{ - "schemaVersion": "2.0.0", - "contractName": "AbiGenDummy", - "compilerOutput": { - "abi": [ - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "bytes", - "name": "someBytes", - "type": "bytes" - }, - { - "indexed": false, - "internalType": "string", - "name": "someString", - "type": "string" - } - ], - "name": "SimpleEvent", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "_owner", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "_value", - "type": "uint256" - } - ], - "name": "Withdrawal", - "type": "event" - }, - { - "constant": true, - "inputs": [ - { - "internalType": "bytes[]", - "name": "a", - "type": "bytes[]" - } - ], - "name": "acceptsAnArrayOfBytes", - "outputs": [], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "internalType": "bytes", - "name": "a", - "type": "bytes" - } - ], - "name": "acceptsBytes", - "outputs": [], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "components": [ - { - "internalType": "uint256", - "name": "foo", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "bar", - "type": "bytes" - }, - { - "internalType": "string", - "name": "car", - "type": "string" - } - ], - "internalType": "struct AbiGenDummy.ComplexInput", - "name": "complexInput", - "type": "tuple" - } - ], - "name": "complexInputComplexOutput", - "outputs": [ - { - "components": [ - { - "components": [ - { - "internalType": "uint256", - "name": "foo", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "bar", - "type": "bytes" - }, - { - "internalType": "string", - "name": "car", - "type": "string" - } - ], - "internalType": "struct AbiGenDummy.ComplexInput", - "name": "input", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "lorem", - "type": "bytes" - }, - { - "internalType": "bytes", - "name": "ipsum", - "type": "bytes" - }, - { - "internalType": "string", - "name": "dolor", - "type": "string" - } - ], - "internalType": "struct AbiGenDummy.ComplexOutput", - "name": "", - "type": "tuple" - } - ], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "internalType": "bytes32", - "name": "hash", - "type": "bytes32" - }, - { - "internalType": "uint8", - "name": "v", - "type": "uint8" - }, - { - "internalType": "bytes32", - "name": "r", - "type": "bytes32" - }, - { - "internalType": "bytes32", - "name": "s", - "type": "bytes32" - } - ], - "name": "ecrecoverFn", - "outputs": [ - { - "internalType": "address", - "name": "signerAddress", - "type": "address" - } - ], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": false, - "inputs": [], - "name": "emitSimpleEvent", - "outputs": [], - "payable": false, - "stateMutability": "nonpayable", - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "components": [ - { - "internalType": "bytes", - "name": "someBytes", - "type": "bytes" - }, - { - "internalType": "uint32", - "name": "anInteger", - "type": "uint32" - }, - { - "internalType": "bytes[]", - "name": "aDynamicArrayOfBytes", - "type": "bytes[]" - }, - { - "internalType": "string", - "name": "aString", - "type": "string" - } - ], - "internalType": "struct AbiGenDummy.Struct[][]", - "name": "", - "type": "tuple[][]" - } - ], - "name": "methodAcceptingArrayOfArrayOfStructs", - "outputs": [], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "components": [ - { - "internalType": "bytes", - "name": "someBytes", - "type": "bytes" - }, - { - "internalType": "uint32", - "name": "anInteger", - "type": "uint32" - }, - { - "internalType": "bytes[]", - "name": "aDynamicArrayOfBytes", - "type": "bytes[]" - }, - { - "internalType": "string", - "name": "aString", - "type": "string" - } - ], - "internalType": "struct AbiGenDummy.Struct[]", - "name": "", - "type": "tuple[]" - } - ], - "name": "methodAcceptingArrayOfStructs", - "outputs": [], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "methodReturningArrayOfStructs", - "outputs": [ - { - "components": [ - { - "internalType": "bytes", - "name": "someBytes", - "type": "bytes" - }, - { - "internalType": "uint32", - "name": "anInteger", - "type": "uint32" - }, - { - "internalType": "bytes[]", - "name": "aDynamicArrayOfBytes", - "type": "bytes[]" - }, - { - "internalType": "string", - "name": "aString", - "type": "string" - } - ], - "internalType": "struct AbiGenDummy.Struct[]", - "name": "", - "type": "tuple[]" - } - ], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "methodReturningMultipleValues", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - }, - { - "internalType": "string", - "name": "", - "type": "string" - } - ], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "methodUsingNestedStructWithInnerStructNotUsedElsewhere", - "outputs": [ - { - "components": [ - { - "components": [ - { - "internalType": "uint256", - "name": "aField", - "type": "uint256" - } - ], - "internalType": "struct AbiGenDummy.StructNotDirectlyUsedAnywhere", - "name": "innerStruct", - "type": "tuple" - } - ], - "internalType": "struct AbiGenDummy.NestedStructWithInnerStructNotUsedElsewhere", - "name": "", - "type": "tuple" - } - ], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "", - "type": "bytes" - }, - { - "internalType": "string", - "name": "", - "type": "string" - } - ], - "name": "multiInputMultiOutput", - "outputs": [ - { - "internalType": "bytes", - "name": "", - "type": "bytes" - }, - { - "internalType": "bytes", - "name": "", - "type": "bytes" - }, - { - "internalType": "string", - "name": "", - "type": "string" - } - ], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "components": [ - { - "components": [ - { - "internalType": "bytes", - "name": "someBytes", - "type": "bytes" - }, - { - "internalType": "uint32", - "name": "anInteger", - "type": "uint32" - }, - { - "internalType": "bytes[]", - "name": "aDynamicArrayOfBytes", - "type": "bytes[]" - }, - { - "internalType": "string", - "name": "aString", - "type": "string" - } - ], - "internalType": "struct AbiGenDummy.Struct", - "name": "innerStruct", - "type": "tuple" - }, - { - "internalType": "string", - "name": "description", - "type": "string" - } - ], - "internalType": "struct AbiGenDummy.NestedStruct", - "name": "n", - "type": "tuple" - } - ], - "name": "nestedStructInput", - "outputs": [], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "nestedStructOutput", - "outputs": [ - { - "components": [ - { - "components": [ - { - "internalType": "bytes", - "name": "someBytes", - "type": "bytes" - }, - { - "internalType": "uint32", - "name": "anInteger", - "type": "uint32" - }, - { - "internalType": "bytes[]", - "name": "aDynamicArrayOfBytes", - "type": "bytes[]" - }, - { - "internalType": "string", - "name": "aString", - "type": "string" - } - ], - "internalType": "struct AbiGenDummy.Struct", - "name": "innerStruct", - "type": "tuple" - }, - { - "internalType": "string", - "name": "description", - "type": "string" - } - ], - "internalType": "struct AbiGenDummy.NestedStruct", - "name": "", - "type": "tuple" - } - ], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "noInputNoOutput", - "outputs": [], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "noInputSimpleOutput", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": false, - "inputs": [], - "name": "nonPureMethod", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "payable": false, - "stateMutability": "nonpayable", - "type": "function" - }, - { - "constant": false, - "inputs": [], - "name": "nonPureMethodThatReturnsNothing", - "outputs": [], - "payable": false, - "stateMutability": "nonpayable", - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "internalType": "string", - "name": "a", - "type": "string" - } - ], - "name": "overloadedMethod", - "outputs": [], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "internalType": "int256", - "name": "a", - "type": "int256" - } - ], - "name": "overloadedMethod", - "outputs": [], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "pureFunctionWithConstant", - "outputs": [ - { - "internalType": "uint256", - "name": "someConstant", - "type": "uint256" - } - ], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "requireWithConstant", - "outputs": [], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "revertWithConstant", - "outputs": [], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "name": "simpleInputNoOutput", - "outputs": [], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "name": "simpleInputSimpleOutput", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "simplePureFunction", - "outputs": [ - { - "internalType": "uint256", - "name": "result", - "type": "uint256" - } - ], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "internalType": "uint256", - "name": "x", - "type": "uint256" - } - ], - "name": "simplePureFunctionWithInput", - "outputs": [ - { - "internalType": "uint256", - "name": "sum", - "type": "uint256" - } - ], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "simpleRequire", - "outputs": [], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "simpleRevert", - "outputs": [], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "components": [ - { - "internalType": "bytes", - "name": "someBytes", - "type": "bytes" - }, - { - "internalType": "uint32", - "name": "anInteger", - "type": "uint32" - }, - { - "internalType": "bytes[]", - "name": "aDynamicArrayOfBytes", - "type": "bytes[]" - }, - { - "internalType": "string", - "name": "aString", - "type": "string" - } - ], - "internalType": "struct AbiGenDummy.Struct", - "name": "s", - "type": "tuple" - } - ], - "name": "structInput", - "outputs": [], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "structOutput", - "outputs": [ - { - "components": [ - { - "internalType": "bytes", - "name": "someBytes", - "type": "bytes" - }, - { - "internalType": "uint32", - "name": "anInteger", - "type": "uint32" - }, - { - "internalType": "bytes[]", - "name": "aDynamicArrayOfBytes", - "type": "bytes[]" - }, - { - "internalType": "string", - "name": "aString", - "type": "string" - } - ], - "internalType": "struct AbiGenDummy.Struct", - "name": "s", - "type": "tuple" - } - ], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "internalType": "address", - "name": "x", - "type": "address" - }, - { - "internalType": "uint256", - "name": "a", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "b", - "type": "uint256" - }, - { - "internalType": "address", - "name": "y", - "type": "address" - }, - { - "internalType": "uint256", - "name": "c", - "type": "uint256" - } - ], - "name": "withAddressInput", - "outputs": [ - { - "internalType": "address", - "name": "z", - "type": "address" - } - ], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "internalType": "uint256", - "name": "wad", - "type": "uint256" - } - ], - "name": "withdraw", - "outputs": [], - "payable": false, - "stateMutability": "nonpayable", - "type": "function" - } - ], - "devdoc": { - "methods": { - "acceptsAnArrayOfBytes(bytes[])": { - "details": "a method that accepts an array of bytes", - "params": { - "a": "the array of bytes being accepted" - } - }, - "complexInputComplexOutput((uint256,bytes,string))": { - "details": "Tests decoding when the input and output are complex." - }, - "ecrecoverFn(bytes32,uint8,bytes32,bytes32)": { - "details": "test that devdocs will be generated and that multiline devdocs will look okay", - "params": { - "hash": "description of some hash. Let's make this line super long to demonstrate hanging indents for method params. It has to be more than one hundred twenty columns.", - "r": "ECDSA r output", - "s": "ECDSA s output", - "v": "some v, recovery id" - }, - "return": "the signerAddress that created this signature. this line too is super long in order to demonstrate the proper hanging indentation in generated code." - }, - "multiInputMultiOutput(uint256,bytes,string)": { - "details": "Tests decoding when the input and output are complex and have more than one argument." - }, - "noInputNoOutput()": { - "details": "Tests decoding when both input and output are empty." - }, - "noInputSimpleOutput()": { - "details": "Tests decoding when input is empty and output is non-empty." - }, - "simpleInputNoOutput(uint256)": { - "details": "Tests decoding when input is not empty but output is empty." - }, - "simpleInputSimpleOutput(uint256)": { - "details": "Tests decoding when both input and output are non-empty." - }, - "structOutput()": { - "details": "a method that returns a struct", - "return": "a Struct struct" - } - } - }, - "evm": { - "bytecode": { - "linkReferences": {}, - "object": "0x608060405234801561001057600080fd5b50611624806100206000396000f3fe608060405234801561001057600080fd5b50600436106101ef5760003560e01c806377ec31ae1161010f578063bdab1688116100a2578063e796ee9611610071578063e796ee96146103c7578063ee8b86fb146103d5578063f408fb311461028f578063fa315f9d146103e8576101ef565b8063bdab16881461038d578063cd3c0b97146103a2578063d6d7618c146103aa578063d88be12f146103bf576101ef565b80639a3b6185116100de5780639a3b618514610359578063a3c2f6b614610361578063ae2dae1714610369578063bb60736214610377576101ef565b806377ec31ae146103105780637833bec01461031e5780637a791e6e1461033e5780638ee52b4e14610346576101ef565b80634582eab2116101875780635ba3c7c0116101565780635ba3c7c0146102df57806363d69c88146102e7578063647341eb146102fa57806376f15d5b14610308576101ef565b80634582eab2146102a557806345fdbdb7146102ad578063586f84b2146102b557806359c28add146102ca576101ef565b80633687617d116101c35780633687617d1461024d57806336b323961461026f5780633e9ef66a1461028f5780634303a5421461029d576101ef565b806209e437146101f45780630527c28f146101fe5780631310e444146102115780632e1a7d4d1461023a575b600080fd5b6101fc6103f6565b005b6101fc61020c366004610d98565b610433565b61022461021f366004610ec5565b610436565b6040516102319190611526565b60405180910390f35b6101fc610248366004610ec5565b61043d565b61026061025b36600461103a565b61048e565b6040516102319392919061128f565b61028261027d366004610e51565b61052e565b60405161023191906111d2565b6101fc61020c366004610e92565b610224610610565b6101fc610617565b6101fc61067c565b6102bd6106ae565b60405161023191906114b1565b6102d26106b6565b60405161023191906114bc565b6101fc6106be565b6102826102f5366004610cbb565b610723565b6101fc61020c366004611007565b61022461072c565b6101fc61020c366004610e16565b61033161032c366004610edd565b61073a565b60405161023191906113c5565b6101fc6107f7565b610224610354366004610ec5565b6107fc565b6101fc610802565b61022461080d565b6101fc61020c366004610f77565b61037f610812565b60405161023192919061152f565b61039561084b565b60405161023191906111f3565b6101fc610850565b6103b2610887565b6040516102319190611513565b6102246109e0565b6101fc61020c366004610d0c565b6101fc6103e3366004610ec5565b61020c565b6101fc61020c366004610ec5565b6040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016104289061138e565b60405180910390fd5b565b50565b506107c790565b3373ffffffffffffffffffffffffffffffffffffffff167f7fcf532c15f0a6db0bd6d0e038bea71d30d808c7d98cb3bf7268a95bf5081b65826040516104839190611526565b60405180910390a250565b505060408051808201825260048082527f1234567800000000000000000000000000000000000000000000000000000000602080840191909152835180850185528281527f87654321000000000000000000000000000000000000000000000000000000008183015284518086019095529184527f616d657400000000000000000000000000000000000000000000000000000000908401529093909250565b600060606040518060400160405280601c81526020017f19457468657265756d205369676e6564204d6573736167653a0a33320000000081525090506000818760405160200161057f9291906111b0565b604051602081830303815290604052805190602001209050600181878787604051600081526020016040526040516105ba9493929190611271565b6020604051602081039080840390855afa1580156105dc573d6000803e3d6000fd5b50506040517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0015198975050505050505050565b6107c75b90565b604080518082018252601481527f5245564552545f574954485f434f4e5354414e54000000000000000000000000602082015290517f08c379a000000000000000000000000000000000000000000000000000000000815261042891906004016112d1565b6040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161042890611357565b6106146109e6565b6106146109fe565b604080518082018252601581527f524551554952455f574954485f434f4e5354414e540000000000000000000000602082015290517f08c379a000000000000000000000000000000000000000000000000000000000815261042891906004016112d1565b50929392505050565b600080546001019081905590565b610742610a1e565b50604080516080810182529182528051808201825260048082527f123456780000000000000000000000000000000000000000000000000000000060208381019190915280850192909252825180840184528181527f87654321000000000000000000000000000000000000000000000000000000008184015284840152825180840190935282527f616d65740000000000000000000000000000000000000000000000000000000090820152606082015290565b610431565b60010190565b600080546001019055565b600190565b60408051808201909152600581527f68656c6c6f0000000000000000000000000000000000000000000000000000006020820152600191565b606090565b7f61a6029a4c7ddee5824d171331eecbd015d26a271310a223718b837facb5b77160405161087d906112eb565b60405180910390a1565b61088f610a4c565b6040805160028082526060828101909352816020015b60608152602001906001900390816108a55790505090506040518060400160405280600581526020017f3078313233000000000000000000000000000000000000000000000000000000815250816000815181106108ff57fe5b60200260200101819052506040518060400160405280600581526020017f30783332310000000000000000000000000000000000000000000000000000008152508160018151811061094d57fe5b6020908102919091018101919091526040805160c0810182526005608082018181527f307831323300000000000000000000000000000000000000000000000000000060a0840152825281840152808201939093528051808201909152600381527f6162630000000000000000000000000000000000000000000000000000000000918101919091526060820152905090565b6104d290565b60405180602001604052806109f9610a7a565b905290565b6040518060400160405280610a11610a4c565b8152602001606081525090565b6040518060800160405280610a31610a8d565b81526020016060815260200160608152602001606081525090565b604051806080016040528060608152602001600063ffffffff16815260200160608152602001606081525090565b6040518060200160405280600081525090565b60405180606001604052806000815260200160608152602001606081525090565b600082601f830112610abe578081fd5b8135610ad1610acc8261156f565b611548565b8181529150602080830190840160005b83811015610b0e57610af98760208435890101610b73565b83526020928301929190910190600101610ae1565b5050505092915050565b600082601f830112610b28578081fd5b8135610b36610acc8261156f565b8181529150602080830190840160005b83811015610b0e57610b5e8760208435890101610bfa565b83526020928301929190910190600101610b46565b600082601f830112610b83578081fd5b813567ffffffffffffffff811115610b99578182fd5b610bca60207fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f84011601611548565b9150808252836020828501011115610be157600080fd5b8060208401602084013760009082016020015292915050565b600060808284031215610c0b578081fd5b610c156080611548565b9050813567ffffffffffffffff80821115610c2f57600080fd5b610c3b85838601610b73565b8352610c4a8560208601610ca1565b60208401526040840135915080821115610c6357600080fd5b610c6f85838601610aae565b60408401526060840135915080821115610c8857600080fd5b50610c9584828501610b73565b60608301525092915050565b803563ffffffff81168114610cb557600080fd5b92915050565b600080600080600060a08688031215610cd2578081fd5b8535610cdd816115bf565b945060208601359350604086013592506060860135610cfb816115bf565b949793965091946080013592915050565b60006020808385031215610d1e578182fd5b823567ffffffffffffffff811115610d34578283fd5b80840185601f820112610d45578384fd5b80359150610d55610acc8361156f565b82815283810190828501865b85811015610d8a57610d788a888435880101610b18565b84529286019290860190600101610d61565b509098975050505050505050565b60006020808385031215610daa578182fd5b823567ffffffffffffffff811115610dc0578283fd5b80840185601f820112610dd1578384fd5b80359150610de1610acc8361156f565b82815283810190828501865b85811015610d8a57610e048a888435880101610b73565b84529286019290860190600101610ded565b600060208284031215610e27578081fd5b813567ffffffffffffffff811115610e3d578182fd5b610e4984828501610b18565b949350505050565b60008060008060808587031215610e66578182fd5b84359350602085013560ff81168114610e7d578283fd5b93969395505050506040820135916060013590565b600060208284031215610ea3578081fd5b813567ffffffffffffffff811115610eb9578182fd5b610e4984828501610b73565b600060208284031215610ed6578081fd5b5035919050565b600060208284031215610eee578081fd5b813567ffffffffffffffff80821115610f05578283fd5b81840160608187031215610f17578384fd5b610f216060611548565b925080358352602081013582811115610f38578485fd5b610f4487828401610b73565b602085015250604081013582811115610f5b578485fd5b610f6787828401610b73565b6040850152509195945050505050565b600060208284031215610f88578081fd5b813567ffffffffffffffff80821115610f9f578283fd5b81840160408187031215610fb1578384fd5b610fbb6040611548565b9250803582811115610fcb578485fd5b610fd787828401610bfa565b845250602081013582811115610feb578485fd5b610ff787828401610b73565b6020850152509195945050505050565b600060208284031215611018578081fd5b813567ffffffffffffffff81111561102e578182fd5b610e4984828501610bfa565b60008060006060848603121561104e578081fd5b83359250602084013567ffffffffffffffff8082111561106c578283fd5b61107887838801610b73565b9350604086013591508082111561108d578283fd5b5061109a86828701610b73565b9150509250925092565b600081518084526110bc81602086016020860161158f565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169290920160200192915050565b600081516080845261110360808501826110a4565b6020915063ffffffff828501511682860152604084015185820360408701528181518084528484019150848582028501018584018794505b82851015611189577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08683030184526111758282516110a4565b60019590950194938701939150860161113b565b506060880151955088810360608a01526111a381876110a4565b9998505050505050505050565b600083516111c281846020880161158f565b9190910191825250602001919050565b73ffffffffffffffffffffffffffffffffffffffff91909116815260200190565b6000602080830181845280855180835260408601915060408482028701019250838701855b82811015611264577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc08886030184526112528583516110ee565b94509285019290850190600101611218565b5092979650505050505050565b93845260ff9290921660208401526040830152606082015260800190565b6000606082526112a260608301866110a4565b82810360208401526112b481866110a4565b83810360408501526112c681866110a4565b979650505050505050565b6000602082526112e460208301846110a4565b9392505050565b60408082526004908201527f123456780000000000000000000000000000000000000000000000000000000060608201526080602082018190526005908201527f6c6f72656d00000000000000000000000000000000000000000000000000000060a082015260c00190565b6020808252600d908201527f53494d504c455f52455645525400000000000000000000000000000000000000604082015260600190565b6020808252600e908201527f53494d504c455f52455155495245000000000000000000000000000000000000604082015260600190565b600060208252825160806020840152805160a08401526020810151606060c08501526113f56101008501826110a4565b604083015191507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff608582030160e086015261143081836110a4565b9250505060208401517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08085840301604086015261146e83836110a4565b604087015193508186820301606087015261148981856110a4565b9250506060860151925080858303016080860152506114a881836110a4565b95945050505050565b905151815260200190565b6000602082528251604060208401526114d860608401826110ee565b602085015191507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08482030160408501526114a881836110a4565b6000602082526112e460208301846110ee565b90815260200190565b600083825260406020830152610e4960408301846110a4565b60405181810167ffffffffffffffff8111828210171561156757600080fd5b604052919050565b600067ffffffffffffffff821115611585578081fd5b5060209081020190565b60005b838110156115aa578181015183820152602001611592565b838111156115b9576000848401525b50505050565b73ffffffffffffffffffffffffffffffffffffffff8116811461043357600080fdfea365627a7a72315820d4953afa8fe277a67a582a705ec911d7c404b5a84176ab0e36aa14da0e5986326c6578706572696d656e74616cf564736f6c63430005100040", - "opcodes": "PUSH1 0x80 PUSH1 0x40 MSTORE CALLVALUE DUP1 ISZERO PUSH2 0x10 JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST POP PUSH2 0x1624 DUP1 PUSH2 0x20 PUSH1 0x0 CODECOPY PUSH1 0x0 RETURN INVALID PUSH1 0x80 PUSH1 0x40 MSTORE CALLVALUE DUP1 ISZERO PUSH2 0x10 JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST POP PUSH1 0x4 CALLDATASIZE LT PUSH2 0x1EF JUMPI PUSH1 0x0 CALLDATALOAD PUSH1 0xE0 SHR DUP1 PUSH4 0x77EC31AE GT PUSH2 0x10F JUMPI DUP1 PUSH4 0xBDAB1688 GT PUSH2 0xA2 JUMPI DUP1 PUSH4 0xE796EE96 GT PUSH2 0x71 JUMPI DUP1 PUSH4 0xE796EE96 EQ PUSH2 0x3C7 JUMPI DUP1 PUSH4 0xEE8B86FB EQ PUSH2 0x3D5 JUMPI DUP1 PUSH4 0xF408FB31 EQ PUSH2 0x28F JUMPI DUP1 PUSH4 0xFA315F9D EQ PUSH2 0x3E8 JUMPI PUSH2 0x1EF JUMP JUMPDEST DUP1 PUSH4 0xBDAB1688 EQ PUSH2 0x38D JUMPI DUP1 PUSH4 0xCD3C0B97 EQ PUSH2 0x3A2 JUMPI DUP1 PUSH4 0xD6D7618C EQ PUSH2 0x3AA JUMPI DUP1 PUSH4 0xD88BE12F EQ PUSH2 0x3BF JUMPI PUSH2 0x1EF JUMP JUMPDEST DUP1 PUSH4 0x9A3B6185 GT PUSH2 0xDE JUMPI DUP1 PUSH4 0x9A3B6185 EQ PUSH2 0x359 JUMPI DUP1 PUSH4 0xA3C2F6B6 EQ PUSH2 0x361 JUMPI DUP1 PUSH4 0xAE2DAE17 EQ PUSH2 0x369 JUMPI DUP1 PUSH4 0xBB607362 EQ PUSH2 0x377 JUMPI PUSH2 0x1EF JUMP JUMPDEST DUP1 PUSH4 0x77EC31AE EQ PUSH2 0x310 JUMPI DUP1 PUSH4 0x7833BEC0 EQ PUSH2 0x31E JUMPI DUP1 PUSH4 0x7A791E6E EQ PUSH2 0x33E JUMPI DUP1 PUSH4 0x8EE52B4E EQ PUSH2 0x346 JUMPI PUSH2 0x1EF JUMP JUMPDEST DUP1 PUSH4 0x4582EAB2 GT PUSH2 0x187 JUMPI DUP1 PUSH4 0x5BA3C7C0 GT PUSH2 0x156 JUMPI DUP1 PUSH4 0x5BA3C7C0 EQ PUSH2 0x2DF JUMPI DUP1 PUSH4 0x63D69C88 EQ PUSH2 0x2E7 JUMPI DUP1 PUSH4 0x647341EB EQ PUSH2 0x2FA JUMPI DUP1 PUSH4 0x76F15D5B EQ PUSH2 0x308 JUMPI PUSH2 0x1EF JUMP JUMPDEST DUP1 PUSH4 0x4582EAB2 EQ PUSH2 0x2A5 JUMPI DUP1 PUSH4 0x45FDBDB7 EQ PUSH2 0x2AD JUMPI DUP1 PUSH4 0x586F84B2 EQ PUSH2 0x2B5 JUMPI DUP1 PUSH4 0x59C28ADD EQ PUSH2 0x2CA JUMPI PUSH2 0x1EF JUMP JUMPDEST DUP1 PUSH4 0x3687617D GT PUSH2 0x1C3 JUMPI DUP1 PUSH4 0x3687617D EQ PUSH2 0x24D JUMPI DUP1 PUSH4 0x36B32396 EQ PUSH2 0x26F JUMPI DUP1 PUSH4 0x3E9EF66A EQ PUSH2 0x28F JUMPI DUP1 PUSH4 0x4303A542 EQ PUSH2 0x29D JUMPI PUSH2 0x1EF JUMP JUMPDEST DUP1 PUSH3 0x9E437 EQ PUSH2 0x1F4 JUMPI DUP1 PUSH4 0x527C28F EQ PUSH2 0x1FE JUMPI DUP1 PUSH4 0x1310E444 EQ PUSH2 0x211 JUMPI DUP1 PUSH4 0x2E1A7D4D EQ PUSH2 0x23A JUMPI JUMPDEST PUSH1 0x0 DUP1 REVERT JUMPDEST PUSH2 0x1FC PUSH2 0x3F6 JUMP JUMPDEST STOP JUMPDEST PUSH2 0x1FC PUSH2 0x20C CALLDATASIZE PUSH1 0x4 PUSH2 0xD98 JUMP JUMPDEST PUSH2 0x433 JUMP JUMPDEST PUSH2 0x224 PUSH2 0x21F CALLDATASIZE PUSH1 0x4 PUSH2 0xEC5 JUMP JUMPDEST PUSH2 0x436 JUMP JUMPDEST PUSH1 0x40 MLOAD PUSH2 0x231 SWAP2 SWAP1 PUSH2 0x1526 JUMP JUMPDEST PUSH1 0x40 MLOAD DUP1 SWAP2 SUB SWAP1 RETURN JUMPDEST PUSH2 0x1FC PUSH2 0x248 CALLDATASIZE PUSH1 0x4 PUSH2 0xEC5 JUMP JUMPDEST PUSH2 0x43D JUMP JUMPDEST PUSH2 0x260 PUSH2 0x25B CALLDATASIZE PUSH1 0x4 PUSH2 0x103A JUMP JUMPDEST PUSH2 0x48E JUMP JUMPDEST PUSH1 0x40 MLOAD PUSH2 0x231 SWAP4 SWAP3 SWAP2 SWAP1 PUSH2 0x128F JUMP JUMPDEST PUSH2 0x282 PUSH2 0x27D CALLDATASIZE PUSH1 0x4 PUSH2 0xE51 JUMP JUMPDEST PUSH2 0x52E JUMP JUMPDEST PUSH1 0x40 MLOAD PUSH2 0x231 SWAP2 SWAP1 PUSH2 0x11D2 JUMP JUMPDEST PUSH2 0x1FC PUSH2 0x20C CALLDATASIZE PUSH1 0x4 PUSH2 0xE92 JUMP JUMPDEST PUSH2 0x224 PUSH2 0x610 JUMP JUMPDEST PUSH2 0x1FC PUSH2 0x617 JUMP JUMPDEST PUSH2 0x1FC PUSH2 0x67C JUMP JUMPDEST PUSH2 0x2BD PUSH2 0x6AE JUMP JUMPDEST PUSH1 0x40 MLOAD PUSH2 0x231 SWAP2 SWAP1 PUSH2 0x14B1 JUMP JUMPDEST PUSH2 0x2D2 PUSH2 0x6B6 JUMP JUMPDEST PUSH1 0x40 MLOAD PUSH2 0x231 SWAP2 SWAP1 PUSH2 0x14BC JUMP JUMPDEST PUSH2 0x1FC PUSH2 0x6BE JUMP JUMPDEST PUSH2 0x282 PUSH2 0x2F5 CALLDATASIZE PUSH1 0x4 PUSH2 0xCBB JUMP JUMPDEST PUSH2 0x723 JUMP JUMPDEST PUSH2 0x1FC PUSH2 0x20C CALLDATASIZE PUSH1 0x4 PUSH2 0x1007 JUMP JUMPDEST PUSH2 0x224 PUSH2 0x72C JUMP JUMPDEST PUSH2 0x1FC PUSH2 0x20C CALLDATASIZE PUSH1 0x4 PUSH2 0xE16 JUMP JUMPDEST PUSH2 0x331 PUSH2 0x32C CALLDATASIZE PUSH1 0x4 PUSH2 0xEDD JUMP JUMPDEST PUSH2 0x73A JUMP JUMPDEST PUSH1 0x40 MLOAD PUSH2 0x231 SWAP2 SWAP1 PUSH2 0x13C5 JUMP JUMPDEST PUSH2 0x1FC PUSH2 0x7F7 JUMP JUMPDEST PUSH2 0x224 PUSH2 0x354 CALLDATASIZE PUSH1 0x4 PUSH2 0xEC5 JUMP JUMPDEST PUSH2 0x7FC JUMP JUMPDEST PUSH2 0x1FC PUSH2 0x802 JUMP JUMPDEST PUSH2 0x224 PUSH2 0x80D JUMP JUMPDEST PUSH2 0x1FC PUSH2 0x20C CALLDATASIZE PUSH1 0x4 PUSH2 0xF77 JUMP JUMPDEST PUSH2 0x37F PUSH2 0x812 JUMP JUMPDEST PUSH1 0x40 MLOAD PUSH2 0x231 SWAP3 SWAP2 SWAP1 PUSH2 0x152F JUMP JUMPDEST PUSH2 0x395 PUSH2 0x84B JUMP JUMPDEST PUSH1 0x40 MLOAD PUSH2 0x231 SWAP2 SWAP1 PUSH2 0x11F3 JUMP JUMPDEST PUSH2 0x1FC PUSH2 0x850 JUMP JUMPDEST PUSH2 0x3B2 PUSH2 0x887 JUMP JUMPDEST PUSH1 0x40 MLOAD PUSH2 0x231 SWAP2 SWAP1 PUSH2 0x1513 JUMP JUMPDEST PUSH2 0x224 PUSH2 0x9E0 JUMP JUMPDEST PUSH2 0x1FC PUSH2 0x20C CALLDATASIZE PUSH1 0x4 PUSH2 0xD0C JUMP JUMPDEST PUSH2 0x1FC PUSH2 0x3E3 CALLDATASIZE PUSH1 0x4 PUSH2 0xEC5 JUMP JUMPDEST PUSH2 0x20C JUMP JUMPDEST PUSH2 0x1FC PUSH2 0x20C CALLDATASIZE PUSH1 0x4 PUSH2 0xEC5 JUMP JUMPDEST PUSH1 0x40 MLOAD PUSH32 0x8C379A000000000000000000000000000000000000000000000000000000000 DUP2 MSTORE PUSH1 0x4 ADD PUSH2 0x428 SWAP1 PUSH2 0x138E JUMP JUMPDEST PUSH1 0x40 MLOAD DUP1 SWAP2 SUB SWAP1 REVERT JUMPDEST JUMP JUMPDEST POP JUMP JUMPDEST POP PUSH2 0x7C7 SWAP1 JUMP JUMPDEST CALLER PUSH20 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF AND PUSH32 0x7FCF532C15F0A6DB0BD6D0E038BEA71D30D808C7D98CB3BF7268A95BF5081B65 DUP3 PUSH1 0x40 MLOAD PUSH2 0x483 SWAP2 SWAP1 PUSH2 0x1526 JUMP JUMPDEST PUSH1 0x40 MLOAD DUP1 SWAP2 SUB SWAP1 LOG2 POP JUMP JUMPDEST POP POP PUSH1 0x40 DUP1 MLOAD DUP1 DUP3 ADD DUP3 MSTORE PUSH1 0x4 DUP1 DUP3 MSTORE PUSH32 0x1234567800000000000000000000000000000000000000000000000000000000 PUSH1 0x20 DUP1 DUP5 ADD SWAP2 SWAP1 SWAP2 MSTORE DUP4 MLOAD DUP1 DUP6 ADD DUP6 MSTORE DUP3 DUP2 MSTORE PUSH32 0x8765432100000000000000000000000000000000000000000000000000000000 DUP2 DUP4 ADD MSTORE DUP5 MLOAD DUP1 DUP7 ADD SWAP1 SWAP6 MSTORE SWAP2 DUP5 MSTORE PUSH32 0x616D657400000000000000000000000000000000000000000000000000000000 SWAP1 DUP5 ADD MSTORE SWAP1 SWAP4 SWAP1 SWAP3 POP JUMP JUMPDEST PUSH1 0x0 PUSH1 0x60 PUSH1 0x40 MLOAD DUP1 PUSH1 0x40 ADD PUSH1 0x40 MSTORE DUP1 PUSH1 0x1C DUP2 MSTORE PUSH1 0x20 ADD PUSH32 0x19457468657265756D205369676E6564204D6573736167653A0A333200000000 DUP2 MSTORE POP SWAP1 POP PUSH1 0x0 DUP2 DUP8 PUSH1 0x40 MLOAD PUSH1 0x20 ADD PUSH2 0x57F SWAP3 SWAP2 SWAP1 PUSH2 0x11B0 JUMP JUMPDEST PUSH1 0x40 MLOAD PUSH1 0x20 DUP2 DUP4 SUB SUB DUP2 MSTORE SWAP1 PUSH1 0x40 MSTORE DUP1 MLOAD SWAP1 PUSH1 0x20 ADD KECCAK256 SWAP1 POP PUSH1 0x1 DUP2 DUP8 DUP8 DUP8 PUSH1 0x40 MLOAD PUSH1 0x0 DUP2 MSTORE PUSH1 0x20 ADD PUSH1 0x40 MSTORE PUSH1 0x40 MLOAD PUSH2 0x5BA SWAP5 SWAP4 SWAP3 SWAP2 SWAP1 PUSH2 0x1271 JUMP JUMPDEST PUSH1 0x20 PUSH1 0x40 MLOAD PUSH1 0x20 DUP2 SUB SWAP1 DUP1 DUP5 SUB SWAP1 DUP6 GAS STATICCALL ISZERO DUP1 ISZERO PUSH2 0x5DC JUMPI RETURNDATASIZE PUSH1 0x0 DUP1 RETURNDATACOPY RETURNDATASIZE PUSH1 0x0 REVERT JUMPDEST POP POP PUSH1 0x40 MLOAD PUSH32 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE0 ADD MLOAD SWAP9 SWAP8 POP POP POP POP POP POP POP POP JUMP JUMPDEST PUSH2 0x7C7 JUMPDEST SWAP1 JUMP JUMPDEST PUSH1 0x40 DUP1 MLOAD DUP1 DUP3 ADD DUP3 MSTORE PUSH1 0x14 DUP2 MSTORE PUSH32 0x5245564552545F574954485F434F4E5354414E54000000000000000000000000 PUSH1 0x20 DUP3 ADD MSTORE SWAP1 MLOAD PUSH32 0x8C379A000000000000000000000000000000000000000000000000000000000 DUP2 MSTORE PUSH2 0x428 SWAP2 SWAP1 PUSH1 0x4 ADD PUSH2 0x12D1 JUMP JUMPDEST PUSH1 0x40 MLOAD PUSH32 0x8C379A000000000000000000000000000000000000000000000000000000000 DUP2 MSTORE PUSH1 0x4 ADD PUSH2 0x428 SWAP1 PUSH2 0x1357 JUMP JUMPDEST PUSH2 0x614 PUSH2 0x9E6 JUMP JUMPDEST PUSH2 0x614 PUSH2 0x9FE JUMP JUMPDEST PUSH1 0x40 DUP1 MLOAD DUP1 DUP3 ADD DUP3 MSTORE PUSH1 0x15 DUP2 MSTORE PUSH32 0x524551554952455F574954485F434F4E5354414E540000000000000000000000 PUSH1 0x20 DUP3 ADD MSTORE SWAP1 MLOAD PUSH32 0x8C379A000000000000000000000000000000000000000000000000000000000 DUP2 MSTORE PUSH2 0x428 SWAP2 SWAP1 PUSH1 0x4 ADD PUSH2 0x12D1 JUMP JUMPDEST POP SWAP3 SWAP4 SWAP3 POP POP POP JUMP JUMPDEST PUSH1 0x0 DUP1 SLOAD PUSH1 0x1 ADD SWAP1 DUP2 SWAP1 SSTORE SWAP1 JUMP JUMPDEST PUSH2 0x742 PUSH2 0xA1E JUMP JUMPDEST POP PUSH1 0x40 DUP1 MLOAD PUSH1 0x80 DUP2 ADD DUP3 MSTORE SWAP2 DUP3 MSTORE DUP1 MLOAD DUP1 DUP3 ADD DUP3 MSTORE PUSH1 0x4 DUP1 DUP3 MSTORE PUSH32 0x1234567800000000000000000000000000000000000000000000000000000000 PUSH1 0x20 DUP4 DUP2 ADD SWAP2 SWAP1 SWAP2 MSTORE DUP1 DUP6 ADD SWAP3 SWAP1 SWAP3 MSTORE DUP3 MLOAD DUP1 DUP5 ADD DUP5 MSTORE DUP2 DUP2 MSTORE PUSH32 0x8765432100000000000000000000000000000000000000000000000000000000 DUP2 DUP5 ADD MSTORE DUP5 DUP5 ADD MSTORE DUP3 MLOAD DUP1 DUP5 ADD SWAP1 SWAP4 MSTORE DUP3 MSTORE PUSH32 0x616D657400000000000000000000000000000000000000000000000000000000 SWAP1 DUP3 ADD MSTORE PUSH1 0x60 DUP3 ADD MSTORE SWAP1 JUMP JUMPDEST PUSH2 0x431 JUMP JUMPDEST PUSH1 0x1 ADD SWAP1 JUMP JUMPDEST PUSH1 0x0 DUP1 SLOAD PUSH1 0x1 ADD SWAP1 SSTORE JUMP JUMPDEST PUSH1 0x1 SWAP1 JUMP JUMPDEST PUSH1 0x40 DUP1 MLOAD DUP1 DUP3 ADD SWAP1 SWAP2 MSTORE PUSH1 0x5 DUP2 MSTORE PUSH32 0x68656C6C6F000000000000000000000000000000000000000000000000000000 PUSH1 0x20 DUP3 ADD MSTORE PUSH1 0x1 SWAP2 JUMP JUMPDEST PUSH1 0x60 SWAP1 JUMP JUMPDEST PUSH32 0x61A6029A4C7DDEE5824D171331EECBD015D26A271310A223718B837FACB5B771 PUSH1 0x40 MLOAD PUSH2 0x87D SWAP1 PUSH2 0x12EB JUMP JUMPDEST PUSH1 0x40 MLOAD DUP1 SWAP2 SUB SWAP1 LOG1 JUMP JUMPDEST PUSH2 0x88F PUSH2 0xA4C JUMP JUMPDEST PUSH1 0x40 DUP1 MLOAD PUSH1 0x2 DUP1 DUP3 MSTORE PUSH1 0x60 DUP3 DUP2 ADD SWAP1 SWAP4 MSTORE DUP2 PUSH1 0x20 ADD JUMPDEST PUSH1 0x60 DUP2 MSTORE PUSH1 0x20 ADD SWAP1 PUSH1 0x1 SWAP1 SUB SWAP1 DUP2 PUSH2 0x8A5 JUMPI SWAP1 POP POP SWAP1 POP PUSH1 0x40 MLOAD DUP1 PUSH1 0x40 ADD PUSH1 0x40 MSTORE DUP1 PUSH1 0x5 DUP2 MSTORE PUSH1 0x20 ADD PUSH32 0x3078313233000000000000000000000000000000000000000000000000000000 DUP2 MSTORE POP DUP2 PUSH1 0x0 DUP2 MLOAD DUP2 LT PUSH2 0x8FF JUMPI INVALID JUMPDEST PUSH1 0x20 MUL PUSH1 0x20 ADD ADD DUP2 SWAP1 MSTORE POP PUSH1 0x40 MLOAD DUP1 PUSH1 0x40 ADD PUSH1 0x40 MSTORE DUP1 PUSH1 0x5 DUP2 MSTORE PUSH1 0x20 ADD PUSH32 0x3078333231000000000000000000000000000000000000000000000000000000 DUP2 MSTORE POP DUP2 PUSH1 0x1 DUP2 MLOAD DUP2 LT PUSH2 0x94D JUMPI INVALID JUMPDEST PUSH1 0x20 SWAP1 DUP2 MUL SWAP2 SWAP1 SWAP2 ADD DUP2 ADD SWAP2 SWAP1 SWAP2 MSTORE PUSH1 0x40 DUP1 MLOAD PUSH1 0xC0 DUP2 ADD DUP3 MSTORE PUSH1 0x5 PUSH1 0x80 DUP3 ADD DUP2 DUP2 MSTORE PUSH32 0x3078313233000000000000000000000000000000000000000000000000000000 PUSH1 0xA0 DUP5 ADD MSTORE DUP3 MSTORE DUP2 DUP5 ADD MSTORE DUP1 DUP3 ADD SWAP4 SWAP1 SWAP4 MSTORE DUP1 MLOAD DUP1 DUP3 ADD SWAP1 SWAP2 MSTORE PUSH1 0x3 DUP2 MSTORE PUSH32 0x6162630000000000000000000000000000000000000000000000000000000000 SWAP2 DUP2 ADD SWAP2 SWAP1 SWAP2 MSTORE PUSH1 0x60 DUP3 ADD MSTORE SWAP1 POP SWAP1 JUMP JUMPDEST PUSH2 0x4D2 SWAP1 JUMP JUMPDEST PUSH1 0x40 MLOAD DUP1 PUSH1 0x20 ADD PUSH1 0x40 MSTORE DUP1 PUSH2 0x9F9 PUSH2 0xA7A JUMP JUMPDEST SWAP1 MSTORE SWAP1 JUMP JUMPDEST PUSH1 0x40 MLOAD DUP1 PUSH1 0x40 ADD PUSH1 0x40 MSTORE DUP1 PUSH2 0xA11 PUSH2 0xA4C JUMP JUMPDEST DUP2 MSTORE PUSH1 0x20 ADD PUSH1 0x60 DUP2 MSTORE POP SWAP1 JUMP JUMPDEST PUSH1 0x40 MLOAD DUP1 PUSH1 0x80 ADD PUSH1 0x40 MSTORE DUP1 PUSH2 0xA31 PUSH2 0xA8D JUMP JUMPDEST DUP2 MSTORE PUSH1 0x20 ADD PUSH1 0x60 DUP2 MSTORE PUSH1 0x20 ADD PUSH1 0x60 DUP2 MSTORE PUSH1 0x20 ADD PUSH1 0x60 DUP2 MSTORE POP SWAP1 JUMP JUMPDEST PUSH1 0x40 MLOAD DUP1 PUSH1 0x80 ADD PUSH1 0x40 MSTORE DUP1 PUSH1 0x60 DUP2 MSTORE PUSH1 0x20 ADD PUSH1 0x0 PUSH4 0xFFFFFFFF AND DUP2 MSTORE PUSH1 0x20 ADD PUSH1 0x60 DUP2 MSTORE PUSH1 0x20 ADD PUSH1 0x60 DUP2 MSTORE POP SWAP1 JUMP JUMPDEST PUSH1 0x40 MLOAD DUP1 PUSH1 0x20 ADD PUSH1 0x40 MSTORE DUP1 PUSH1 0x0 DUP2 MSTORE POP SWAP1 JUMP JUMPDEST PUSH1 0x40 MLOAD DUP1 PUSH1 0x60 ADD PUSH1 0x40 MSTORE DUP1 PUSH1 0x0 DUP2 MSTORE PUSH1 0x20 ADD PUSH1 0x60 DUP2 MSTORE PUSH1 0x20 ADD PUSH1 0x60 DUP2 MSTORE POP SWAP1 JUMP JUMPDEST PUSH1 0x0 DUP3 PUSH1 0x1F DUP4 ADD SLT PUSH2 0xABE JUMPI DUP1 DUP2 REVERT JUMPDEST DUP2 CALLDATALOAD PUSH2 0xAD1 PUSH2 0xACC DUP3 PUSH2 0x156F JUMP JUMPDEST PUSH2 0x1548 JUMP JUMPDEST DUP2 DUP2 MSTORE SWAP2 POP PUSH1 0x20 DUP1 DUP4 ADD SWAP1 DUP5 ADD PUSH1 0x0 JUMPDEST DUP4 DUP2 LT ISZERO PUSH2 0xB0E JUMPI PUSH2 0xAF9 DUP8 PUSH1 0x20 DUP5 CALLDATALOAD DUP10 ADD ADD PUSH2 0xB73 JUMP JUMPDEST DUP4 MSTORE PUSH1 0x20 SWAP3 DUP4 ADD SWAP3 SWAP2 SWAP1 SWAP2 ADD SWAP1 PUSH1 0x1 ADD PUSH2 0xAE1 JUMP JUMPDEST POP POP POP POP SWAP3 SWAP2 POP POP JUMP JUMPDEST PUSH1 0x0 DUP3 PUSH1 0x1F DUP4 ADD SLT PUSH2 0xB28 JUMPI DUP1 DUP2 REVERT JUMPDEST DUP2 CALLDATALOAD PUSH2 0xB36 PUSH2 0xACC DUP3 PUSH2 0x156F JUMP JUMPDEST DUP2 DUP2 MSTORE SWAP2 POP PUSH1 0x20 DUP1 DUP4 ADD SWAP1 DUP5 ADD PUSH1 0x0 JUMPDEST DUP4 DUP2 LT ISZERO PUSH2 0xB0E JUMPI PUSH2 0xB5E DUP8 PUSH1 0x20 DUP5 CALLDATALOAD DUP10 ADD ADD PUSH2 0xBFA JUMP JUMPDEST DUP4 MSTORE PUSH1 0x20 SWAP3 DUP4 ADD SWAP3 SWAP2 SWAP1 SWAP2 ADD SWAP1 PUSH1 0x1 ADD PUSH2 0xB46 JUMP JUMPDEST PUSH1 0x0 DUP3 PUSH1 0x1F DUP4 ADD SLT PUSH2 0xB83 JUMPI DUP1 DUP2 REVERT JUMPDEST DUP2 CALLDATALOAD PUSH8 0xFFFFFFFFFFFFFFFF DUP2 GT ISZERO PUSH2 0xB99 JUMPI DUP2 DUP3 REVERT JUMPDEST PUSH2 0xBCA PUSH1 0x20 PUSH32 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE0 PUSH1 0x1F DUP5 ADD AND ADD PUSH2 0x1548 JUMP JUMPDEST SWAP2 POP DUP1 DUP3 MSTORE DUP4 PUSH1 0x20 DUP3 DUP6 ADD ADD GT ISZERO PUSH2 0xBE1 JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST DUP1 PUSH1 0x20 DUP5 ADD PUSH1 0x20 DUP5 ADD CALLDATACOPY PUSH1 0x0 SWAP1 DUP3 ADD PUSH1 0x20 ADD MSTORE SWAP3 SWAP2 POP POP JUMP JUMPDEST PUSH1 0x0 PUSH1 0x80 DUP3 DUP5 SUB SLT ISZERO PUSH2 0xC0B JUMPI DUP1 DUP2 REVERT JUMPDEST PUSH2 0xC15 PUSH1 0x80 PUSH2 0x1548 JUMP JUMPDEST SWAP1 POP DUP2 CALLDATALOAD PUSH8 0xFFFFFFFFFFFFFFFF DUP1 DUP3 GT ISZERO PUSH2 0xC2F JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST PUSH2 0xC3B DUP6 DUP4 DUP7 ADD PUSH2 0xB73 JUMP JUMPDEST DUP4 MSTORE PUSH2 0xC4A DUP6 PUSH1 0x20 DUP7 ADD PUSH2 0xCA1 JUMP JUMPDEST PUSH1 0x20 DUP5 ADD MSTORE PUSH1 0x40 DUP5 ADD CALLDATALOAD SWAP2 POP DUP1 DUP3 GT ISZERO PUSH2 0xC63 JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST PUSH2 0xC6F DUP6 DUP4 DUP7 ADD PUSH2 0xAAE JUMP JUMPDEST PUSH1 0x40 DUP5 ADD MSTORE PUSH1 0x60 DUP5 ADD CALLDATALOAD SWAP2 POP DUP1 DUP3 GT ISZERO PUSH2 0xC88 JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST POP PUSH2 0xC95 DUP5 DUP3 DUP6 ADD PUSH2 0xB73 JUMP JUMPDEST PUSH1 0x60 DUP4 ADD MSTORE POP SWAP3 SWAP2 POP POP JUMP JUMPDEST DUP1 CALLDATALOAD PUSH4 0xFFFFFFFF DUP2 AND DUP2 EQ PUSH2 0xCB5 JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST SWAP3 SWAP2 POP POP JUMP JUMPDEST PUSH1 0x0 DUP1 PUSH1 0x0 DUP1 PUSH1 0x0 PUSH1 0xA0 DUP7 DUP9 SUB SLT ISZERO PUSH2 0xCD2 JUMPI DUP1 DUP2 REVERT JUMPDEST DUP6 CALLDATALOAD PUSH2 0xCDD DUP2 PUSH2 0x15BF JUMP JUMPDEST SWAP5 POP PUSH1 0x20 DUP7 ADD CALLDATALOAD SWAP4 POP PUSH1 0x40 DUP7 ADD CALLDATALOAD SWAP3 POP PUSH1 0x60 DUP7 ADD CALLDATALOAD PUSH2 0xCFB DUP2 PUSH2 0x15BF JUMP JUMPDEST SWAP5 SWAP8 SWAP4 SWAP7 POP SWAP2 SWAP5 PUSH1 0x80 ADD CALLDATALOAD SWAP3 SWAP2 POP POP JUMP JUMPDEST PUSH1 0x0 PUSH1 0x20 DUP1 DUP4 DUP6 SUB SLT ISZERO PUSH2 0xD1E JUMPI DUP2 DUP3 REVERT JUMPDEST DUP3 CALLDATALOAD PUSH8 0xFFFFFFFFFFFFFFFF DUP2 GT ISZERO PUSH2 0xD34 JUMPI DUP3 DUP4 REVERT JUMPDEST DUP1 DUP5 ADD DUP6 PUSH1 0x1F DUP3 ADD SLT PUSH2 0xD45 JUMPI DUP4 DUP5 REVERT JUMPDEST DUP1 CALLDATALOAD SWAP2 POP PUSH2 0xD55 PUSH2 0xACC DUP4 PUSH2 0x156F JUMP JUMPDEST DUP3 DUP2 MSTORE DUP4 DUP2 ADD SWAP1 DUP3 DUP6 ADD DUP7 JUMPDEST DUP6 DUP2 LT ISZERO PUSH2 0xD8A JUMPI PUSH2 0xD78 DUP11 DUP9 DUP5 CALLDATALOAD DUP9 ADD ADD PUSH2 0xB18 JUMP JUMPDEST DUP5 MSTORE SWAP3 DUP7 ADD SWAP3 SWAP1 DUP7 ADD SWAP1 PUSH1 0x1 ADD PUSH2 0xD61 JUMP JUMPDEST POP SWAP1 SWAP9 SWAP8 POP POP POP POP POP POP POP POP JUMP JUMPDEST PUSH1 0x0 PUSH1 0x20 DUP1 DUP4 DUP6 SUB SLT ISZERO PUSH2 0xDAA JUMPI DUP2 DUP3 REVERT JUMPDEST DUP3 CALLDATALOAD PUSH8 0xFFFFFFFFFFFFFFFF DUP2 GT ISZERO PUSH2 0xDC0 JUMPI DUP3 DUP4 REVERT JUMPDEST DUP1 DUP5 ADD DUP6 PUSH1 0x1F DUP3 ADD SLT PUSH2 0xDD1 JUMPI DUP4 DUP5 REVERT JUMPDEST DUP1 CALLDATALOAD SWAP2 POP PUSH2 0xDE1 PUSH2 0xACC DUP4 PUSH2 0x156F JUMP JUMPDEST DUP3 DUP2 MSTORE DUP4 DUP2 ADD SWAP1 DUP3 DUP6 ADD DUP7 JUMPDEST DUP6 DUP2 LT ISZERO PUSH2 0xD8A JUMPI PUSH2 0xE04 DUP11 DUP9 DUP5 CALLDATALOAD DUP9 ADD ADD PUSH2 0xB73 JUMP JUMPDEST DUP5 MSTORE SWAP3 DUP7 ADD SWAP3 SWAP1 DUP7 ADD SWAP1 PUSH1 0x1 ADD PUSH2 0xDED JUMP JUMPDEST PUSH1 0x0 PUSH1 0x20 DUP3 DUP5 SUB SLT ISZERO PUSH2 0xE27 JUMPI DUP1 DUP2 REVERT JUMPDEST DUP2 CALLDATALOAD PUSH8 0xFFFFFFFFFFFFFFFF DUP2 GT ISZERO PUSH2 0xE3D JUMPI DUP2 DUP3 REVERT JUMPDEST PUSH2 0xE49 DUP5 DUP3 DUP6 ADD PUSH2 0xB18 JUMP JUMPDEST SWAP5 SWAP4 POP POP POP POP JUMP JUMPDEST PUSH1 0x0 DUP1 PUSH1 0x0 DUP1 PUSH1 0x80 DUP6 DUP8 SUB SLT ISZERO PUSH2 0xE66 JUMPI DUP2 DUP3 REVERT JUMPDEST DUP5 CALLDATALOAD SWAP4 POP PUSH1 0x20 DUP6 ADD CALLDATALOAD PUSH1 0xFF DUP2 AND DUP2 EQ PUSH2 0xE7D JUMPI DUP3 DUP4 REVERT JUMPDEST SWAP4 SWAP7 SWAP4 SWAP6 POP POP POP POP PUSH1 0x40 DUP3 ADD CALLDATALOAD SWAP2 PUSH1 0x60 ADD CALLDATALOAD SWAP1 JUMP JUMPDEST PUSH1 0x0 PUSH1 0x20 DUP3 DUP5 SUB SLT ISZERO PUSH2 0xEA3 JUMPI DUP1 DUP2 REVERT JUMPDEST DUP2 CALLDATALOAD PUSH8 0xFFFFFFFFFFFFFFFF DUP2 GT ISZERO PUSH2 0xEB9 JUMPI DUP2 DUP3 REVERT JUMPDEST PUSH2 0xE49 DUP5 DUP3 DUP6 ADD PUSH2 0xB73 JUMP JUMPDEST PUSH1 0x0 PUSH1 0x20 DUP3 DUP5 SUB SLT ISZERO PUSH2 0xED6 JUMPI DUP1 DUP2 REVERT JUMPDEST POP CALLDATALOAD SWAP2 SWAP1 POP JUMP JUMPDEST PUSH1 0x0 PUSH1 0x20 DUP3 DUP5 SUB SLT ISZERO PUSH2 0xEEE JUMPI DUP1 DUP2 REVERT JUMPDEST DUP2 CALLDATALOAD PUSH8 0xFFFFFFFFFFFFFFFF DUP1 DUP3 GT ISZERO PUSH2 0xF05 JUMPI DUP3 DUP4 REVERT JUMPDEST DUP2 DUP5 ADD PUSH1 0x60 DUP2 DUP8 SUB SLT ISZERO PUSH2 0xF17 JUMPI DUP4 DUP5 REVERT JUMPDEST PUSH2 0xF21 PUSH1 0x60 PUSH2 0x1548 JUMP JUMPDEST SWAP3 POP DUP1 CALLDATALOAD DUP4 MSTORE PUSH1 0x20 DUP2 ADD CALLDATALOAD DUP3 DUP2 GT ISZERO PUSH2 0xF38 JUMPI DUP5 DUP6 REVERT JUMPDEST PUSH2 0xF44 DUP8 DUP3 DUP5 ADD PUSH2 0xB73 JUMP JUMPDEST PUSH1 0x20 DUP6 ADD MSTORE POP PUSH1 0x40 DUP2 ADD CALLDATALOAD DUP3 DUP2 GT ISZERO PUSH2 0xF5B JUMPI DUP5 DUP6 REVERT JUMPDEST PUSH2 0xF67 DUP8 DUP3 DUP5 ADD PUSH2 0xB73 JUMP JUMPDEST PUSH1 0x40 DUP6 ADD MSTORE POP SWAP2 SWAP6 SWAP5 POP POP POP POP POP JUMP JUMPDEST PUSH1 0x0 PUSH1 0x20 DUP3 DUP5 SUB SLT ISZERO PUSH2 0xF88 JUMPI DUP1 DUP2 REVERT JUMPDEST DUP2 CALLDATALOAD PUSH8 0xFFFFFFFFFFFFFFFF DUP1 DUP3 GT ISZERO PUSH2 0xF9F JUMPI DUP3 DUP4 REVERT JUMPDEST DUP2 DUP5 ADD PUSH1 0x40 DUP2 DUP8 SUB SLT ISZERO PUSH2 0xFB1 JUMPI DUP4 DUP5 REVERT JUMPDEST PUSH2 0xFBB PUSH1 0x40 PUSH2 0x1548 JUMP JUMPDEST SWAP3 POP DUP1 CALLDATALOAD DUP3 DUP2 GT ISZERO PUSH2 0xFCB JUMPI DUP5 DUP6 REVERT JUMPDEST PUSH2 0xFD7 DUP8 DUP3 DUP5 ADD PUSH2 0xBFA JUMP JUMPDEST DUP5 MSTORE POP PUSH1 0x20 DUP2 ADD CALLDATALOAD DUP3 DUP2 GT ISZERO PUSH2 0xFEB JUMPI DUP5 DUP6 REVERT JUMPDEST PUSH2 0xFF7 DUP8 DUP3 DUP5 ADD PUSH2 0xB73 JUMP JUMPDEST PUSH1 0x20 DUP6 ADD MSTORE POP SWAP2 SWAP6 SWAP5 POP POP POP POP POP JUMP JUMPDEST PUSH1 0x0 PUSH1 0x20 DUP3 DUP5 SUB SLT ISZERO PUSH2 0x1018 JUMPI DUP1 DUP2 REVERT JUMPDEST DUP2 CALLDATALOAD PUSH8 0xFFFFFFFFFFFFFFFF DUP2 GT ISZERO PUSH2 0x102E JUMPI DUP2 DUP3 REVERT JUMPDEST PUSH2 0xE49 DUP5 DUP3 DUP6 ADD PUSH2 0xBFA JUMP JUMPDEST PUSH1 0x0 DUP1 PUSH1 0x0 PUSH1 0x60 DUP5 DUP7 SUB SLT ISZERO PUSH2 0x104E JUMPI DUP1 DUP2 REVERT JUMPDEST DUP4 CALLDATALOAD SWAP3 POP PUSH1 0x20 DUP5 ADD CALLDATALOAD PUSH8 0xFFFFFFFFFFFFFFFF DUP1 DUP3 GT ISZERO PUSH2 0x106C JUMPI DUP3 DUP4 REVERT JUMPDEST PUSH2 0x1078 DUP8 DUP4 DUP9 ADD PUSH2 0xB73 JUMP JUMPDEST SWAP4 POP PUSH1 0x40 DUP7 ADD CALLDATALOAD SWAP2 POP DUP1 DUP3 GT ISZERO PUSH2 0x108D JUMPI DUP3 DUP4 REVERT JUMPDEST POP PUSH2 0x109A DUP7 DUP3 DUP8 ADD PUSH2 0xB73 JUMP JUMPDEST SWAP2 POP POP SWAP3 POP SWAP3 POP SWAP3 JUMP JUMPDEST PUSH1 0x0 DUP2 MLOAD DUP1 DUP5 MSTORE PUSH2 0x10BC DUP2 PUSH1 0x20 DUP7 ADD PUSH1 0x20 DUP7 ADD PUSH2 0x158F JUMP JUMPDEST PUSH1 0x1F ADD PUSH32 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE0 AND SWAP3 SWAP1 SWAP3 ADD PUSH1 0x20 ADD SWAP3 SWAP2 POP POP JUMP JUMPDEST PUSH1 0x0 DUP2 MLOAD PUSH1 0x80 DUP5 MSTORE PUSH2 0x1103 PUSH1 0x80 DUP6 ADD DUP3 PUSH2 0x10A4 JUMP JUMPDEST PUSH1 0x20 SWAP2 POP PUSH4 0xFFFFFFFF DUP3 DUP6 ADD MLOAD AND DUP3 DUP7 ADD MSTORE PUSH1 0x40 DUP5 ADD MLOAD DUP6 DUP3 SUB PUSH1 0x40 DUP8 ADD MSTORE DUP2 DUP2 MLOAD DUP1 DUP5 MSTORE DUP5 DUP5 ADD SWAP2 POP DUP5 DUP6 DUP3 MUL DUP6 ADD ADD DUP6 DUP5 ADD DUP8 SWAP5 POP JUMPDEST DUP3 DUP6 LT ISZERO PUSH2 0x1189 JUMPI PUSH32 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE0 DUP7 DUP4 SUB ADD DUP5 MSTORE PUSH2 0x1175 DUP3 DUP3 MLOAD PUSH2 0x10A4 JUMP JUMPDEST PUSH1 0x1 SWAP6 SWAP1 SWAP6 ADD SWAP5 SWAP4 DUP8 ADD SWAP4 SWAP2 POP DUP7 ADD PUSH2 0x113B JUMP JUMPDEST POP PUSH1 0x60 DUP9 ADD MLOAD SWAP6 POP DUP9 DUP2 SUB PUSH1 0x60 DUP11 ADD MSTORE PUSH2 0x11A3 DUP2 DUP8 PUSH2 0x10A4 JUMP JUMPDEST SWAP10 SWAP9 POP POP POP POP POP POP POP POP POP JUMP JUMPDEST PUSH1 0x0 DUP4 MLOAD PUSH2 0x11C2 DUP2 DUP5 PUSH1 0x20 DUP9 ADD PUSH2 0x158F JUMP JUMPDEST SWAP2 SWAP1 SWAP2 ADD SWAP2 DUP3 MSTORE POP PUSH1 0x20 ADD SWAP2 SWAP1 POP JUMP JUMPDEST PUSH20 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF SWAP2 SWAP1 SWAP2 AND DUP2 MSTORE PUSH1 0x20 ADD SWAP1 JUMP JUMPDEST PUSH1 0x0 PUSH1 0x20 DUP1 DUP4 ADD DUP2 DUP5 MSTORE DUP1 DUP6 MLOAD DUP1 DUP4 MSTORE PUSH1 0x40 DUP7 ADD SWAP2 POP PUSH1 0x40 DUP5 DUP3 MUL DUP8 ADD ADD SWAP3 POP DUP4 DUP8 ADD DUP6 JUMPDEST DUP3 DUP2 LT ISZERO PUSH2 0x1264 JUMPI PUSH32 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC0 DUP9 DUP7 SUB ADD DUP5 MSTORE PUSH2 0x1252 DUP6 DUP4 MLOAD PUSH2 0x10EE JUMP JUMPDEST SWAP5 POP SWAP3 DUP6 ADD SWAP3 SWAP1 DUP6 ADD SWAP1 PUSH1 0x1 ADD PUSH2 0x1218 JUMP JUMPDEST POP SWAP3 SWAP8 SWAP7 POP POP POP POP POP POP POP JUMP JUMPDEST SWAP4 DUP5 MSTORE PUSH1 0xFF SWAP3 SWAP1 SWAP3 AND PUSH1 0x20 DUP5 ADD MSTORE PUSH1 0x40 DUP4 ADD MSTORE PUSH1 0x60 DUP3 ADD MSTORE PUSH1 0x80 ADD SWAP1 JUMP JUMPDEST PUSH1 0x0 PUSH1 0x60 DUP3 MSTORE PUSH2 0x12A2 PUSH1 0x60 DUP4 ADD DUP7 PUSH2 0x10A4 JUMP JUMPDEST DUP3 DUP2 SUB PUSH1 0x20 DUP5 ADD MSTORE PUSH2 0x12B4 DUP2 DUP7 PUSH2 0x10A4 JUMP JUMPDEST DUP4 DUP2 SUB PUSH1 0x40 DUP6 ADD MSTORE PUSH2 0x12C6 DUP2 DUP7 PUSH2 0x10A4 JUMP JUMPDEST SWAP8 SWAP7 POP POP POP POP POP POP POP JUMP JUMPDEST PUSH1 0x0 PUSH1 0x20 DUP3 MSTORE PUSH2 0x12E4 PUSH1 0x20 DUP4 ADD DUP5 PUSH2 0x10A4 JUMP JUMPDEST SWAP4 SWAP3 POP POP POP JUMP JUMPDEST PUSH1 0x40 DUP1 DUP3 MSTORE PUSH1 0x4 SWAP1 DUP3 ADD MSTORE PUSH32 0x1234567800000000000000000000000000000000000000000000000000000000 PUSH1 0x60 DUP3 ADD MSTORE PUSH1 0x80 PUSH1 0x20 DUP3 ADD DUP2 SWAP1 MSTORE PUSH1 0x5 SWAP1 DUP3 ADD MSTORE PUSH32 0x6C6F72656D000000000000000000000000000000000000000000000000000000 PUSH1 0xA0 DUP3 ADD MSTORE PUSH1 0xC0 ADD SWAP1 JUMP JUMPDEST PUSH1 0x20 DUP1 DUP3 MSTORE PUSH1 0xD SWAP1 DUP3 ADD MSTORE PUSH32 0x53494D504C455F52455645525400000000000000000000000000000000000000 PUSH1 0x40 DUP3 ADD MSTORE PUSH1 0x60 ADD SWAP1 JUMP JUMPDEST PUSH1 0x20 DUP1 DUP3 MSTORE PUSH1 0xE SWAP1 DUP3 ADD MSTORE PUSH32 0x53494D504C455F52455155495245000000000000000000000000000000000000 PUSH1 0x40 DUP3 ADD MSTORE PUSH1 0x60 ADD SWAP1 JUMP JUMPDEST PUSH1 0x0 PUSH1 0x20 DUP3 MSTORE DUP3 MLOAD PUSH1 0x80 PUSH1 0x20 DUP5 ADD MSTORE DUP1 MLOAD PUSH1 0xA0 DUP5 ADD MSTORE PUSH1 0x20 DUP2 ADD MLOAD PUSH1 0x60 PUSH1 0xC0 DUP6 ADD MSTORE PUSH2 0x13F5 PUSH2 0x100 DUP6 ADD DUP3 PUSH2 0x10A4 JUMP JUMPDEST PUSH1 0x40 DUP4 ADD MLOAD SWAP2 POP PUSH32 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF60 DUP6 DUP3 SUB ADD PUSH1 0xE0 DUP7 ADD MSTORE PUSH2 0x1430 DUP2 DUP4 PUSH2 0x10A4 JUMP JUMPDEST SWAP3 POP POP POP PUSH1 0x20 DUP5 ADD MLOAD PUSH32 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE0 DUP1 DUP6 DUP5 SUB ADD PUSH1 0x40 DUP7 ADD MSTORE PUSH2 0x146E DUP4 DUP4 PUSH2 0x10A4 JUMP JUMPDEST PUSH1 0x40 DUP8 ADD MLOAD SWAP4 POP DUP2 DUP7 DUP3 SUB ADD PUSH1 0x60 DUP8 ADD MSTORE PUSH2 0x1489 DUP2 DUP6 PUSH2 0x10A4 JUMP JUMPDEST SWAP3 POP POP PUSH1 0x60 DUP7 ADD MLOAD SWAP3 POP DUP1 DUP6 DUP4 SUB ADD PUSH1 0x80 DUP7 ADD MSTORE POP PUSH2 0x14A8 DUP2 DUP4 PUSH2 0x10A4 JUMP JUMPDEST SWAP6 SWAP5 POP POP POP POP POP JUMP JUMPDEST SWAP1 MLOAD MLOAD DUP2 MSTORE PUSH1 0x20 ADD SWAP1 JUMP JUMPDEST PUSH1 0x0 PUSH1 0x20 DUP3 MSTORE DUP3 MLOAD PUSH1 0x40 PUSH1 0x20 DUP5 ADD MSTORE PUSH2 0x14D8 PUSH1 0x60 DUP5 ADD DUP3 PUSH2 0x10EE JUMP JUMPDEST PUSH1 0x20 DUP6 ADD MLOAD SWAP2 POP PUSH32 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE0 DUP5 DUP3 SUB ADD PUSH1 0x40 DUP6 ADD MSTORE PUSH2 0x14A8 DUP2 DUP4 PUSH2 0x10A4 JUMP JUMPDEST PUSH1 0x0 PUSH1 0x20 DUP3 MSTORE PUSH2 0x12E4 PUSH1 0x20 DUP4 ADD DUP5 PUSH2 0x10EE JUMP JUMPDEST SWAP1 DUP2 MSTORE PUSH1 0x20 ADD SWAP1 JUMP JUMPDEST PUSH1 0x0 DUP4 DUP3 MSTORE PUSH1 0x40 PUSH1 0x20 DUP4 ADD MSTORE PUSH2 0xE49 PUSH1 0x40 DUP4 ADD DUP5 PUSH2 0x10A4 JUMP JUMPDEST PUSH1 0x40 MLOAD DUP2 DUP2 ADD PUSH8 0xFFFFFFFFFFFFFFFF DUP2 GT DUP3 DUP3 LT OR ISZERO PUSH2 0x1567 JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST PUSH1 0x40 MSTORE SWAP2 SWAP1 POP JUMP JUMPDEST PUSH1 0x0 PUSH8 0xFFFFFFFFFFFFFFFF DUP3 GT ISZERO PUSH2 0x1585 JUMPI DUP1 DUP2 REVERT JUMPDEST POP PUSH1 0x20 SWAP1 DUP2 MUL ADD SWAP1 JUMP JUMPDEST PUSH1 0x0 JUMPDEST DUP4 DUP2 LT ISZERO PUSH2 0x15AA JUMPI DUP2 DUP2 ADD MLOAD DUP4 DUP3 ADD MSTORE PUSH1 0x20 ADD PUSH2 0x1592 JUMP JUMPDEST DUP4 DUP2 GT ISZERO PUSH2 0x15B9 JUMPI PUSH1 0x0 DUP5 DUP5 ADD MSTORE JUMPDEST POP POP POP POP JUMP JUMPDEST PUSH20 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF DUP2 AND DUP2 EQ PUSH2 0x433 JUMPI PUSH1 0x0 DUP1 REVERT INVALID LOG3 PUSH6 0x627A7A723158 KECCAK256 0xD4 SWAP6 GASPRICE STATICCALL DUP16 0xE2 PUSH24 0xA67A582A705EC911D7C404B5A84176AB0E36AA14DA0E5986 ORIGIN PUSH13 0x6578706572696D656E74616CF5 PUSH5 0x736F6C6343 STOP SDIV LT STOP BLOCKHASH ", - "sourceMap": "641:6913:0:-;;;;8:9:-1;5:2;;;30:1;27;20:12;5:2;641:6913:0;;;;;;;" - }, - "deployedBytecode": { - "linkReferences": {}, - "object": "0x608060405234801561001057600080fd5b50600436106101ef5760003560e01c806377ec31ae1161010f578063bdab1688116100a2578063e796ee9611610071578063e796ee96146103c7578063ee8b86fb146103d5578063f408fb311461028f578063fa315f9d146103e8576101ef565b8063bdab16881461038d578063cd3c0b97146103a2578063d6d7618c146103aa578063d88be12f146103bf576101ef565b80639a3b6185116100de5780639a3b618514610359578063a3c2f6b614610361578063ae2dae1714610369578063bb60736214610377576101ef565b806377ec31ae146103105780637833bec01461031e5780637a791e6e1461033e5780638ee52b4e14610346576101ef565b80634582eab2116101875780635ba3c7c0116101565780635ba3c7c0146102df57806363d69c88146102e7578063647341eb146102fa57806376f15d5b14610308576101ef565b80634582eab2146102a557806345fdbdb7146102ad578063586f84b2146102b557806359c28add146102ca576101ef565b80633687617d116101c35780633687617d1461024d57806336b323961461026f5780633e9ef66a1461028f5780634303a5421461029d576101ef565b806209e437146101f45780630527c28f146101fe5780631310e444146102115780632e1a7d4d1461023a575b600080fd5b6101fc6103f6565b005b6101fc61020c366004610d98565b610433565b61022461021f366004610ec5565b610436565b6040516102319190611526565b60405180910390f35b6101fc610248366004610ec5565b61043d565b61026061025b36600461103a565b61048e565b6040516102319392919061128f565b61028261027d366004610e51565b61052e565b60405161023191906111d2565b6101fc61020c366004610e92565b610224610610565b6101fc610617565b6101fc61067c565b6102bd6106ae565b60405161023191906114b1565b6102d26106b6565b60405161023191906114bc565b6101fc6106be565b6102826102f5366004610cbb565b610723565b6101fc61020c366004611007565b61022461072c565b6101fc61020c366004610e16565b61033161032c366004610edd565b61073a565b60405161023191906113c5565b6101fc6107f7565b610224610354366004610ec5565b6107fc565b6101fc610802565b61022461080d565b6101fc61020c366004610f77565b61037f610812565b60405161023192919061152f565b61039561084b565b60405161023191906111f3565b6101fc610850565b6103b2610887565b6040516102319190611513565b6102246109e0565b6101fc61020c366004610d0c565b6101fc6103e3366004610ec5565b61020c565b6101fc61020c366004610ec5565b6040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016104289061138e565b60405180910390fd5b565b50565b506107c790565b3373ffffffffffffffffffffffffffffffffffffffff167f7fcf532c15f0a6db0bd6d0e038bea71d30d808c7d98cb3bf7268a95bf5081b65826040516104839190611526565b60405180910390a250565b505060408051808201825260048082527f1234567800000000000000000000000000000000000000000000000000000000602080840191909152835180850185528281527f87654321000000000000000000000000000000000000000000000000000000008183015284518086019095529184527f616d657400000000000000000000000000000000000000000000000000000000908401529093909250565b600060606040518060400160405280601c81526020017f19457468657265756d205369676e6564204d6573736167653a0a33320000000081525090506000818760405160200161057f9291906111b0565b604051602081830303815290604052805190602001209050600181878787604051600081526020016040526040516105ba9493929190611271565b6020604051602081039080840390855afa1580156105dc573d6000803e3d6000fd5b50506040517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0015198975050505050505050565b6107c75b90565b604080518082018252601481527f5245564552545f574954485f434f4e5354414e54000000000000000000000000602082015290517f08c379a000000000000000000000000000000000000000000000000000000000815261042891906004016112d1565b6040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161042890611357565b6106146109e6565b6106146109fe565b604080518082018252601581527f524551554952455f574954485f434f4e5354414e540000000000000000000000602082015290517f08c379a000000000000000000000000000000000000000000000000000000000815261042891906004016112d1565b50929392505050565b600080546001019081905590565b610742610a1e565b50604080516080810182529182528051808201825260048082527f123456780000000000000000000000000000000000000000000000000000000060208381019190915280850192909252825180840184528181527f87654321000000000000000000000000000000000000000000000000000000008184015284840152825180840190935282527f616d65740000000000000000000000000000000000000000000000000000000090820152606082015290565b610431565b60010190565b600080546001019055565b600190565b60408051808201909152600581527f68656c6c6f0000000000000000000000000000000000000000000000000000006020820152600191565b606090565b7f61a6029a4c7ddee5824d171331eecbd015d26a271310a223718b837facb5b77160405161087d906112eb565b60405180910390a1565b61088f610a4c565b6040805160028082526060828101909352816020015b60608152602001906001900390816108a55790505090506040518060400160405280600581526020017f3078313233000000000000000000000000000000000000000000000000000000815250816000815181106108ff57fe5b60200260200101819052506040518060400160405280600581526020017f30783332310000000000000000000000000000000000000000000000000000008152508160018151811061094d57fe5b6020908102919091018101919091526040805160c0810182526005608082018181527f307831323300000000000000000000000000000000000000000000000000000060a0840152825281840152808201939093528051808201909152600381527f6162630000000000000000000000000000000000000000000000000000000000918101919091526060820152905090565b6104d290565b60405180602001604052806109f9610a7a565b905290565b6040518060400160405280610a11610a4c565b8152602001606081525090565b6040518060800160405280610a31610a8d565b81526020016060815260200160608152602001606081525090565b604051806080016040528060608152602001600063ffffffff16815260200160608152602001606081525090565b6040518060200160405280600081525090565b60405180606001604052806000815260200160608152602001606081525090565b600082601f830112610abe578081fd5b8135610ad1610acc8261156f565b611548565b8181529150602080830190840160005b83811015610b0e57610af98760208435890101610b73565b83526020928301929190910190600101610ae1565b5050505092915050565b600082601f830112610b28578081fd5b8135610b36610acc8261156f565b8181529150602080830190840160005b83811015610b0e57610b5e8760208435890101610bfa565b83526020928301929190910190600101610b46565b600082601f830112610b83578081fd5b813567ffffffffffffffff811115610b99578182fd5b610bca60207fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f84011601611548565b9150808252836020828501011115610be157600080fd5b8060208401602084013760009082016020015292915050565b600060808284031215610c0b578081fd5b610c156080611548565b9050813567ffffffffffffffff80821115610c2f57600080fd5b610c3b85838601610b73565b8352610c4a8560208601610ca1565b60208401526040840135915080821115610c6357600080fd5b610c6f85838601610aae565b60408401526060840135915080821115610c8857600080fd5b50610c9584828501610b73565b60608301525092915050565b803563ffffffff81168114610cb557600080fd5b92915050565b600080600080600060a08688031215610cd2578081fd5b8535610cdd816115bf565b945060208601359350604086013592506060860135610cfb816115bf565b949793965091946080013592915050565b60006020808385031215610d1e578182fd5b823567ffffffffffffffff811115610d34578283fd5b80840185601f820112610d45578384fd5b80359150610d55610acc8361156f565b82815283810190828501865b85811015610d8a57610d788a888435880101610b18565b84529286019290860190600101610d61565b509098975050505050505050565b60006020808385031215610daa578182fd5b823567ffffffffffffffff811115610dc0578283fd5b80840185601f820112610dd1578384fd5b80359150610de1610acc8361156f565b82815283810190828501865b85811015610d8a57610e048a888435880101610b73565b84529286019290860190600101610ded565b600060208284031215610e27578081fd5b813567ffffffffffffffff811115610e3d578182fd5b610e4984828501610b18565b949350505050565b60008060008060808587031215610e66578182fd5b84359350602085013560ff81168114610e7d578283fd5b93969395505050506040820135916060013590565b600060208284031215610ea3578081fd5b813567ffffffffffffffff811115610eb9578182fd5b610e4984828501610b73565b600060208284031215610ed6578081fd5b5035919050565b600060208284031215610eee578081fd5b813567ffffffffffffffff80821115610f05578283fd5b81840160608187031215610f17578384fd5b610f216060611548565b925080358352602081013582811115610f38578485fd5b610f4487828401610b73565b602085015250604081013582811115610f5b578485fd5b610f6787828401610b73565b6040850152509195945050505050565b600060208284031215610f88578081fd5b813567ffffffffffffffff80821115610f9f578283fd5b81840160408187031215610fb1578384fd5b610fbb6040611548565b9250803582811115610fcb578485fd5b610fd787828401610bfa565b845250602081013582811115610feb578485fd5b610ff787828401610b73565b6020850152509195945050505050565b600060208284031215611018578081fd5b813567ffffffffffffffff81111561102e578182fd5b610e4984828501610bfa565b60008060006060848603121561104e578081fd5b83359250602084013567ffffffffffffffff8082111561106c578283fd5b61107887838801610b73565b9350604086013591508082111561108d578283fd5b5061109a86828701610b73565b9150509250925092565b600081518084526110bc81602086016020860161158f565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169290920160200192915050565b600081516080845261110360808501826110a4565b6020915063ffffffff828501511682860152604084015185820360408701528181518084528484019150848582028501018584018794505b82851015611189577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08683030184526111758282516110a4565b60019590950194938701939150860161113b565b506060880151955088810360608a01526111a381876110a4565b9998505050505050505050565b600083516111c281846020880161158f565b9190910191825250602001919050565b73ffffffffffffffffffffffffffffffffffffffff91909116815260200190565b6000602080830181845280855180835260408601915060408482028701019250838701855b82811015611264577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc08886030184526112528583516110ee565b94509285019290850190600101611218565b5092979650505050505050565b93845260ff9290921660208401526040830152606082015260800190565b6000606082526112a260608301866110a4565b82810360208401526112b481866110a4565b83810360408501526112c681866110a4565b979650505050505050565b6000602082526112e460208301846110a4565b9392505050565b60408082526004908201527f123456780000000000000000000000000000000000000000000000000000000060608201526080602082018190526005908201527f6c6f72656d00000000000000000000000000000000000000000000000000000060a082015260c00190565b6020808252600d908201527f53494d504c455f52455645525400000000000000000000000000000000000000604082015260600190565b6020808252600e908201527f53494d504c455f52455155495245000000000000000000000000000000000000604082015260600190565b600060208252825160806020840152805160a08401526020810151606060c08501526113f56101008501826110a4565b604083015191507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff608582030160e086015261143081836110a4565b9250505060208401517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08085840301604086015261146e83836110a4565b604087015193508186820301606087015261148981856110a4565b9250506060860151925080858303016080860152506114a881836110a4565b95945050505050565b905151815260200190565b6000602082528251604060208401526114d860608401826110ee565b602085015191507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08482030160408501526114a881836110a4565b6000602082526112e460208301846110ee565b90815260200190565b600083825260406020830152610e4960408301846110a4565b60405181810167ffffffffffffffff8111828210171561156757600080fd5b604052919050565b600067ffffffffffffffff821115611585578081fd5b5060209081020190565b60005b838110156115aa578181015183820152602001611592565b838111156115b9576000848401525b50505050565b73ffffffffffffffffffffffffffffffffffffffff8116811461043357600080fdfea365627a7a72315820d4953afa8fe277a67a582a705ec911d7c404b5a84176ab0e36aa14da0e5986326c6578706572696d656e74616cf564736f6c63430005100040", - "opcodes": "PUSH1 0x80 PUSH1 0x40 MSTORE CALLVALUE DUP1 ISZERO PUSH2 0x10 JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST POP PUSH1 0x4 CALLDATASIZE LT PUSH2 0x1EF JUMPI PUSH1 0x0 CALLDATALOAD PUSH1 0xE0 SHR DUP1 PUSH4 0x77EC31AE GT PUSH2 0x10F JUMPI DUP1 PUSH4 0xBDAB1688 GT PUSH2 0xA2 JUMPI DUP1 PUSH4 0xE796EE96 GT PUSH2 0x71 JUMPI DUP1 PUSH4 0xE796EE96 EQ PUSH2 0x3C7 JUMPI DUP1 PUSH4 0xEE8B86FB EQ PUSH2 0x3D5 JUMPI DUP1 PUSH4 0xF408FB31 EQ PUSH2 0x28F JUMPI DUP1 PUSH4 0xFA315F9D EQ PUSH2 0x3E8 JUMPI PUSH2 0x1EF JUMP JUMPDEST DUP1 PUSH4 0xBDAB1688 EQ PUSH2 0x38D JUMPI DUP1 PUSH4 0xCD3C0B97 EQ PUSH2 0x3A2 JUMPI DUP1 PUSH4 0xD6D7618C EQ PUSH2 0x3AA JUMPI DUP1 PUSH4 0xD88BE12F EQ PUSH2 0x3BF JUMPI PUSH2 0x1EF JUMP JUMPDEST DUP1 PUSH4 0x9A3B6185 GT PUSH2 0xDE JUMPI DUP1 PUSH4 0x9A3B6185 EQ PUSH2 0x359 JUMPI DUP1 PUSH4 0xA3C2F6B6 EQ PUSH2 0x361 JUMPI DUP1 PUSH4 0xAE2DAE17 EQ PUSH2 0x369 JUMPI DUP1 PUSH4 0xBB607362 EQ PUSH2 0x377 JUMPI PUSH2 0x1EF JUMP JUMPDEST DUP1 PUSH4 0x77EC31AE EQ PUSH2 0x310 JUMPI DUP1 PUSH4 0x7833BEC0 EQ PUSH2 0x31E JUMPI DUP1 PUSH4 0x7A791E6E EQ PUSH2 0x33E JUMPI DUP1 PUSH4 0x8EE52B4E EQ PUSH2 0x346 JUMPI PUSH2 0x1EF JUMP JUMPDEST DUP1 PUSH4 0x4582EAB2 GT PUSH2 0x187 JUMPI DUP1 PUSH4 0x5BA3C7C0 GT PUSH2 0x156 JUMPI DUP1 PUSH4 0x5BA3C7C0 EQ PUSH2 0x2DF JUMPI DUP1 PUSH4 0x63D69C88 EQ PUSH2 0x2E7 JUMPI DUP1 PUSH4 0x647341EB EQ PUSH2 0x2FA JUMPI DUP1 PUSH4 0x76F15D5B EQ PUSH2 0x308 JUMPI PUSH2 0x1EF JUMP JUMPDEST DUP1 PUSH4 0x4582EAB2 EQ PUSH2 0x2A5 JUMPI DUP1 PUSH4 0x45FDBDB7 EQ PUSH2 0x2AD JUMPI DUP1 PUSH4 0x586F84B2 EQ PUSH2 0x2B5 JUMPI DUP1 PUSH4 0x59C28ADD EQ PUSH2 0x2CA JUMPI PUSH2 0x1EF JUMP JUMPDEST DUP1 PUSH4 0x3687617D GT PUSH2 0x1C3 JUMPI DUP1 PUSH4 0x3687617D EQ PUSH2 0x24D JUMPI DUP1 PUSH4 0x36B32396 EQ PUSH2 0x26F JUMPI DUP1 PUSH4 0x3E9EF66A EQ PUSH2 0x28F JUMPI DUP1 PUSH4 0x4303A542 EQ PUSH2 0x29D JUMPI PUSH2 0x1EF JUMP JUMPDEST DUP1 PUSH3 0x9E437 EQ PUSH2 0x1F4 JUMPI DUP1 PUSH4 0x527C28F EQ PUSH2 0x1FE JUMPI DUP1 PUSH4 0x1310E444 EQ PUSH2 0x211 JUMPI DUP1 PUSH4 0x2E1A7D4D EQ PUSH2 0x23A JUMPI JUMPDEST PUSH1 0x0 DUP1 REVERT JUMPDEST PUSH2 0x1FC PUSH2 0x3F6 JUMP JUMPDEST STOP JUMPDEST PUSH2 0x1FC PUSH2 0x20C CALLDATASIZE PUSH1 0x4 PUSH2 0xD98 JUMP JUMPDEST PUSH2 0x433 JUMP JUMPDEST PUSH2 0x224 PUSH2 0x21F CALLDATASIZE PUSH1 0x4 PUSH2 0xEC5 JUMP JUMPDEST PUSH2 0x436 JUMP JUMPDEST PUSH1 0x40 MLOAD PUSH2 0x231 SWAP2 SWAP1 PUSH2 0x1526 JUMP JUMPDEST PUSH1 0x40 MLOAD DUP1 SWAP2 SUB SWAP1 RETURN JUMPDEST PUSH2 0x1FC PUSH2 0x248 CALLDATASIZE PUSH1 0x4 PUSH2 0xEC5 JUMP JUMPDEST PUSH2 0x43D JUMP JUMPDEST PUSH2 0x260 PUSH2 0x25B CALLDATASIZE PUSH1 0x4 PUSH2 0x103A JUMP JUMPDEST PUSH2 0x48E JUMP JUMPDEST PUSH1 0x40 MLOAD PUSH2 0x231 SWAP4 SWAP3 SWAP2 SWAP1 PUSH2 0x128F JUMP JUMPDEST PUSH2 0x282 PUSH2 0x27D CALLDATASIZE PUSH1 0x4 PUSH2 0xE51 JUMP JUMPDEST PUSH2 0x52E JUMP JUMPDEST PUSH1 0x40 MLOAD PUSH2 0x231 SWAP2 SWAP1 PUSH2 0x11D2 JUMP JUMPDEST PUSH2 0x1FC PUSH2 0x20C CALLDATASIZE PUSH1 0x4 PUSH2 0xE92 JUMP JUMPDEST PUSH2 0x224 PUSH2 0x610 JUMP JUMPDEST PUSH2 0x1FC PUSH2 0x617 JUMP JUMPDEST PUSH2 0x1FC PUSH2 0x67C JUMP JUMPDEST PUSH2 0x2BD PUSH2 0x6AE JUMP JUMPDEST PUSH1 0x40 MLOAD PUSH2 0x231 SWAP2 SWAP1 PUSH2 0x14B1 JUMP JUMPDEST PUSH2 0x2D2 PUSH2 0x6B6 JUMP JUMPDEST PUSH1 0x40 MLOAD PUSH2 0x231 SWAP2 SWAP1 PUSH2 0x14BC JUMP JUMPDEST PUSH2 0x1FC PUSH2 0x6BE JUMP JUMPDEST PUSH2 0x282 PUSH2 0x2F5 CALLDATASIZE PUSH1 0x4 PUSH2 0xCBB JUMP JUMPDEST PUSH2 0x723 JUMP JUMPDEST PUSH2 0x1FC PUSH2 0x20C CALLDATASIZE PUSH1 0x4 PUSH2 0x1007 JUMP JUMPDEST PUSH2 0x224 PUSH2 0x72C JUMP JUMPDEST PUSH2 0x1FC PUSH2 0x20C CALLDATASIZE PUSH1 0x4 PUSH2 0xE16 JUMP JUMPDEST PUSH2 0x331 PUSH2 0x32C CALLDATASIZE PUSH1 0x4 PUSH2 0xEDD JUMP JUMPDEST PUSH2 0x73A JUMP JUMPDEST PUSH1 0x40 MLOAD PUSH2 0x231 SWAP2 SWAP1 PUSH2 0x13C5 JUMP JUMPDEST PUSH2 0x1FC PUSH2 0x7F7 JUMP JUMPDEST PUSH2 0x224 PUSH2 0x354 CALLDATASIZE PUSH1 0x4 PUSH2 0xEC5 JUMP JUMPDEST PUSH2 0x7FC JUMP JUMPDEST PUSH2 0x1FC PUSH2 0x802 JUMP JUMPDEST PUSH2 0x224 PUSH2 0x80D JUMP JUMPDEST PUSH2 0x1FC PUSH2 0x20C CALLDATASIZE PUSH1 0x4 PUSH2 0xF77 JUMP JUMPDEST PUSH2 0x37F PUSH2 0x812 JUMP JUMPDEST PUSH1 0x40 MLOAD PUSH2 0x231 SWAP3 SWAP2 SWAP1 PUSH2 0x152F JUMP JUMPDEST PUSH2 0x395 PUSH2 0x84B JUMP JUMPDEST PUSH1 0x40 MLOAD PUSH2 0x231 SWAP2 SWAP1 PUSH2 0x11F3 JUMP JUMPDEST PUSH2 0x1FC PUSH2 0x850 JUMP JUMPDEST PUSH2 0x3B2 PUSH2 0x887 JUMP JUMPDEST PUSH1 0x40 MLOAD PUSH2 0x231 SWAP2 SWAP1 PUSH2 0x1513 JUMP JUMPDEST PUSH2 0x224 PUSH2 0x9E0 JUMP JUMPDEST PUSH2 0x1FC PUSH2 0x20C CALLDATASIZE PUSH1 0x4 PUSH2 0xD0C JUMP JUMPDEST PUSH2 0x1FC PUSH2 0x3E3 CALLDATASIZE PUSH1 0x4 PUSH2 0xEC5 JUMP JUMPDEST PUSH2 0x20C JUMP JUMPDEST PUSH2 0x1FC PUSH2 0x20C CALLDATASIZE PUSH1 0x4 PUSH2 0xEC5 JUMP JUMPDEST PUSH1 0x40 MLOAD PUSH32 0x8C379A000000000000000000000000000000000000000000000000000000000 DUP2 MSTORE PUSH1 0x4 ADD PUSH2 0x428 SWAP1 PUSH2 0x138E JUMP JUMPDEST PUSH1 0x40 MLOAD DUP1 SWAP2 SUB SWAP1 REVERT JUMPDEST JUMP JUMPDEST POP JUMP JUMPDEST POP PUSH2 0x7C7 SWAP1 JUMP JUMPDEST CALLER PUSH20 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF AND PUSH32 0x7FCF532C15F0A6DB0BD6D0E038BEA71D30D808C7D98CB3BF7268A95BF5081B65 DUP3 PUSH1 0x40 MLOAD PUSH2 0x483 SWAP2 SWAP1 PUSH2 0x1526 JUMP JUMPDEST PUSH1 0x40 MLOAD DUP1 SWAP2 SUB SWAP1 LOG2 POP JUMP JUMPDEST POP POP PUSH1 0x40 DUP1 MLOAD DUP1 DUP3 ADD DUP3 MSTORE PUSH1 0x4 DUP1 DUP3 MSTORE PUSH32 0x1234567800000000000000000000000000000000000000000000000000000000 PUSH1 0x20 DUP1 DUP5 ADD SWAP2 SWAP1 SWAP2 MSTORE DUP4 MLOAD DUP1 DUP6 ADD DUP6 MSTORE DUP3 DUP2 MSTORE PUSH32 0x8765432100000000000000000000000000000000000000000000000000000000 DUP2 DUP4 ADD MSTORE DUP5 MLOAD DUP1 DUP7 ADD SWAP1 SWAP6 MSTORE SWAP2 DUP5 MSTORE PUSH32 0x616D657400000000000000000000000000000000000000000000000000000000 SWAP1 DUP5 ADD MSTORE SWAP1 SWAP4 SWAP1 SWAP3 POP JUMP JUMPDEST PUSH1 0x0 PUSH1 0x60 PUSH1 0x40 MLOAD DUP1 PUSH1 0x40 ADD PUSH1 0x40 MSTORE DUP1 PUSH1 0x1C DUP2 MSTORE PUSH1 0x20 ADD PUSH32 0x19457468657265756D205369676E6564204D6573736167653A0A333200000000 DUP2 MSTORE POP SWAP1 POP PUSH1 0x0 DUP2 DUP8 PUSH1 0x40 MLOAD PUSH1 0x20 ADD PUSH2 0x57F SWAP3 SWAP2 SWAP1 PUSH2 0x11B0 JUMP JUMPDEST PUSH1 0x40 MLOAD PUSH1 0x20 DUP2 DUP4 SUB SUB DUP2 MSTORE SWAP1 PUSH1 0x40 MSTORE DUP1 MLOAD SWAP1 PUSH1 0x20 ADD KECCAK256 SWAP1 POP PUSH1 0x1 DUP2 DUP8 DUP8 DUP8 PUSH1 0x40 MLOAD PUSH1 0x0 DUP2 MSTORE PUSH1 0x20 ADD PUSH1 0x40 MSTORE PUSH1 0x40 MLOAD PUSH2 0x5BA SWAP5 SWAP4 SWAP3 SWAP2 SWAP1 PUSH2 0x1271 JUMP JUMPDEST PUSH1 0x20 PUSH1 0x40 MLOAD PUSH1 0x20 DUP2 SUB SWAP1 DUP1 DUP5 SUB SWAP1 DUP6 GAS STATICCALL ISZERO DUP1 ISZERO PUSH2 0x5DC JUMPI RETURNDATASIZE PUSH1 0x0 DUP1 RETURNDATACOPY RETURNDATASIZE PUSH1 0x0 REVERT JUMPDEST POP POP PUSH1 0x40 MLOAD PUSH32 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE0 ADD MLOAD SWAP9 SWAP8 POP POP POP POP POP POP POP POP JUMP JUMPDEST PUSH2 0x7C7 JUMPDEST SWAP1 JUMP JUMPDEST PUSH1 0x40 DUP1 MLOAD DUP1 DUP3 ADD DUP3 MSTORE PUSH1 0x14 DUP2 MSTORE PUSH32 0x5245564552545F574954485F434F4E5354414E54000000000000000000000000 PUSH1 0x20 DUP3 ADD MSTORE SWAP1 MLOAD PUSH32 0x8C379A000000000000000000000000000000000000000000000000000000000 DUP2 MSTORE PUSH2 0x428 SWAP2 SWAP1 PUSH1 0x4 ADD PUSH2 0x12D1 JUMP JUMPDEST PUSH1 0x40 MLOAD PUSH32 0x8C379A000000000000000000000000000000000000000000000000000000000 DUP2 MSTORE PUSH1 0x4 ADD PUSH2 0x428 SWAP1 PUSH2 0x1357 JUMP JUMPDEST PUSH2 0x614 PUSH2 0x9E6 JUMP JUMPDEST PUSH2 0x614 PUSH2 0x9FE JUMP JUMPDEST PUSH1 0x40 DUP1 MLOAD DUP1 DUP3 ADD DUP3 MSTORE PUSH1 0x15 DUP2 MSTORE PUSH32 0x524551554952455F574954485F434F4E5354414E540000000000000000000000 PUSH1 0x20 DUP3 ADD MSTORE SWAP1 MLOAD PUSH32 0x8C379A000000000000000000000000000000000000000000000000000000000 DUP2 MSTORE PUSH2 0x428 SWAP2 SWAP1 PUSH1 0x4 ADD PUSH2 0x12D1 JUMP JUMPDEST POP SWAP3 SWAP4 SWAP3 POP POP POP JUMP JUMPDEST PUSH1 0x0 DUP1 SLOAD PUSH1 0x1 ADD SWAP1 DUP2 SWAP1 SSTORE SWAP1 JUMP JUMPDEST PUSH2 0x742 PUSH2 0xA1E JUMP JUMPDEST POP PUSH1 0x40 DUP1 MLOAD PUSH1 0x80 DUP2 ADD DUP3 MSTORE SWAP2 DUP3 MSTORE DUP1 MLOAD DUP1 DUP3 ADD DUP3 MSTORE PUSH1 0x4 DUP1 DUP3 MSTORE PUSH32 0x1234567800000000000000000000000000000000000000000000000000000000 PUSH1 0x20 DUP4 DUP2 ADD SWAP2 SWAP1 SWAP2 MSTORE DUP1 DUP6 ADD SWAP3 SWAP1 SWAP3 MSTORE DUP3 MLOAD DUP1 DUP5 ADD DUP5 MSTORE DUP2 DUP2 MSTORE PUSH32 0x8765432100000000000000000000000000000000000000000000000000000000 DUP2 DUP5 ADD MSTORE DUP5 DUP5 ADD MSTORE DUP3 MLOAD DUP1 DUP5 ADD SWAP1 SWAP4 MSTORE DUP3 MSTORE PUSH32 0x616D657400000000000000000000000000000000000000000000000000000000 SWAP1 DUP3 ADD MSTORE PUSH1 0x60 DUP3 ADD MSTORE SWAP1 JUMP JUMPDEST PUSH2 0x431 JUMP JUMPDEST PUSH1 0x1 ADD SWAP1 JUMP JUMPDEST PUSH1 0x0 DUP1 SLOAD PUSH1 0x1 ADD SWAP1 SSTORE JUMP JUMPDEST PUSH1 0x1 SWAP1 JUMP JUMPDEST PUSH1 0x40 DUP1 MLOAD DUP1 DUP3 ADD SWAP1 SWAP2 MSTORE PUSH1 0x5 DUP2 MSTORE PUSH32 0x68656C6C6F000000000000000000000000000000000000000000000000000000 PUSH1 0x20 DUP3 ADD MSTORE PUSH1 0x1 SWAP2 JUMP JUMPDEST PUSH1 0x60 SWAP1 JUMP JUMPDEST PUSH32 0x61A6029A4C7DDEE5824D171331EECBD015D26A271310A223718B837FACB5B771 PUSH1 0x40 MLOAD PUSH2 0x87D SWAP1 PUSH2 0x12EB JUMP JUMPDEST PUSH1 0x40 MLOAD DUP1 SWAP2 SUB SWAP1 LOG1 JUMP JUMPDEST PUSH2 0x88F PUSH2 0xA4C JUMP JUMPDEST PUSH1 0x40 DUP1 MLOAD PUSH1 0x2 DUP1 DUP3 MSTORE PUSH1 0x60 DUP3 DUP2 ADD SWAP1 SWAP4 MSTORE DUP2 PUSH1 0x20 ADD JUMPDEST PUSH1 0x60 DUP2 MSTORE PUSH1 0x20 ADD SWAP1 PUSH1 0x1 SWAP1 SUB SWAP1 DUP2 PUSH2 0x8A5 JUMPI SWAP1 POP POP SWAP1 POP PUSH1 0x40 MLOAD DUP1 PUSH1 0x40 ADD PUSH1 0x40 MSTORE DUP1 PUSH1 0x5 DUP2 MSTORE PUSH1 0x20 ADD PUSH32 0x3078313233000000000000000000000000000000000000000000000000000000 DUP2 MSTORE POP DUP2 PUSH1 0x0 DUP2 MLOAD DUP2 LT PUSH2 0x8FF JUMPI INVALID JUMPDEST PUSH1 0x20 MUL PUSH1 0x20 ADD ADD DUP2 SWAP1 MSTORE POP PUSH1 0x40 MLOAD DUP1 PUSH1 0x40 ADD PUSH1 0x40 MSTORE DUP1 PUSH1 0x5 DUP2 MSTORE PUSH1 0x20 ADD PUSH32 0x3078333231000000000000000000000000000000000000000000000000000000 DUP2 MSTORE POP DUP2 PUSH1 0x1 DUP2 MLOAD DUP2 LT PUSH2 0x94D JUMPI INVALID JUMPDEST PUSH1 0x20 SWAP1 DUP2 MUL SWAP2 SWAP1 SWAP2 ADD DUP2 ADD SWAP2 SWAP1 SWAP2 MSTORE PUSH1 0x40 DUP1 MLOAD PUSH1 0xC0 DUP2 ADD DUP3 MSTORE PUSH1 0x5 PUSH1 0x80 DUP3 ADD DUP2 DUP2 MSTORE PUSH32 0x3078313233000000000000000000000000000000000000000000000000000000 PUSH1 0xA0 DUP5 ADD MSTORE DUP3 MSTORE DUP2 DUP5 ADD MSTORE DUP1 DUP3 ADD SWAP4 SWAP1 SWAP4 MSTORE DUP1 MLOAD DUP1 DUP3 ADD SWAP1 SWAP2 MSTORE PUSH1 0x3 DUP2 MSTORE PUSH32 0x6162630000000000000000000000000000000000000000000000000000000000 SWAP2 DUP2 ADD SWAP2 SWAP1 SWAP2 MSTORE PUSH1 0x60 DUP3 ADD MSTORE SWAP1 POP SWAP1 JUMP JUMPDEST PUSH2 0x4D2 SWAP1 JUMP JUMPDEST PUSH1 0x40 MLOAD DUP1 PUSH1 0x20 ADD PUSH1 0x40 MSTORE DUP1 PUSH2 0x9F9 PUSH2 0xA7A JUMP JUMPDEST SWAP1 MSTORE SWAP1 JUMP JUMPDEST PUSH1 0x40 MLOAD DUP1 PUSH1 0x40 ADD PUSH1 0x40 MSTORE DUP1 PUSH2 0xA11 PUSH2 0xA4C JUMP JUMPDEST DUP2 MSTORE PUSH1 0x20 ADD PUSH1 0x60 DUP2 MSTORE POP SWAP1 JUMP JUMPDEST PUSH1 0x40 MLOAD DUP1 PUSH1 0x80 ADD PUSH1 0x40 MSTORE DUP1 PUSH2 0xA31 PUSH2 0xA8D JUMP JUMPDEST DUP2 MSTORE PUSH1 0x20 ADD PUSH1 0x60 DUP2 MSTORE PUSH1 0x20 ADD PUSH1 0x60 DUP2 MSTORE PUSH1 0x20 ADD PUSH1 0x60 DUP2 MSTORE POP SWAP1 JUMP JUMPDEST PUSH1 0x40 MLOAD DUP1 PUSH1 0x80 ADD PUSH1 0x40 MSTORE DUP1 PUSH1 0x60 DUP2 MSTORE PUSH1 0x20 ADD PUSH1 0x0 PUSH4 0xFFFFFFFF AND DUP2 MSTORE PUSH1 0x20 ADD PUSH1 0x60 DUP2 MSTORE PUSH1 0x20 ADD PUSH1 0x60 DUP2 MSTORE POP SWAP1 JUMP JUMPDEST PUSH1 0x40 MLOAD DUP1 PUSH1 0x20 ADD PUSH1 0x40 MSTORE DUP1 PUSH1 0x0 DUP2 MSTORE POP SWAP1 JUMP JUMPDEST PUSH1 0x40 MLOAD DUP1 PUSH1 0x60 ADD PUSH1 0x40 MSTORE DUP1 PUSH1 0x0 DUP2 MSTORE PUSH1 0x20 ADD PUSH1 0x60 DUP2 MSTORE PUSH1 0x20 ADD PUSH1 0x60 DUP2 MSTORE POP SWAP1 JUMP JUMPDEST PUSH1 0x0 DUP3 PUSH1 0x1F DUP4 ADD SLT PUSH2 0xABE JUMPI DUP1 DUP2 REVERT JUMPDEST DUP2 CALLDATALOAD PUSH2 0xAD1 PUSH2 0xACC DUP3 PUSH2 0x156F JUMP JUMPDEST PUSH2 0x1548 JUMP JUMPDEST DUP2 DUP2 MSTORE SWAP2 POP PUSH1 0x20 DUP1 DUP4 ADD SWAP1 DUP5 ADD PUSH1 0x0 JUMPDEST DUP4 DUP2 LT ISZERO PUSH2 0xB0E JUMPI PUSH2 0xAF9 DUP8 PUSH1 0x20 DUP5 CALLDATALOAD DUP10 ADD ADD PUSH2 0xB73 JUMP JUMPDEST DUP4 MSTORE PUSH1 0x20 SWAP3 DUP4 ADD SWAP3 SWAP2 SWAP1 SWAP2 ADD SWAP1 PUSH1 0x1 ADD PUSH2 0xAE1 JUMP JUMPDEST POP POP POP POP SWAP3 SWAP2 POP POP JUMP JUMPDEST PUSH1 0x0 DUP3 PUSH1 0x1F DUP4 ADD SLT PUSH2 0xB28 JUMPI DUP1 DUP2 REVERT JUMPDEST DUP2 CALLDATALOAD PUSH2 0xB36 PUSH2 0xACC DUP3 PUSH2 0x156F JUMP JUMPDEST DUP2 DUP2 MSTORE SWAP2 POP PUSH1 0x20 DUP1 DUP4 ADD SWAP1 DUP5 ADD PUSH1 0x0 JUMPDEST DUP4 DUP2 LT ISZERO PUSH2 0xB0E JUMPI PUSH2 0xB5E DUP8 PUSH1 0x20 DUP5 CALLDATALOAD DUP10 ADD ADD PUSH2 0xBFA JUMP JUMPDEST DUP4 MSTORE PUSH1 0x20 SWAP3 DUP4 ADD SWAP3 SWAP2 SWAP1 SWAP2 ADD SWAP1 PUSH1 0x1 ADD PUSH2 0xB46 JUMP JUMPDEST PUSH1 0x0 DUP3 PUSH1 0x1F DUP4 ADD SLT PUSH2 0xB83 JUMPI DUP1 DUP2 REVERT JUMPDEST DUP2 CALLDATALOAD PUSH8 0xFFFFFFFFFFFFFFFF DUP2 GT ISZERO PUSH2 0xB99 JUMPI DUP2 DUP3 REVERT JUMPDEST PUSH2 0xBCA PUSH1 0x20 PUSH32 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE0 PUSH1 0x1F DUP5 ADD AND ADD PUSH2 0x1548 JUMP JUMPDEST SWAP2 POP DUP1 DUP3 MSTORE DUP4 PUSH1 0x20 DUP3 DUP6 ADD ADD GT ISZERO PUSH2 0xBE1 JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST DUP1 PUSH1 0x20 DUP5 ADD PUSH1 0x20 DUP5 ADD CALLDATACOPY PUSH1 0x0 SWAP1 DUP3 ADD PUSH1 0x20 ADD MSTORE SWAP3 SWAP2 POP POP JUMP JUMPDEST PUSH1 0x0 PUSH1 0x80 DUP3 DUP5 SUB SLT ISZERO PUSH2 0xC0B JUMPI DUP1 DUP2 REVERT JUMPDEST PUSH2 0xC15 PUSH1 0x80 PUSH2 0x1548 JUMP JUMPDEST SWAP1 POP DUP2 CALLDATALOAD PUSH8 0xFFFFFFFFFFFFFFFF DUP1 DUP3 GT ISZERO PUSH2 0xC2F JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST PUSH2 0xC3B DUP6 DUP4 DUP7 ADD PUSH2 0xB73 JUMP JUMPDEST DUP4 MSTORE PUSH2 0xC4A DUP6 PUSH1 0x20 DUP7 ADD PUSH2 0xCA1 JUMP JUMPDEST PUSH1 0x20 DUP5 ADD MSTORE PUSH1 0x40 DUP5 ADD CALLDATALOAD SWAP2 POP DUP1 DUP3 GT ISZERO PUSH2 0xC63 JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST PUSH2 0xC6F DUP6 DUP4 DUP7 ADD PUSH2 0xAAE JUMP JUMPDEST PUSH1 0x40 DUP5 ADD MSTORE PUSH1 0x60 DUP5 ADD CALLDATALOAD SWAP2 POP DUP1 DUP3 GT ISZERO PUSH2 0xC88 JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST POP PUSH2 0xC95 DUP5 DUP3 DUP6 ADD PUSH2 0xB73 JUMP JUMPDEST PUSH1 0x60 DUP4 ADD MSTORE POP SWAP3 SWAP2 POP POP JUMP JUMPDEST DUP1 CALLDATALOAD PUSH4 0xFFFFFFFF DUP2 AND DUP2 EQ PUSH2 0xCB5 JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST SWAP3 SWAP2 POP POP JUMP JUMPDEST PUSH1 0x0 DUP1 PUSH1 0x0 DUP1 PUSH1 0x0 PUSH1 0xA0 DUP7 DUP9 SUB SLT ISZERO PUSH2 0xCD2 JUMPI DUP1 DUP2 REVERT JUMPDEST DUP6 CALLDATALOAD PUSH2 0xCDD DUP2 PUSH2 0x15BF JUMP JUMPDEST SWAP5 POP PUSH1 0x20 DUP7 ADD CALLDATALOAD SWAP4 POP PUSH1 0x40 DUP7 ADD CALLDATALOAD SWAP3 POP PUSH1 0x60 DUP7 ADD CALLDATALOAD PUSH2 0xCFB DUP2 PUSH2 0x15BF JUMP JUMPDEST SWAP5 SWAP8 SWAP4 SWAP7 POP SWAP2 SWAP5 PUSH1 0x80 ADD CALLDATALOAD SWAP3 SWAP2 POP POP JUMP JUMPDEST PUSH1 0x0 PUSH1 0x20 DUP1 DUP4 DUP6 SUB SLT ISZERO PUSH2 0xD1E JUMPI DUP2 DUP3 REVERT JUMPDEST DUP3 CALLDATALOAD PUSH8 0xFFFFFFFFFFFFFFFF DUP2 GT ISZERO PUSH2 0xD34 JUMPI DUP3 DUP4 REVERT JUMPDEST DUP1 DUP5 ADD DUP6 PUSH1 0x1F DUP3 ADD SLT PUSH2 0xD45 JUMPI DUP4 DUP5 REVERT JUMPDEST DUP1 CALLDATALOAD SWAP2 POP PUSH2 0xD55 PUSH2 0xACC DUP4 PUSH2 0x156F JUMP JUMPDEST DUP3 DUP2 MSTORE DUP4 DUP2 ADD SWAP1 DUP3 DUP6 ADD DUP7 JUMPDEST DUP6 DUP2 LT ISZERO PUSH2 0xD8A JUMPI PUSH2 0xD78 DUP11 DUP9 DUP5 CALLDATALOAD DUP9 ADD ADD PUSH2 0xB18 JUMP JUMPDEST DUP5 MSTORE SWAP3 DUP7 ADD SWAP3 SWAP1 DUP7 ADD SWAP1 PUSH1 0x1 ADD PUSH2 0xD61 JUMP JUMPDEST POP SWAP1 SWAP9 SWAP8 POP POP POP POP POP POP POP POP JUMP JUMPDEST PUSH1 0x0 PUSH1 0x20 DUP1 DUP4 DUP6 SUB SLT ISZERO PUSH2 0xDAA JUMPI DUP2 DUP3 REVERT JUMPDEST DUP3 CALLDATALOAD PUSH8 0xFFFFFFFFFFFFFFFF DUP2 GT ISZERO PUSH2 0xDC0 JUMPI DUP3 DUP4 REVERT JUMPDEST DUP1 DUP5 ADD DUP6 PUSH1 0x1F DUP3 ADD SLT PUSH2 0xDD1 JUMPI DUP4 DUP5 REVERT JUMPDEST DUP1 CALLDATALOAD SWAP2 POP PUSH2 0xDE1 PUSH2 0xACC DUP4 PUSH2 0x156F JUMP JUMPDEST DUP3 DUP2 MSTORE DUP4 DUP2 ADD SWAP1 DUP3 DUP6 ADD DUP7 JUMPDEST DUP6 DUP2 LT ISZERO PUSH2 0xD8A JUMPI PUSH2 0xE04 DUP11 DUP9 DUP5 CALLDATALOAD DUP9 ADD ADD PUSH2 0xB73 JUMP JUMPDEST DUP5 MSTORE SWAP3 DUP7 ADD SWAP3 SWAP1 DUP7 ADD SWAP1 PUSH1 0x1 ADD PUSH2 0xDED JUMP JUMPDEST PUSH1 0x0 PUSH1 0x20 DUP3 DUP5 SUB SLT ISZERO PUSH2 0xE27 JUMPI DUP1 DUP2 REVERT JUMPDEST DUP2 CALLDATALOAD PUSH8 0xFFFFFFFFFFFFFFFF DUP2 GT ISZERO PUSH2 0xE3D JUMPI DUP2 DUP3 REVERT JUMPDEST PUSH2 0xE49 DUP5 DUP3 DUP6 ADD PUSH2 0xB18 JUMP JUMPDEST SWAP5 SWAP4 POP POP POP POP JUMP JUMPDEST PUSH1 0x0 DUP1 PUSH1 0x0 DUP1 PUSH1 0x80 DUP6 DUP8 SUB SLT ISZERO PUSH2 0xE66 JUMPI DUP2 DUP3 REVERT JUMPDEST DUP5 CALLDATALOAD SWAP4 POP PUSH1 0x20 DUP6 ADD CALLDATALOAD PUSH1 0xFF DUP2 AND DUP2 EQ PUSH2 0xE7D JUMPI DUP3 DUP4 REVERT JUMPDEST SWAP4 SWAP7 SWAP4 SWAP6 POP POP POP POP PUSH1 0x40 DUP3 ADD CALLDATALOAD SWAP2 PUSH1 0x60 ADD CALLDATALOAD SWAP1 JUMP JUMPDEST PUSH1 0x0 PUSH1 0x20 DUP3 DUP5 SUB SLT ISZERO PUSH2 0xEA3 JUMPI DUP1 DUP2 REVERT JUMPDEST DUP2 CALLDATALOAD PUSH8 0xFFFFFFFFFFFFFFFF DUP2 GT ISZERO PUSH2 0xEB9 JUMPI DUP2 DUP3 REVERT JUMPDEST PUSH2 0xE49 DUP5 DUP3 DUP6 ADD PUSH2 0xB73 JUMP JUMPDEST PUSH1 0x0 PUSH1 0x20 DUP3 DUP5 SUB SLT ISZERO PUSH2 0xED6 JUMPI DUP1 DUP2 REVERT JUMPDEST POP CALLDATALOAD SWAP2 SWAP1 POP JUMP JUMPDEST PUSH1 0x0 PUSH1 0x20 DUP3 DUP5 SUB SLT ISZERO PUSH2 0xEEE JUMPI DUP1 DUP2 REVERT JUMPDEST DUP2 CALLDATALOAD PUSH8 0xFFFFFFFFFFFFFFFF DUP1 DUP3 GT ISZERO PUSH2 0xF05 JUMPI DUP3 DUP4 REVERT JUMPDEST DUP2 DUP5 ADD PUSH1 0x60 DUP2 DUP8 SUB SLT ISZERO PUSH2 0xF17 JUMPI DUP4 DUP5 REVERT JUMPDEST PUSH2 0xF21 PUSH1 0x60 PUSH2 0x1548 JUMP JUMPDEST SWAP3 POP DUP1 CALLDATALOAD DUP4 MSTORE PUSH1 0x20 DUP2 ADD CALLDATALOAD DUP3 DUP2 GT ISZERO PUSH2 0xF38 JUMPI DUP5 DUP6 REVERT JUMPDEST PUSH2 0xF44 DUP8 DUP3 DUP5 ADD PUSH2 0xB73 JUMP JUMPDEST PUSH1 0x20 DUP6 ADD MSTORE POP PUSH1 0x40 DUP2 ADD CALLDATALOAD DUP3 DUP2 GT ISZERO PUSH2 0xF5B JUMPI DUP5 DUP6 REVERT JUMPDEST PUSH2 0xF67 DUP8 DUP3 DUP5 ADD PUSH2 0xB73 JUMP JUMPDEST PUSH1 0x40 DUP6 ADD MSTORE POP SWAP2 SWAP6 SWAP5 POP POP POP POP POP JUMP JUMPDEST PUSH1 0x0 PUSH1 0x20 DUP3 DUP5 SUB SLT ISZERO PUSH2 0xF88 JUMPI DUP1 DUP2 REVERT JUMPDEST DUP2 CALLDATALOAD PUSH8 0xFFFFFFFFFFFFFFFF DUP1 DUP3 GT ISZERO PUSH2 0xF9F JUMPI DUP3 DUP4 REVERT JUMPDEST DUP2 DUP5 ADD PUSH1 0x40 DUP2 DUP8 SUB SLT ISZERO PUSH2 0xFB1 JUMPI DUP4 DUP5 REVERT JUMPDEST PUSH2 0xFBB PUSH1 0x40 PUSH2 0x1548 JUMP JUMPDEST SWAP3 POP DUP1 CALLDATALOAD DUP3 DUP2 GT ISZERO PUSH2 0xFCB JUMPI DUP5 DUP6 REVERT JUMPDEST PUSH2 0xFD7 DUP8 DUP3 DUP5 ADD PUSH2 0xBFA JUMP JUMPDEST DUP5 MSTORE POP PUSH1 0x20 DUP2 ADD CALLDATALOAD DUP3 DUP2 GT ISZERO PUSH2 0xFEB JUMPI DUP5 DUP6 REVERT JUMPDEST PUSH2 0xFF7 DUP8 DUP3 DUP5 ADD PUSH2 0xB73 JUMP JUMPDEST PUSH1 0x20 DUP6 ADD MSTORE POP SWAP2 SWAP6 SWAP5 POP POP POP POP POP JUMP JUMPDEST PUSH1 0x0 PUSH1 0x20 DUP3 DUP5 SUB SLT ISZERO PUSH2 0x1018 JUMPI DUP1 DUP2 REVERT JUMPDEST DUP2 CALLDATALOAD PUSH8 0xFFFFFFFFFFFFFFFF DUP2 GT ISZERO PUSH2 0x102E JUMPI DUP2 DUP3 REVERT JUMPDEST PUSH2 0xE49 DUP5 DUP3 DUP6 ADD PUSH2 0xBFA JUMP JUMPDEST PUSH1 0x0 DUP1 PUSH1 0x0 PUSH1 0x60 DUP5 DUP7 SUB SLT ISZERO PUSH2 0x104E JUMPI DUP1 DUP2 REVERT JUMPDEST DUP4 CALLDATALOAD SWAP3 POP PUSH1 0x20 DUP5 ADD CALLDATALOAD PUSH8 0xFFFFFFFFFFFFFFFF DUP1 DUP3 GT ISZERO PUSH2 0x106C JUMPI DUP3 DUP4 REVERT JUMPDEST PUSH2 0x1078 DUP8 DUP4 DUP9 ADD PUSH2 0xB73 JUMP JUMPDEST SWAP4 POP PUSH1 0x40 DUP7 ADD CALLDATALOAD SWAP2 POP DUP1 DUP3 GT ISZERO PUSH2 0x108D JUMPI DUP3 DUP4 REVERT JUMPDEST POP PUSH2 0x109A DUP7 DUP3 DUP8 ADD PUSH2 0xB73 JUMP JUMPDEST SWAP2 POP POP SWAP3 POP SWAP3 POP SWAP3 JUMP JUMPDEST PUSH1 0x0 DUP2 MLOAD DUP1 DUP5 MSTORE PUSH2 0x10BC DUP2 PUSH1 0x20 DUP7 ADD PUSH1 0x20 DUP7 ADD PUSH2 0x158F JUMP JUMPDEST PUSH1 0x1F ADD PUSH32 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE0 AND SWAP3 SWAP1 SWAP3 ADD PUSH1 0x20 ADD SWAP3 SWAP2 POP POP JUMP JUMPDEST PUSH1 0x0 DUP2 MLOAD PUSH1 0x80 DUP5 MSTORE PUSH2 0x1103 PUSH1 0x80 DUP6 ADD DUP3 PUSH2 0x10A4 JUMP JUMPDEST PUSH1 0x20 SWAP2 POP PUSH4 0xFFFFFFFF DUP3 DUP6 ADD MLOAD AND DUP3 DUP7 ADD MSTORE PUSH1 0x40 DUP5 ADD MLOAD DUP6 DUP3 SUB PUSH1 0x40 DUP8 ADD MSTORE DUP2 DUP2 MLOAD DUP1 DUP5 MSTORE DUP5 DUP5 ADD SWAP2 POP DUP5 DUP6 DUP3 MUL DUP6 ADD ADD DUP6 DUP5 ADD DUP8 SWAP5 POP JUMPDEST DUP3 DUP6 LT ISZERO PUSH2 0x1189 JUMPI PUSH32 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE0 DUP7 DUP4 SUB ADD DUP5 MSTORE PUSH2 0x1175 DUP3 DUP3 MLOAD PUSH2 0x10A4 JUMP JUMPDEST PUSH1 0x1 SWAP6 SWAP1 SWAP6 ADD SWAP5 SWAP4 DUP8 ADD SWAP4 SWAP2 POP DUP7 ADD PUSH2 0x113B JUMP JUMPDEST POP PUSH1 0x60 DUP9 ADD MLOAD SWAP6 POP DUP9 DUP2 SUB PUSH1 0x60 DUP11 ADD MSTORE PUSH2 0x11A3 DUP2 DUP8 PUSH2 0x10A4 JUMP JUMPDEST SWAP10 SWAP9 POP POP POP POP POP POP POP POP POP JUMP JUMPDEST PUSH1 0x0 DUP4 MLOAD PUSH2 0x11C2 DUP2 DUP5 PUSH1 0x20 DUP9 ADD PUSH2 0x158F JUMP JUMPDEST SWAP2 SWAP1 SWAP2 ADD SWAP2 DUP3 MSTORE POP PUSH1 0x20 ADD SWAP2 SWAP1 POP JUMP JUMPDEST PUSH20 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF SWAP2 SWAP1 SWAP2 AND DUP2 MSTORE PUSH1 0x20 ADD SWAP1 JUMP JUMPDEST PUSH1 0x0 PUSH1 0x20 DUP1 DUP4 ADD DUP2 DUP5 MSTORE DUP1 DUP6 MLOAD DUP1 DUP4 MSTORE PUSH1 0x40 DUP7 ADD SWAP2 POP PUSH1 0x40 DUP5 DUP3 MUL DUP8 ADD ADD SWAP3 POP DUP4 DUP8 ADD DUP6 JUMPDEST DUP3 DUP2 LT ISZERO PUSH2 0x1264 JUMPI PUSH32 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC0 DUP9 DUP7 SUB ADD DUP5 MSTORE PUSH2 0x1252 DUP6 DUP4 MLOAD PUSH2 0x10EE JUMP JUMPDEST SWAP5 POP SWAP3 DUP6 ADD SWAP3 SWAP1 DUP6 ADD SWAP1 PUSH1 0x1 ADD PUSH2 0x1218 JUMP JUMPDEST POP SWAP3 SWAP8 SWAP7 POP POP POP POP POP POP POP JUMP JUMPDEST SWAP4 DUP5 MSTORE PUSH1 0xFF SWAP3 SWAP1 SWAP3 AND PUSH1 0x20 DUP5 ADD MSTORE PUSH1 0x40 DUP4 ADD MSTORE PUSH1 0x60 DUP3 ADD MSTORE PUSH1 0x80 ADD SWAP1 JUMP JUMPDEST PUSH1 0x0 PUSH1 0x60 DUP3 MSTORE PUSH2 0x12A2 PUSH1 0x60 DUP4 ADD DUP7 PUSH2 0x10A4 JUMP JUMPDEST DUP3 DUP2 SUB PUSH1 0x20 DUP5 ADD MSTORE PUSH2 0x12B4 DUP2 DUP7 PUSH2 0x10A4 JUMP JUMPDEST DUP4 DUP2 SUB PUSH1 0x40 DUP6 ADD MSTORE PUSH2 0x12C6 DUP2 DUP7 PUSH2 0x10A4 JUMP JUMPDEST SWAP8 SWAP7 POP POP POP POP POP POP POP JUMP JUMPDEST PUSH1 0x0 PUSH1 0x20 DUP3 MSTORE PUSH2 0x12E4 PUSH1 0x20 DUP4 ADD DUP5 PUSH2 0x10A4 JUMP JUMPDEST SWAP4 SWAP3 POP POP POP JUMP JUMPDEST PUSH1 0x40 DUP1 DUP3 MSTORE PUSH1 0x4 SWAP1 DUP3 ADD MSTORE PUSH32 0x1234567800000000000000000000000000000000000000000000000000000000 PUSH1 0x60 DUP3 ADD MSTORE PUSH1 0x80 PUSH1 0x20 DUP3 ADD DUP2 SWAP1 MSTORE PUSH1 0x5 SWAP1 DUP3 ADD MSTORE PUSH32 0x6C6F72656D000000000000000000000000000000000000000000000000000000 PUSH1 0xA0 DUP3 ADD MSTORE PUSH1 0xC0 ADD SWAP1 JUMP JUMPDEST PUSH1 0x20 DUP1 DUP3 MSTORE PUSH1 0xD SWAP1 DUP3 ADD MSTORE PUSH32 0x53494D504C455F52455645525400000000000000000000000000000000000000 PUSH1 0x40 DUP3 ADD MSTORE PUSH1 0x60 ADD SWAP1 JUMP JUMPDEST PUSH1 0x20 DUP1 DUP3 MSTORE PUSH1 0xE SWAP1 DUP3 ADD MSTORE PUSH32 0x53494D504C455F52455155495245000000000000000000000000000000000000 PUSH1 0x40 DUP3 ADD MSTORE PUSH1 0x60 ADD SWAP1 JUMP JUMPDEST PUSH1 0x0 PUSH1 0x20 DUP3 MSTORE DUP3 MLOAD PUSH1 0x80 PUSH1 0x20 DUP5 ADD MSTORE DUP1 MLOAD PUSH1 0xA0 DUP5 ADD MSTORE PUSH1 0x20 DUP2 ADD MLOAD PUSH1 0x60 PUSH1 0xC0 DUP6 ADD MSTORE PUSH2 0x13F5 PUSH2 0x100 DUP6 ADD DUP3 PUSH2 0x10A4 JUMP JUMPDEST PUSH1 0x40 DUP4 ADD MLOAD SWAP2 POP PUSH32 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF60 DUP6 DUP3 SUB ADD PUSH1 0xE0 DUP7 ADD MSTORE PUSH2 0x1430 DUP2 DUP4 PUSH2 0x10A4 JUMP JUMPDEST SWAP3 POP POP POP PUSH1 0x20 DUP5 ADD MLOAD PUSH32 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE0 DUP1 DUP6 DUP5 SUB ADD PUSH1 0x40 DUP7 ADD MSTORE PUSH2 0x146E DUP4 DUP4 PUSH2 0x10A4 JUMP JUMPDEST PUSH1 0x40 DUP8 ADD MLOAD SWAP4 POP DUP2 DUP7 DUP3 SUB ADD PUSH1 0x60 DUP8 ADD MSTORE PUSH2 0x1489 DUP2 DUP6 PUSH2 0x10A4 JUMP JUMPDEST SWAP3 POP POP PUSH1 0x60 DUP7 ADD MLOAD SWAP3 POP DUP1 DUP6 DUP4 SUB ADD PUSH1 0x80 DUP7 ADD MSTORE POP PUSH2 0x14A8 DUP2 DUP4 PUSH2 0x10A4 JUMP JUMPDEST SWAP6 SWAP5 POP POP POP POP POP JUMP JUMPDEST SWAP1 MLOAD MLOAD DUP2 MSTORE PUSH1 0x20 ADD SWAP1 JUMP JUMPDEST PUSH1 0x0 PUSH1 0x20 DUP3 MSTORE DUP3 MLOAD PUSH1 0x40 PUSH1 0x20 DUP5 ADD MSTORE PUSH2 0x14D8 PUSH1 0x60 DUP5 ADD DUP3 PUSH2 0x10EE JUMP JUMPDEST PUSH1 0x20 DUP6 ADD MLOAD SWAP2 POP PUSH32 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE0 DUP5 DUP3 SUB ADD PUSH1 0x40 DUP6 ADD MSTORE PUSH2 0x14A8 DUP2 DUP4 PUSH2 0x10A4 JUMP JUMPDEST PUSH1 0x0 PUSH1 0x20 DUP3 MSTORE PUSH2 0x12E4 PUSH1 0x20 DUP4 ADD DUP5 PUSH2 0x10EE JUMP JUMPDEST SWAP1 DUP2 MSTORE PUSH1 0x20 ADD SWAP1 JUMP JUMPDEST PUSH1 0x0 DUP4 DUP3 MSTORE PUSH1 0x40 PUSH1 0x20 DUP4 ADD MSTORE PUSH2 0xE49 PUSH1 0x40 DUP4 ADD DUP5 PUSH2 0x10A4 JUMP JUMPDEST PUSH1 0x40 MLOAD DUP2 DUP2 ADD PUSH8 0xFFFFFFFFFFFFFFFF DUP2 GT DUP3 DUP3 LT OR ISZERO PUSH2 0x1567 JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST PUSH1 0x40 MSTORE SWAP2 SWAP1 POP JUMP JUMPDEST PUSH1 0x0 PUSH8 0xFFFFFFFFFFFFFFFF DUP3 GT ISZERO PUSH2 0x1585 JUMPI DUP1 DUP2 REVERT JUMPDEST POP PUSH1 0x20 SWAP1 DUP2 MUL ADD SWAP1 JUMP JUMPDEST PUSH1 0x0 JUMPDEST DUP4 DUP2 LT ISZERO PUSH2 0x15AA JUMPI DUP2 DUP2 ADD MLOAD DUP4 DUP3 ADD MSTORE PUSH1 0x20 ADD PUSH2 0x1592 JUMP JUMPDEST DUP4 DUP2 GT ISZERO PUSH2 0x15B9 JUMPI PUSH1 0x0 DUP5 DUP5 ADD MSTORE JUMPDEST POP POP POP POP JUMP JUMPDEST PUSH20 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF DUP2 AND DUP2 EQ PUSH2 0x433 JUMPI PUSH1 0x0 DUP1 REVERT INVALID LOG3 PUSH6 0x627A7A723158 KECCAK256 0xD4 SWAP6 GASPRICE STATICCALL DUP16 0xE2 PUSH24 0xA67A582A705EC911D7C404B5A84176AB0E36AA14DA0E5986 ORIGIN PUSH13 0x6578706572696D656E74616CF5 PUSH5 0x736F6C6343 STOP SDIV LT STOP BLOCKHASH ", - "sourceMap": "641:6913:0:-;;;;8:9:-1;5:2;;;30:1;27;20:12;5:2;641:6913:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;1496:107;;;:::i;:::-;;3110:63;;;;;;;;;:::i;6518:128::-;;;;;;;;;:::i;:::-;;;;;;;;;;;;;;;;5127:84;;;;;;;;;:::i;7141:345::-;;;;;;;;;:::i;:::-;;;;;;;;;;2288:334;;;;;;;;;:::i;:::-;;;;;;;;2948:52;;;;;;;6123:117;;;:::i;1389:101::-;;;:::i;1286:97::-;;;:::i;4480:153::-;;;:::i;:::-;;;;;;;;4212:73;;;:::i;:::-;;;;;;;;1609:111;;;:::i;2776:166::-;;;;;;;;;:::i;3319:52::-;;;;;;;4659:72;;;:::i;3894:70::-;;;;;;;6719:317;;;;;;;;;:::i;:::-;;;;;;;;5932:112;;;:::i;989:140::-;;;;;;;;;:::i;4736:69::-;;;:::i;862:121::-;;;:::i;4143:64::-;;;;;;;4811:134;;;:::i;:::-;;;;;;;;;3809:80;;;:::i;:::-;;;;;;;;5277:125;;;:::i;3453:350::-;;;:::i;:::-;;;;;;;;1135:145;;;:::i;3969:79::-;;;;;;;6319:123;;;;;;;;;:::i;4951:47::-;;;;;;;1496:107;1564:32;;;;;;;;;;;;;;;;;;;;1496:107::o;3110:63::-;;:::o;6518:128::-;-1:-1:-1;6635:4:0;;6518:128::o;5127:84::-;5188:10;5177:27;;;5200:3;5177:27;;;;;;;;;;;;;;;5127:84;:::o;7141:345::-;-1:-1:-1;;7388:91:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;-1:-1:-1;7141:345:0:o;2288:334::-;2399:21;2436:19;:56;;;;;;;;;;;;;;;;;;;2502:20;2552:6;2560:4;2535:30;;;;;;;;;;;;;49:4:-1;39:7;30;26:21;22:32;13:7;6:49;2535:30:0;;;2525:41;;;;;;2502:64;;2583:32;2593:12;2607:1;2610;2613;2583:32;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;8:9:-1;5:2;;;45:16;42:1;39;24:38;77:16;74:1;67:27;5:2;-1:-1;;2583:32:0;;;;;;2288:334;-1:-1:-1;;;;;;;;2288:334:0:o;6123:117::-;6229:4;6123:117;;:::o;1389:101::-;1469:13;;;;;;;;;;;;;;;;1462:21;;;;;;;1469:13;1462:21;;;;1286:97;1353:23;;;;;;;;;;;4480:153;4574:51;;:::i;4212:73::-;4262:19;;:::i;1609:111::-;1698:14;;;;;;;;;;;;;;;;1683:30;;;;;;;1698:14;1683:30;;;;2776:166;-1:-1:-1;2934:1:0;;2776:166;-1:-1:-1;;;2776:166:0:o;4659:72::-;4699:4;4714:14;;4727:1;4714:14;;;;;4659:72;:::o;6719:317::-;6833:20;;:::i;:::-;-1:-1:-1;6876:153:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;6719:317::o;5932:112::-;6016:21;;989:140;1117:1;:5;;989:140::o;4736:69::-;4788:9;:14;;4801:1;4788:14;;;4736:69::o;862:121::-;975:1;862:121;:::o;4811:134::-;4919:19;;;;;;;;;;;;;;;;;4927:1;4811:134;:::o;3809:80::-;3870:15;3809:80;:::o;5277:125::-;5326:69;;;;;;;;;;;;;;;5277:125::o;3453:350::-;3497:15;;:::i;:::-;3551:14;;;3563:1;3551:14;;;3524:24;3551:14;;;;;;;;;;;;;;;;;;;;;;;;;;3524:41;;3575:22;;;;;;;;;;;;;;;;;:9;3585:1;3575:12;;;;;;;;;;;;;:22;;;;3607;;;;;;;;;;;;;;;;;:9;3617:1;3607:12;;;;;;;;;;;;;;;;;;:22;;;;3647:149;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;-1:-1:-1;3647:149:0;;;;-1:-1:-1;3453:350:0;:::o;1135:145::-;711:4;1135:145;:::o;641:6913::-;;;;;;;;;;;:::i;:::-;;;;:::o;:::-;;;;;;;;;;;:::i;:::-;;;;;;;;;;:::o;:::-;;;;;;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;:::o;:::-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::o;:::-;;;;;;;;;;;;;;:::o;:::-;;;;;;;;;;;;;;;;;;;;;;;;:::o;1002:685:-1:-;;1120:3;1113:4;1105:6;1101:17;1097:27;1087:2;;-1:-1;;1128:12;1087:2;1175:6;1162:20;1197:81;1212:65;1270:6;1212:65;;;1197:81;;;1306:21;;;1188:90;-1:-1;1350:4;1363:14;;;;1338:17;;1458:1;1443:238;1468:6;1465:1;1462:13;1443:238;;;1575:42;1613:3;1350:4;1551:3;1538:17;1342:6;1526:30;;1575:42;;;1563:55;;1350:4;1632:14;;;;1660;;;;;1490:1;1483:9;1443:238;;;1447:14;;;;1080:607;;;;;2448:727;;2580:3;2573:4;2565:6;2561:17;2557:27;2547:2;;-1:-1;;2588:12;2547:2;2635:6;2622:20;2657:95;2672:79;2744:6;2672:79;;2657:95;2780:21;;;2648:104;-1:-1;2824:4;2837:14;;;;2812:17;;2932:1;2917:252;2942:6;2939:1;2936:13;2917:252;;;3049:56;3101:3;2824:4;3025:3;3012:17;2816:6;3000:30;;3049:56;;;3037:69;;2824:4;3120:14;;;;3148;;;;;2964:1;2957:9;2917:252;;4100:432;;4197:3;4190:4;4182:6;4178:17;4174:27;4164:2;;-1:-1;;4205:12;4164:2;4252:6;4239:20;37223:18;37215:6;37212:30;37209:2;;;-1:-1;;37245:12;37209:2;4274:60;37386:4;37318:9;4190:4;37303:6;37299:17;37295:33;37376:15;4274:60;;;4265:69;;4354:6;4347:5;4340:21;4458:3;37386:4;4449:6;4382;4440:16;;4437:25;4434:2;;;4475:1;;4465:12;4434:2;41724:6;37386:4;4382:6;4378:17;37386:4;4416:5;4412:16;41701:30;41780:1;41762:16;;;37386:4;41762:16;41755:27;4416:5;4157:375;-1:-1;;4157:375;7617:1072;;7725:4;7713:9;7708:3;7704:19;7700:30;7697:2;;;-1:-1;;7733:12;7697:2;7761:20;7725:4;7761:20;;;7752:29;;7849:17;7836:31;7887:18;;7879:6;7876:30;7873:2;;;7864:1;;7909:12;7873:2;7954:54;8004:3;7995:6;7984:9;7980:22;7954:54;;;7936:16;7929:80;8108:48;8152:3;8075:2;8132:9;8128:22;8108:48;;;8075:2;8094:5;8090:16;8083:74;8262:2;8251:9;8247:18;8234:32;8220:46;;7887:18;8278:6;8275:30;8272:2;;;7864:1;;8308:12;8272:2;8353:75;8424:3;8415:6;8404:9;8400:22;8353:75;;;8262:2;8339:5;8335:16;8328:101;8521:2;8510:9;8506:18;8493:32;8479:46;;7887:18;8537:6;8534:30;8531:2;;;7864:1;;8567:12;8531:2;;8612:55;8663:3;8654:6;8643:9;8639:22;8612:55;;;8521:2;8598:5;8594:16;8587:81;;7691:998;;;;;9948:128;10014:20;;41531:10;41520:22;;42811:34;;42801:2;;42859:1;;42849:12;42801:2;9999:77;;;;;10216:743;;;;;;10388:3;10376:9;10367:7;10363:23;10359:33;10356:2;;;-1:-1;;10395:12;10356:2;85:6;72:20;97:33;124:5;97:33;;;10447:63;-1:-1;10547:2;10586:22;;9878:20;;-1:-1;10655:2;10694:22;;9878:20;;-1:-1;10763:2;10802:22;;72:20;97:33;72:20;97:33;;;10350:609;;;;-1:-1;10350:609;;10871:3;10911:22;9878:20;;10350:609;-1:-1;;10350:609;10966:457;;11135:2;;11123:9;11114:7;11110:23;11106:32;11103:2;;;-1:-1;;11141:12;11103:2;11199:17;11186:31;11237:18;11229:6;11226:30;11223:2;;;-1:-1;;11259:12;11223:2;11390:6;11379:9;11375:22;337:3;330:4;322:6;318:17;314:27;304:2;;-1:-1;;345:12;304:2;392:6;379:20;365:34;;414:120;429:104;526:6;429:104;;414:120;562:21;;;619:14;;;;594:17;;;-1:-1;699:273;724:6;721:1;718:13;699:273;;;831:77;904:3;11135:2;807:3;794:17;598:6;782:30;;831:77;;;819:90;;923:14;;;;951;;;;746:1;739:9;699:273;;;-1:-1;11279:128;;11097:326;-1:-1;;;;;;;;11097:326;11430:387;;11564:2;;11552:9;11543:7;11539:23;11535:32;11532:2;;;-1:-1;;11570:12;11532:2;11628:17;11615:31;11666:18;11658:6;11655:30;11652:2;;;-1:-1;;11688:12;11652:2;11784:6;11773:9;11769:22;1833:3;1826:4;1818:6;1814:17;1810:27;1800:2;;-1:-1;;1841:12;1800:2;1888:6;1875:20;1861:34;;1910:85;1925:69;1987:6;1925:69;;1910:85;2023:21;;;2080:14;;;;2055:17;;;-1:-1;2160:238;2185:6;2182:1;2179:13;2160:238;;;2292:42;2330:3;11564:2;2268:3;2255:17;2059:6;2243:30;;2292:42;;;2280:55;;2349:14;;;;2377;;;;2207:1;2200:9;2160:238;;11824:415;;11972:2;11960:9;11951:7;11947:23;11943:32;11940:2;;;-1:-1;;11978:12;11940:2;12036:17;12023:31;12074:18;12066:6;12063:30;12060:2;;;-1:-1;;12096:12;12060:2;12126:97;12215:7;12206:6;12195:9;12191:22;12126:97;;;12116:107;11934:305;-1:-1;;;;11934:305;12246:613;;;;;12399:3;12387:9;12378:7;12374:23;12370:33;12367:2;;;-1:-1;;12406:12;12367:2;4042:6;4029:20;12458:63;;12558:2;12599:9;12595:22;10148:20;41625:4;42958:5;41614:16;42935:5;42932:33;42922:2;;-1:-1;;42969:12;42922:2;12361:498;;12566:61;;-1:-1;;;;12664:2;12703:22;;4029:20;;12772:2;12811:22;4029:20;;12361:498;12866:345;;12979:2;12967:9;12958:7;12954:23;12950:32;12947:2;;;-1:-1;;12985:12;12947:2;13043:17;13030:31;13081:18;13073:6;13070:30;13067:2;;;-1:-1;;13103:12;13067:2;13133:62;13187:7;13178:6;13167:9;13163:22;13133:62;;13218:239;;13321:2;13309:9;13300:7;13296:23;13292:32;13289:2;;;-1:-1;;13327:12;13289:2;-1:-1;5055:20;;13283:174;-1:-1;13283:174;13818:385;;13951:2;13939:9;13930:7;13926:23;13922:32;13919:2;;;-1:-1;;13957:12;13919:2;14015:17;14002:31;14053:18;;14045:6;14042:30;14039:2;;;-1:-1;;14075:12;14039:2;14170:6;14159:9;14155:22;6174:4;6162:9;6157:3;6153:19;6149:30;6146:2;;;-1:-1;;6182:12;6146:2;6210:20;6174:4;6210:20;;;6201:29;;9891:6;9878:20;6293:16;6286:75;13951:2;6438:9;6434:18;6421:32;14053:18;6465:6;6462:30;6459:2;;;-1:-1;;6495:12;6459:2;6540:54;6590:3;6581:6;6570:9;6566:22;6540:54;;;13951:2;6526:5;6522:16;6515:80;;6683:2;6672:9;6668:18;6655:32;14053:18;6699:6;6696:30;6693:2;;;-1:-1;;6729:12;6693:2;6774:55;6825:3;6816:6;6805:9;6801:22;6774:55;;;6683:2;6756:16;;6749:81;-1:-1;6760:5;;13913:290;-1:-1;;;;;13913:290;14210:385;;14343:2;14331:9;14322:7;14318:23;14314:32;14311:2;;;-1:-1;;14349:12;14311:2;14407:17;14394:31;14445:18;;14437:6;14434:30;14431:2;;;-1:-1;;14467:12;14431:2;14562:6;14551:9;14547:22;7014:4;7002:9;6997:3;6993:19;6989:30;6986:2;;;-1:-1;;7022:12;6986:2;7050:20;7014:4;7050:20;;;7041:29;;7140:17;7127:31;14445:18;7170:6;7167:30;7164:2;;;-1:-1;;7200:12;7164:2;7245:68;7309:3;7300:6;7289:9;7285:22;7245:68;;;7227:16;7220:94;;14343:2;7399:9;7395:18;7382:32;14445:18;7426:6;7423:30;7420:2;;;-1:-1;;7456:12;7420:2;7501:55;7552:3;7543:6;7532:9;7528:22;7501:55;;;14343:2;7483:16;;7476:81;-1:-1;7487:5;;14305:290;-1:-1;;;;;14305:290;14602:373;;14729:2;14717:9;14708:7;14704:23;14700:32;14697:2;;;-1:-1;;14735:12;14697:2;14793:17;14780:31;14831:18;14823:6;14820:30;14817:2;;;-1:-1;;14853:12;14817:2;14883:76;14951:7;14942:6;14931:9;14927:22;14883:76;;15230:701;;;;15387:2;15375:9;15366:7;15362:23;15358:32;15355:2;;;-1:-1;;15393:12;15355:2;9891:6;9878:20;15445:63;;15573:2;15562:9;15558:18;15545:32;15597:18;;15589:6;15586:30;15583:2;;;-1:-1;;15619:12;15583:2;15649:62;15703:7;15694:6;15683:9;15679:22;15649:62;;;15639:72;;15776:2;15765:9;15761:18;15748:32;15734:46;;15597:18;15792:6;15789:30;15786:2;;;-1:-1;;15822:12;15786:2;;15852:63;15907:7;15898:6;15887:9;15883:22;15852:63;;;15842:73;;;15349:582;;;;;;18727:343;;18869:5;38830:12;39916:6;39911:3;39904:19;18962:52;19007:6;39953:4;39948:3;39944:14;39953:4;18988:5;18984:16;18962:52;;;42242:2;42222:14;42238:7;42218:28;19026:39;;;;39953:4;19026:39;;18817:253;-1:-1;;18817:253;26122:1080;;26346:16;26340:23;26269:4;26383:14;26376:38;26429:67;26269:4;26264:3;26260:14;26477:12;26429:67;;;26586:4;;;41531:10;26586:4;26579:5;26575:16;26569:23;41520:22;26586:4;26648:3;26644:14;28632:36;26754:4;26747:5;26743:16;26737:23;26806:3;26800:4;26796:14;26754:4;26784:3;26780:14;26773:38;26826:109;16703:5;38830:12;39916:6;39911:3;39904:19;26586:4;39948:3;39944:14;16715:88;;26586:4;;16860:6;16856:17;39948:3;16847:27;;26586:4;16946:5;38506:14;-1:-1;16991:10;;16985:341;17010:6;17007:1;17004:13;16985:341;;;17062:20;39948:3;17066:4;17062:20;;17057:3;17050:33;16050:60;16106:3;17117:6;17111:13;16050:60;;;17032:1;17025:9;;;;;17305:14;;;;17131:82;-1:-1;39630:14;;16985:341;;;16989:14;27023:4;27016:5;27012:16;27006:23;26986:43;;27075:3;27069:4;27065:14;27023:4;27053:3;27049:14;27042:38;27095:69;27159:4;27145:12;27095:69;;;27186:11;26242:960;-1:-1;;;;;;;;;26242:960;28794:401;;19237:5;38830:12;19348:52;19393:6;19388:3;19381:4;19374:5;19370:16;19348:52;;;19412:16;;;;18519:37;;;-1:-1;19381:4;29158:12;;28947:248;-1:-1;28947:248;29202:213;41325:42;41314:54;;;;16437:37;;29320:2;29305:18;;29291:124;29422:437;;29628:2;;29617:9;29613:18;29628:2;29649:17;29642:47;29703:146;17690:5;38830:12;39916:6;39911:3;39904:19;39944:14;29617:9;39944:14;17702:112;;39944:14;29628:2;17871:6;17867:17;29617:9;17858:27;;17846:39;;29628:2;17975:5;38506:14;-1:-1;18014:387;18039:6;18036:1;18033:13;18014:387;;;18091:20;29617:9;18095:4;18091:20;;18086:3;18079:33;16264:88;16348:3;18146:6;18140:13;16264:88;;;18160:110;-1:-1;18380:14;;;;39630;;;;18061:1;18054:9;18014:387;;;-1:-1;29695:154;;29599:260;-1:-1;;;;;;;29599:260;29866:539;18519:37;;;41625:4;41614:16;;;;30225:2;30210:18;;28747:35;30308:2;30293:18;;18519:37;30391:2;30376:18;;18519:37;30064:3;30049:19;;30035:370;30412:691;;30642:2;30663:17;30656:47;30717:76;30642:2;30631:9;30627:18;30779:6;30717:76;;;30841:9;30835:4;30831:20;30826:2;30815:9;30811:18;30804:48;30866:76;30937:4;30928:6;30866:76;;;30990:9;30984:4;30980:20;30975:2;30964:9;30960:18;30953:48;31015:78;31088:4;31079:6;31015:78;;;31007:86;30613:490;-1:-1;;;;;;;30613:490;31110:293;;31244:2;31265:17;31258:47;31319:74;31244:2;31233:9;31229:18;31379:6;31319:74;;;31311:82;31215:188;-1:-1;;;31215:188;31410:710;31701:2;31715:47;;;21324:1;31686:18;;;39904:19;21359:66;39944:14;;;21339:87;21445:12;39953:4;31924:18;;31917:48;;;21013:1;21445:12;;;39904:19;21048:7;39944:14;;;21028:28;21075:12;;;31672:448;32127:407;32318:2;32332:47;;;21696:2;32303:18;;;39904:19;21732:15;39944:14;;;21712:36;21767:12;;;32289:245;32541:407;32732:2;32746:47;;;22018:2;32717:18;;;39904:19;22054:16;39944:14;;;22034:37;22090:12;;;32703:245;32955:381;;33133:2;33154:17;33147:47;23287:16;23281:23;23214:4;33133:2;33122:9;33118:18;23317:38;22405:16;22399:23;23205:14;33122:9;23205:14;18519:37;33133:2;22562:5;22558:16;22552:23;22334:4;22595:14;33122:9;22595:14;22588:38;22641:67;22325:14;33122:9;22325:14;22689:12;22641:67;;;22792:4;22785:5;22781:16;22775:23;22755:43;;22834:14;33122:9;22838:4;22834:14;;22818;33122:9;22818:14;22811:38;22864:69;22928:4;22914:12;22864:69;;;22955:11;;;;33133:2;23556:5;23552:16;23546:23;23605:14;;33122:9;23609:4;23605:14;;22792:4;33122:9;23589:14;23582:38;23635:67;23697:4;23683:12;23635:67;;;22792:4;23781:5;23777:16;23771:23;23751:43;;23605:14;33122:9;23834:4;23830:14;;22334:4;33122:9;23814:14;23807:38;23860:67;23922:4;23908:12;23860:67;;;23852:75;;;22334:4;24006:5;24002:16;23996:23;23976:43;;23605:14;33122:9;24059:4;24055:14;;23214:4;33122:9;24039:14;24032:38;;24085:69;24149:4;24135:12;24085:69;;;33200:126;33104:232;-1:-1;;;;;33104:232;33343:453;24620:23;;25941;18519:37;;33581:2;33566:18;;33552:244;33803:377;;33979:2;34000:17;33993:47;25139:16;25133:23;25060:4;33979:2;33968:9;33964:18;25169:38;25222:95;25051:14;33968:9;25051:14;25298:12;25222:95;;;33979:2;25402:5;25398:16;25392:23;25372:43;;25451:14;33968:9;25455:4;25451:14;;25060:4;33968:9;25435:14;25428:38;25481:69;25545:4;25531:12;25481:69;;34187:353;;34351:2;34372:17;34365:47;34426:104;34351:2;34340:9;34336:18;34516:6;34426:104;;34547:213;18519:37;;;34665:2;34650:18;;34636:124;34767:412;;18549:5;18526:3;18519:37;34933:2;35051;35040:9;35036:18;35029:48;35091:78;34933:2;34922:9;34918:18;35155:6;35091:78;;35186:256;35248:2;35242:9;35274:17;;;35349:18;35334:34;;35370:22;;;35331:62;35328:2;;;35406:1;;35396:12;35328:2;35248;35415:22;35226:216;;-1:-1;35226:216;35449:344;;35648:18;35640:6;35637:30;35634:2;;;-1:-1;;35670:12;35634:2;-1:-1;35715:4;35703:17;;;35768:15;;35571:222;41797:268;41862:1;41869:101;41883:6;41880:1;41877:13;41869:101;;;41950:11;;;41944:18;41931:11;;;41924:39;41905:2;41898:10;41869:101;;;41985:6;41982:1;41979:13;41976:2;;;41862:1;42041:6;42036:3;42032:16;42025:27;41976:2;;41846:219;;;;42259:117;41325:42;42346:5;41314:54;42321:5;42318:35;42308:2;;42367:1;;42357:12" - } - } - }, - "sources": { - "AbiGenDummy.sol": { - "id": 0 - } - }, - "sourceCodes": { - "AbiGenDummy.sol": "/*\n\n Copyright 2019 ZeroEx Intl.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n*/\n\npragma experimental ABIEncoderV2;\n\npragma solidity ^0.5.5;\n\n\ncontract AbiGenDummy\n{\n\n uint256 constant internal SOME_CONSTANT = 1234;\n string constant internal REVERT_REASON = \"REVERT_WITH_CONSTANT\";\n string constant internal REQUIRE_REASON = \"REQUIRE_WITH_CONSTANT\";\n\n function simplePureFunction ()\n public\n pure\n returns (uint256 result)\n {\n return 1;\n }\n\n function simplePureFunctionWithInput (uint256 x)\n public\n pure\n returns (uint256 sum)\n {\n return 1 + x;\n }\n\n function pureFunctionWithConstant ()\n public\n pure\n returns (uint256 someConstant)\n {\n return SOME_CONSTANT;\n }\n\n function simpleRevert ()\n public\n pure\n {\n revert(\"SIMPLE_REVERT\");\n }\n\n function revertWithConstant ()\n public\n pure\n {\n revert(REVERT_REASON);\n }\n\n function simpleRequire ()\n public\n pure\n {\n require(0 > 1, \"SIMPLE_REQUIRE\");\n }\n\n function requireWithConstant ()\n public\n pure\n {\n require(0 > 1, REQUIRE_REASON);\n }\n\n /// @dev test that devdocs will be generated and\n /// that multiline devdocs will look okay\n /// @param hash description of some hash. Let's make this line super long to demonstrate hanging indents for method params. It has to be more than one hundred twenty columns.\n /// @param v some v, recovery id\n /// @param r ECDSA r output\n /// @param s ECDSA s output\n /// @return the signerAddress that created this signature. this line too is super long in order to demonstrate the proper hanging indentation in generated code.\n function ecrecoverFn(bytes32 hash, uint8 v, bytes32 r, bytes32 s)\n public\n pure\n returns (address signerAddress)\n {\n bytes memory prefix = \"\\x19Ethereum Signed Message:\\n32\";\n bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash));\n return ecrecover(prefixedHash, v, r, s);\n }\n\n // test: generated code should normalize address inputs to lowercase\n // add extra inputs to make sure it works with address in any position\n function withAddressInput(address x, uint256 a, uint256 b, address y, uint256 c)\n public\n pure\n returns (address z)\n {\n return x;\n }\n\n function acceptsBytes(bytes memory a) public pure {}\n\n /// @dev a method that accepts an array of bytes\n /// @param a the array of bytes being accepted\n function acceptsAnArrayOfBytes(bytes[] memory a) public pure {}\n\n struct Struct {\n bytes someBytes;\n uint32 anInteger;\n bytes[] aDynamicArrayOfBytes;\n string aString;\n }\n\n function structInput(Struct memory s) public pure {}\n\n /// @dev a method that returns a struct\n /// @return a Struct struct\n function structOutput() public pure returns(Struct memory s) {\n bytes[] memory byteArray = new bytes[](2);\n byteArray[0] = \"0x123\";\n byteArray[1] = \"0x321\";\n\n return Struct({\n someBytes: \"0x123\",\n anInteger: 5,\n aDynamicArrayOfBytes: byteArray,\n aString: \"abc\"\n });\n }\n\n function methodReturningArrayOfStructs() public pure returns(Struct[] memory) {}\n function methodAcceptingArrayOfStructs(Struct[] memory) public pure {}\n function methodAcceptingArrayOfArrayOfStructs(Struct[][] memory) public pure {}\n\n struct NestedStruct {\n Struct innerStruct;\n string description;\n }\n\n function nestedStructInput(NestedStruct memory n) public pure {}\n function nestedStructOutput() public pure returns(NestedStruct memory) {}\n\n struct StructNotDirectlyUsedAnywhere {\n uint256 aField;\n }\n\n struct NestedStructWithInnerStructNotUsedElsewhere {\n StructNotDirectlyUsedAnywhere innerStruct;\n }\n\n function methodUsingNestedStructWithInnerStructNotUsedElsewhere()\n public pure returns(NestedStructWithInnerStructNotUsedElsewhere memory)\n {}\n\n uint someState;\n function nonPureMethod() public returns(uint) { return someState += 1; }\n function nonPureMethodThatReturnsNothing() public { someState += 1; }\n\n function methodReturningMultipleValues()\n public pure returns (uint256, string memory)\n {\n return (1, \"hello\");\n }\n\n function overloadedMethod(int a) public pure {}\n function overloadedMethod(string memory a) public pure {}\n\n\n event Withdrawal(address indexed _owner, uint _value);\n\n function withdraw(uint wad) public {\n emit Withdrawal(msg.sender, wad);\n }\n\n event SimpleEvent(bytes someBytes, string someString);\n\n function emitSimpleEvent() public {\n emit SimpleEvent(\n hex'12345678',\n \"lorem\"\n );\n }\n\n // begin tests for `decodeTransactionData`, `decodeReturnData`\n /// @dev complex input is dynamic and more difficult to decode than simple input.\n struct ComplexInput {\n uint256 foo;\n bytes bar;\n string car;\n }\n\n /// @dev complex input is dynamic and more difficult to decode than simple input.\n struct ComplexOutput {\n ComplexInput input;\n bytes lorem;\n bytes ipsum;\n string dolor;\n }\n\n /// @dev Tests decoding when both input and output are empty.\n function noInputNoOutput()\n public\n pure\n {\n // NOP\n require(true == true);\n }\n\n /// @dev Tests decoding when input is empty and output is non-empty.\n function noInputSimpleOutput()\n public\n pure\n returns (uint256)\n {\n return 1991;\n }\n\n /// @dev Tests decoding when input is not empty but output is empty.\n function simpleInputNoOutput(uint256)\n public\n pure\n {\n // NOP\n require(true == true);\n }\n\n /// @dev Tests decoding when both input and output are non-empty.\n function simpleInputSimpleOutput(uint256)\n public\n pure\n returns (uint256)\n {\n return 1991;\n }\n\n /// @dev Tests decoding when the input and output are complex.\n function complexInputComplexOutput(ComplexInput memory complexInput)\n public\n pure\n returns (ComplexOutput memory)\n {\n return ComplexOutput({\n input: complexInput,\n lorem: hex'12345678',\n ipsum: hex'87654321',\n dolor: \"amet\"\n });\n }\n\n /// @dev Tests decoding when the input and output are complex and have more than one argument.\n function multiInputMultiOutput(\n uint256,\n bytes memory,\n string memory\n )\n public\n pure\n returns (\n bytes memory,\n bytes memory,\n string memory\n )\n {\n return (\n hex'12345678',\n hex'87654321',\n \"amet\"\n );\n }\n\n // end tests for `decodeTransactionData`, `decodeReturnData`\n}\n" - }, - "sourceTreeHashHex": "0x7eddc853f5154dd78fdcb2634f515f9e86c0e5ef161f4bc24455e92bb7b874f4", - "compiler": { - "name": "solc", - "version": "soljson-v0.5.16+commit.9c3226ce.js", - "settings": { - "optimizer": { - "enabled": true, - "runs": 1000000, - "details": { - "yul": true, - "deduplicate": true, - "cse": true, - "constantOptimizer": true - } - }, - "outputSelection": { - "*": { - "*": [ - "abi", - "evm.bytecode.object", - "evm.bytecode.sourceMap", - "evm.deployedBytecode.object", - "evm.deployedBytecode.sourceMap", - "devdoc" - ] - } - }, - "evmVersion": "constantinople", - "remappings": [] - } - }, - "chains": {} -} \ No newline at end of file diff --git a/packages/abi-gen/test-cli/fixtures/artifacts/LibDummy.json b/packages/abi-gen/test-cli/fixtures/artifacts/LibDummy.json deleted file mode 100644 index af6f5d5d56..0000000000 --- a/packages/abi-gen/test-cli/fixtures/artifacts/LibDummy.json +++ /dev/null @@ -1,64 +0,0 @@ -{ - "schemaVersion": "2.0.0", - "contractName": "LibDummy", - "compilerOutput": { - "abi": [], - "devdoc": { - "methods": {} - }, - "evm": { - "bytecode": { - "linkReferences": {}, - "object": "0x60556023600b82828239805160001a607314601657fe5b30600052607381538281f3fe73000000000000000000000000000000000000000030146080604052600080fdfea265627a7a72315820725ed7971b4c6a8dad5ee5e2dfb2083612f69a239b2ad69690a85c8e21d5f23864736f6c634300050c0032", - "opcodes": "PUSH1 0x55 PUSH1 0x23 PUSH1 0xB DUP3 DUP3 DUP3 CODECOPY DUP1 MLOAD PUSH1 0x0 BYTE PUSH1 0x73 EQ PUSH1 0x16 JUMPI INVALID JUMPDEST ADDRESS PUSH1 0x0 MSTORE PUSH1 0x73 DUP2 MSTORE8 DUP3 DUP2 RETURN INVALID PUSH20 0x0 ADDRESS EQ PUSH1 0x80 PUSH1 0x40 MSTORE PUSH1 0x0 DUP1 REVERT INVALID LOG2 PUSH6 0x627A7A723158 KECCAK256 PUSH19 0x5ED7971B4C6A8DAD5EE5E2DFB2083612F69A23 SWAP12 0x2a 0xd6 SWAP7 SWAP1 0xa8 0x5c DUP15 0x21 0xd5 CALLCODE CODESIZE PUSH5 0x736F6C6343 STOP SDIV 0xc STOP ORIGIN ", - "sourceMap": "606:385:1:-;;132:2:-1;166:7;155:9;146:7;137:37;255:7;249:14;246:1;241:23;235:4;232:33;222:2;;269:9;222:2;293:9;290:1;283:20;323:4;314:7;306:22;347:7;338;331:24" - }, - "deployedBytecode": { - "linkReferences": {}, - "object": "0x73000000000000000000000000000000000000000030146080604052600080fdfea265627a7a72315820725ed7971b4c6a8dad5ee5e2dfb2083612f69a239b2ad69690a85c8e21d5f23864736f6c634300050c0032", - "opcodes": "PUSH20 0x0 ADDRESS EQ PUSH1 0x80 PUSH1 0x40 MSTORE PUSH1 0x0 DUP1 REVERT INVALID LOG2 PUSH6 0x627A7A723158 KECCAK256 PUSH19 0x5ED7971B4C6A8DAD5EE5E2DFB2083612F69A23 SWAP12 0x2a 0xd6 SWAP7 SWAP1 0xa8 0x5c DUP15 0x21 0xd5 CALLCODE CODESIZE PUSH5 0x736F6C6343 STOP SDIV 0xc STOP ORIGIN ", - "sourceMap": "606:385:1:-;;;;;;;;" - } - } - }, - "sources": { - "LibDummy.sol": { - "id": 1 - } - }, - "sourceCodes": { - "LibDummy.sol": "/*\n\n Copyright 2019 ZeroEx Intl.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n*/\n\npragma solidity ^0.5.5;\n\n\nlibrary LibDummy {\n\n using LibDummy for uint256;\n uint256 constant internal SOME_CONSTANT = 1234;\n\n function addOne (uint256 x)\n internal\n pure\n returns (uint256 sum)\n {\n return x + 1;\n }\n\n function addConstant (uint256 x)\n internal\n pure\n returns (uint256 someConstant)\n {\n return x + SOME_CONSTANT;\n }\n}\n" - }, - "sourceTreeHashHex": "0xd7314c6b96d3195f1d6823802c5a01b0090fe630f4908495ba19d9c298b3ded1", - "compiler": { - "name": "solc", - "version": "soljson-v0.5.12+commit.7709ece9.js", - "settings": { - "optimizer": { - "enabled": true, - "runs": 1000000, - "details": { - "yul": true, - "deduplicate": true, - "cse": true, - "constantOptimizer": true - } - }, - "outputSelection": { - "*": { - "*": [ - "abi", - "evm.bytecode.object", - "evm.bytecode.sourceMap", - "evm.deployedBytecode.object", - "evm.deployedBytecode.sourceMap", - "devdoc" - ] - } - }, - "evmVersion": "constantinople", - "remappings": [] - } - }, - "chains": {} -} \ No newline at end of file diff --git a/packages/abi-gen/test-cli/fixtures/artifacts/TestLibDummy.json b/packages/abi-gen/test-cli/fixtures/artifacts/TestLibDummy.json deleted file mode 100644 index 9edf4668cb..0000000000 --- a/packages/abi-gen/test-cli/fixtures/artifacts/TestLibDummy.json +++ /dev/null @@ -1,111 +0,0 @@ -{ - "schemaVersion": "2.0.0", - "contractName": "TestLibDummy", - "compilerOutput": { - "abi": [ - { - "constant": true, - "inputs": [ - { - "internalType": "uint256", - "name": "x", - "type": "uint256" - } - ], - "name": "publicAddConstant", - "outputs": [ - { - "internalType": "uint256", - "name": "result", - "type": "uint256" - } - ], - "payable": false, - "stateMutability": "pure", - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "internalType": "uint256", - "name": "x", - "type": "uint256" - } - ], - "name": "publicAddOne", - "outputs": [ - { - "internalType": "uint256", - "name": "result", - "type": "uint256" - } - ], - "payable": false, - "stateMutability": "pure", - "type": "function" - } - ], - "devdoc": { - "methods": {} - }, - "evm": { - "bytecode": { - "linkReferences": {}, - "object": "0x608060405234801561001057600080fd5b5060d78061001f6000396000f3fe6080604052348015600f57600080fd5b506004361060325760003560e01c806322935e921460375780632b82fdf0146063575b600080fd5b605160048036036020811015604b57600080fd5b5035607d565b60408051918252519081900360200190f35b605160048036036020811015607757600080fd5b5035608c565b60006086826095565b92915050565b6000608682609c565b6104d20190565b6001019056fea265627a7a72315820863e53f0da474a1275d583d88852313fe053941e79bddd5279abd812b31e020c64736f6c634300050c0032", - "opcodes": "PUSH1 0x80 PUSH1 0x40 MSTORE CALLVALUE DUP1 ISZERO PUSH2 0x10 JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST POP PUSH1 0xD7 DUP1 PUSH2 0x1F PUSH1 0x0 CODECOPY PUSH1 0x0 RETURN INVALID PUSH1 0x80 PUSH1 0x40 MSTORE CALLVALUE DUP1 ISZERO PUSH1 0xF JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST POP PUSH1 0x4 CALLDATASIZE LT PUSH1 0x32 JUMPI PUSH1 0x0 CALLDATALOAD PUSH1 0xE0 SHR DUP1 PUSH4 0x22935E92 EQ PUSH1 0x37 JUMPI DUP1 PUSH4 0x2B82FDF0 EQ PUSH1 0x63 JUMPI JUMPDEST PUSH1 0x0 DUP1 REVERT JUMPDEST PUSH1 0x51 PUSH1 0x4 DUP1 CALLDATASIZE SUB PUSH1 0x20 DUP2 LT ISZERO PUSH1 0x4B JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST POP CALLDATALOAD PUSH1 0x7D JUMP JUMPDEST PUSH1 0x40 DUP1 MLOAD SWAP2 DUP3 MSTORE MLOAD SWAP1 DUP2 SWAP1 SUB PUSH1 0x20 ADD SWAP1 RETURN JUMPDEST PUSH1 0x51 PUSH1 0x4 DUP1 CALLDATASIZE SUB PUSH1 0x20 DUP2 LT ISZERO PUSH1 0x77 JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST POP CALLDATALOAD PUSH1 0x8C JUMP JUMPDEST PUSH1 0x0 PUSH1 0x86 DUP3 PUSH1 0x95 JUMP JUMPDEST SWAP3 SWAP2 POP POP JUMP JUMPDEST PUSH1 0x0 PUSH1 0x86 DUP3 PUSH1 0x9C JUMP JUMPDEST PUSH2 0x4D2 ADD SWAP1 JUMP JUMPDEST PUSH1 0x1 ADD SWAP1 JUMP INVALID LOG2 PUSH6 0x627A7A723158 KECCAK256 DUP7 RETURNDATACOPY MSTORE8 CREATE 0xda SELFBALANCE 0x4a SLT PUSH22 0xD583D88852313FE053941E79BDDD5279ABD812B31E02 0xc PUSH5 0x736F6C6343 STOP SDIV 0xc STOP ORIGIN ", - "sourceMap": "632:346:2:-;;;;8:9:-1;5:2;;;30:1;27;20:12;5:2;632:346:2;;;;;;;" - }, - "deployedBytecode": { - "linkReferences": {}, - "object": "0x6080604052348015600f57600080fd5b506004361060325760003560e01c806322935e921460375780632b82fdf0146063575b600080fd5b605160048036036020811015604b57600080fd5b5035607d565b60408051918252519081900360200190f35b605160048036036020811015607757600080fd5b5035608c565b60006086826095565b92915050565b6000608682609c565b6104d20190565b6001019056fea265627a7a72315820863e53f0da474a1275d583d88852313fe053941e79bddd5279abd812b31e020c64736f6c634300050c0032", - "opcodes": "PUSH1 0x80 PUSH1 0x40 MSTORE CALLVALUE DUP1 ISZERO PUSH1 0xF JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST POP PUSH1 0x4 CALLDATASIZE LT PUSH1 0x32 JUMPI PUSH1 0x0 CALLDATALOAD PUSH1 0xE0 SHR DUP1 PUSH4 0x22935E92 EQ PUSH1 0x37 JUMPI DUP1 PUSH4 0x2B82FDF0 EQ PUSH1 0x63 JUMPI JUMPDEST PUSH1 0x0 DUP1 REVERT JUMPDEST PUSH1 0x51 PUSH1 0x4 DUP1 CALLDATASIZE SUB PUSH1 0x20 DUP2 LT ISZERO PUSH1 0x4B JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST POP CALLDATALOAD PUSH1 0x7D JUMP JUMPDEST PUSH1 0x40 DUP1 MLOAD SWAP2 DUP3 MSTORE MLOAD SWAP1 DUP2 SWAP1 SUB PUSH1 0x20 ADD SWAP1 RETURN JUMPDEST PUSH1 0x51 PUSH1 0x4 DUP1 CALLDATASIZE SUB PUSH1 0x20 DUP2 LT ISZERO PUSH1 0x77 JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST POP CALLDATALOAD PUSH1 0x8C JUMP JUMPDEST PUSH1 0x0 PUSH1 0x86 DUP3 PUSH1 0x95 JUMP JUMPDEST SWAP3 SWAP2 POP POP JUMP JUMPDEST PUSH1 0x0 PUSH1 0x86 DUP3 PUSH1 0x9C JUMP JUMPDEST PUSH2 0x4D2 ADD SWAP1 JUMP JUMPDEST PUSH1 0x1 ADD SWAP1 JUMP INVALID LOG2 PUSH6 0x627A7A723158 KECCAK256 DUP7 RETURNDATACOPY MSTORE8 CREATE 0xda SELFBALANCE 0x4a SLT PUSH22 0xD583D88852313FE053941E79BDDD5279ABD812B31E02 0xc PUSH5 0x736F6C6343 STOP SDIV 0xc STOP ORIGIN ", - "sourceMap": "632:346:2:-;;;;8:9:-1;5:2;;;30:1;27;20:12;5:2;632:346:2;;;;;;;;;;;;;;;;;;;;;;;;833:143;;;;;;13:2:-1;8:3;5:11;2:2;;;29:1;26;19:12;2:2;-1:-1;833:143:2;;:::i;:::-;;;;;;;;;;;;;;;;694:133;;;;;;13:2:-1;8:3;5:11;2:2;;;29:1;26;19:12;2:2;-1:-1;694:133:2;;:::i;833:143::-;917:14;954:15;:1;:13;:15::i;:::-;947:22;833:143;-1:-1:-1;;833:143:2:o;694:133::-;773:14;810:10;:1;:8;:10::i;842:147:1:-;704:4;965:17;;842:147::o;715:121::-;828:1;824:5;;715:121::o" - } - } - }, - "sources": { - "TestLibDummy.sol": { - "id": 2 - }, - "LibDummy.sol": { - "id": 1 - } - }, - "sourceCodes": { - "TestLibDummy.sol": "/*\n\n Copyright 2019 ZeroEx Intl.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n*/\n\npragma solidity ^0.5.5;\n\nimport \"./LibDummy.sol\";\n\n\ncontract TestLibDummy {\n\n using LibDummy for uint256;\n\n function publicAddOne (uint256 x)\n public\n pure\n returns (uint256 result)\n {\n return x.addOne();\n }\n\n function publicAddConstant (uint256 x)\n public\n pure\n returns (uint256 result)\n {\n return x.addConstant();\n }\n}\n", - "LibDummy.sol": "/*\n\n Copyright 2019 ZeroEx Intl.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n*/\n\npragma solidity ^0.5.5;\n\n\nlibrary LibDummy {\n\n using LibDummy for uint256;\n uint256 constant internal SOME_CONSTANT = 1234;\n\n function addOne (uint256 x)\n internal\n pure\n returns (uint256 sum)\n {\n return x + 1;\n }\n\n function addConstant (uint256 x)\n internal\n pure\n returns (uint256 someConstant)\n {\n return x + SOME_CONSTANT;\n }\n}\n" - }, - "sourceTreeHashHex": "0xd7efa9dfeb2bbdec2bead8b892d1288c1398b34216d26c6a48bffb25c692bbc0", - "compiler": { - "name": "solc", - "version": "soljson-v0.5.12+commit.7709ece9.js", - "settings": { - "optimizer": { - "enabled": true, - "runs": 1000000, - "details": { - "yul": true, - "deduplicate": true, - "cse": true, - "constantOptimizer": true - } - }, - "outputSelection": { - "*": { - "*": [ - "abi", - "evm.bytecode.object", - "evm.bytecode.sourceMap", - "evm.deployedBytecode.object", - "evm.deployedBytecode.sourceMap", - "devdoc" - ] - } - }, - "evmVersion": "constantinople", - "remappings": [] - } - }, - "chains": {} -} \ No newline at end of file diff --git a/packages/abi-gen/test-cli/fixtures/contracts/AbiGenDummy.sol b/packages/abi-gen/test-cli/fixtures/contracts/AbiGenDummy.sol deleted file mode 100644 index 20f897023a..0000000000 --- a/packages/abi-gen/test-cli/fixtures/contracts/AbiGenDummy.sol +++ /dev/null @@ -1,281 +0,0 @@ -/* - - Copyright 2019 ZeroEx Intl. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -pragma experimental ABIEncoderV2; - -pragma solidity ^0.5.5; - - -contract AbiGenDummy -{ - - uint256 constant internal SOME_CONSTANT = 1234; - string constant internal REVERT_REASON = "REVERT_WITH_CONSTANT"; - string constant internal REQUIRE_REASON = "REQUIRE_WITH_CONSTANT"; - - function simplePureFunction () - public - pure - returns (uint256 result) - { - return 1; - } - - function simplePureFunctionWithInput (uint256 x) - public - pure - returns (uint256 sum) - { - return 1 + x; - } - - function pureFunctionWithConstant () - public - pure - returns (uint256 someConstant) - { - return SOME_CONSTANT; - } - - function simpleRevert () - public - pure - { - revert("SIMPLE_REVERT"); - } - - function revertWithConstant () - public - pure - { - revert(REVERT_REASON); - } - - function simpleRequire () - public - pure - { - require(0 > 1, "SIMPLE_REQUIRE"); - } - - function requireWithConstant () - public - pure - { - require(0 > 1, REQUIRE_REASON); - } - - /// @dev test that devdocs will be generated and - /// that multiline devdocs will look okay - /// @param hash description of some hash. Let's make this line super long to demonstrate hanging indents for method params. It has to be more than one hundred twenty columns. - /// @param v some v, recovery id - /// @param r ECDSA r output - /// @param s ECDSA s output - /// @return the signerAddress that created this signature. this line too is super long in order to demonstrate the proper hanging indentation in generated code. - function ecrecoverFn(bytes32 hash, uint8 v, bytes32 r, bytes32 s) - public - pure - returns (address signerAddress) - { - bytes memory prefix = "\x19Ethereum Signed Message:\n32"; - bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash)); - return ecrecover(prefixedHash, v, r, s); - } - - // test: generated code should normalize address inputs to lowercase - // add extra inputs to make sure it works with address in any position - function withAddressInput(address x, uint256 a, uint256 b, address y, uint256 c) - public - pure - returns (address z) - { - return x; - } - - function acceptsBytes(bytes memory a) public pure {} - - /// @dev a method that accepts an array of bytes - /// @param a the array of bytes being accepted - function acceptsAnArrayOfBytes(bytes[] memory a) public pure {} - - struct Struct { - bytes someBytes; - uint32 anInteger; - bytes[] aDynamicArrayOfBytes; - string aString; - } - - function structInput(Struct memory s) public pure {} - - /// @dev a method that returns a struct - /// @return a Struct struct - function structOutput() public pure returns(Struct memory s) { - bytes[] memory byteArray = new bytes[](2); - byteArray[0] = "0x123"; - byteArray[1] = "0x321"; - - return Struct({ - someBytes: "0x123", - anInteger: 5, - aDynamicArrayOfBytes: byteArray, - aString: "abc" - }); - } - - function methodReturningArrayOfStructs() public pure returns(Struct[] memory) {} - function methodAcceptingArrayOfStructs(Struct[] memory) public pure {} - function methodAcceptingArrayOfArrayOfStructs(Struct[][] memory) public pure {} - - struct NestedStruct { - Struct innerStruct; - string description; - } - - function nestedStructInput(NestedStruct memory n) public pure {} - function nestedStructOutput() public pure returns(NestedStruct memory) {} - - struct StructNotDirectlyUsedAnywhere { - uint256 aField; - } - - struct NestedStructWithInnerStructNotUsedElsewhere { - StructNotDirectlyUsedAnywhere innerStruct; - } - - function methodUsingNestedStructWithInnerStructNotUsedElsewhere() - public pure returns(NestedStructWithInnerStructNotUsedElsewhere memory) - {} - - uint someState; - function nonPureMethod() public returns(uint) { return someState += 1; } - function nonPureMethodThatReturnsNothing() public { someState += 1; } - - function methodReturningMultipleValues() - public pure returns (uint256, string memory) - { - return (1, "hello"); - } - - function overloadedMethod(int a) public pure {} - function overloadedMethod(string memory a) public pure {} - - - event Withdrawal(address indexed _owner, uint _value); - - function withdraw(uint wad) public { - emit Withdrawal(msg.sender, wad); - } - - event SimpleEvent(bytes someBytes, string someString); - - function emitSimpleEvent() public { - emit SimpleEvent( - hex'12345678', - "lorem" - ); - } - - // begin tests for `decodeTransactionData`, `decodeReturnData` - /// @dev complex input is dynamic and more difficult to decode than simple input. - struct ComplexInput { - uint256 foo; - bytes bar; - string car; - } - - /// @dev complex input is dynamic and more difficult to decode than simple input. - struct ComplexOutput { - ComplexInput input; - bytes lorem; - bytes ipsum; - string dolor; - } - - /// @dev Tests decoding when both input and output are empty. - function noInputNoOutput() - public - pure - { - // NOP - require(true == true); - } - - /// @dev Tests decoding when input is empty and output is non-empty. - function noInputSimpleOutput() - public - pure - returns (uint256) - { - return 1991; - } - - /// @dev Tests decoding when input is not empty but output is empty. - function simpleInputNoOutput(uint256) - public - pure - { - // NOP - require(true == true); - } - - /// @dev Tests decoding when both input and output are non-empty. - function simpleInputSimpleOutput(uint256) - public - pure - returns (uint256) - { - return 1991; - } - - /// @dev Tests decoding when the input and output are complex. - function complexInputComplexOutput(ComplexInput memory complexInput) - public - pure - returns (ComplexOutput memory) - { - return ComplexOutput({ - input: complexInput, - lorem: hex'12345678', - ipsum: hex'87654321', - dolor: "amet" - }); - } - - /// @dev Tests decoding when the input and output are complex and have more than one argument. - function multiInputMultiOutput( - uint256, - bytes memory, - string memory - ) - public - pure - returns ( - bytes memory, - bytes memory, - string memory - ) - { - return ( - hex'12345678', - hex'87654321', - "amet" - ); - } - - // end tests for `decodeTransactionData`, `decodeReturnData` -} diff --git a/packages/abi-gen/test-cli/fixtures/contracts/LibDummy.sol b/packages/abi-gen/test-cli/fixtures/contracts/LibDummy.sol deleted file mode 100644 index 8c732daa39..0000000000 --- a/packages/abi-gen/test-cli/fixtures/contracts/LibDummy.sol +++ /dev/null @@ -1,42 +0,0 @@ -/* - - Copyright 2019 ZeroEx Intl. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -pragma solidity ^0.5.5; - - -library LibDummy { - - using LibDummy for uint256; - uint256 constant internal SOME_CONSTANT = 1234; - - function addOne (uint256 x) - internal - pure - returns (uint256 sum) - { - return x + 1; - } - - function addConstant (uint256 x) - internal - pure - returns (uint256 someConstant) - { - return x + SOME_CONSTANT; - } -} diff --git a/packages/abi-gen/test-cli/fixtures/contracts/TestLibDummy.sol b/packages/abi-gen/test-cli/fixtures/contracts/TestLibDummy.sol deleted file mode 100644 index 4409650729..0000000000 --- a/packages/abi-gen/test-cli/fixtures/contracts/TestLibDummy.sol +++ /dev/null @@ -1,43 +0,0 @@ -/* - - Copyright 2019 ZeroEx Intl. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -pragma solidity ^0.5.5; - -import "./LibDummy.sol"; - - -contract TestLibDummy { - - using LibDummy for uint256; - - function publicAddOne (uint256 x) - public - pure - returns (uint256 result) - { - return x.addOne(); - } - - function publicAddConstant (uint256 x) - public - pure - returns (uint256 result) - { - return x.addConstant(); - } -} diff --git a/packages/abi-gen/test-cli/fixtures/pylintrc b/packages/abi-gen/test-cli/fixtures/pylintrc deleted file mode 100644 index 0bad5f64e8..0000000000 --- a/packages/abi-gen/test-cli/fixtures/pylintrc +++ /dev/null @@ -1,7 +0,0 @@ -[MESSAGES CONTROL] -disable=C0330,line-too-long,fixme,too-few-public-methods,too-many-ancestors,duplicate-code,blacklisted-name -# C0330 is "bad hanging indent". we use indents per `black`. - -[BASIC] -argument-rgx=[a-z_][a-z0-9_]{0,31}$ -# above differs from the default only in that it allows 2-character names diff --git a/packages/abi-gen/test-cli/fixtures/python-requirements.txt b/packages/abi-gen/test-cli/fixtures/python-requirements.txt deleted file mode 100644 index 60cebd9185..0000000000 --- a/packages/abi-gen/test-cli/fixtures/python-requirements.txt +++ /dev/null @@ -1,8 +0,0 @@ -black -eth_utils -hexbytes -mypy -mypy_extensions -pylint -web3 -../../python-packages/contract_wrappers diff --git a/packages/abi-gen/test-cli/output/python/abi_gen_dummy/__init__.py b/packages/abi-gen/test-cli/output/python/abi_gen_dummy/__init__.py deleted file mode 100644 index f047e399a6..0000000000 --- a/packages/abi-gen/test-cli/output/python/abi_gen_dummy/__init__.py +++ /dev/null @@ -1,2081 +0,0 @@ -"""Generated wrapper for AbiGenDummy Solidity contract.""" - -# pylint: disable=too-many-arguments - -import json -from typing import ( # pylint: disable=unused-import - Any, - List, - Optional, - Tuple, - Union, -) - -from eth_utils import to_checksum_address -from mypy_extensions import TypedDict # pylint: disable=unused-import -from hexbytes import HexBytes -from web3 import Web3 -from web3.contract import ContractFunction -from web3.datastructures import AttributeDict -from web3.providers.base import BaseProvider - -from zero_ex.contract_wrappers.bases import ContractMethod, Validator -from zero_ex.contract_wrappers.tx_params import TxParams - - -# Try to import a custom validator class definition; if there isn't one, -# declare one that we can instantiate for the default argument to the -# constructor for AbiGenDummy below. -try: - # both mypy and pylint complain about what we're doing here, but this - # works just fine, so their messages have been disabled here. - from . import ( # type: ignore # pylint: disable=import-self - AbiGenDummyValidator, - ) -except ImportError: - - class AbiGenDummyValidator( # type: ignore - Validator - ): - """No-op input validator.""" - - -try: - from .middleware import MIDDLEWARE # type: ignore -except ImportError: - pass - - -class AbiGenDummyComplexInput(TypedDict): - """Python representation of a tuple or struct. - - Solidity compiler output does not include the names of structs that appear - in method definitions. A tuple found in an ABI may have been written in - Solidity as a literal, anonymous tuple, or it may have been written as a - named `struct`:code:, but there is no way to tell from the compiler - output. This class represents a tuple that appeared in a method - definition. Its name is derived from a hash of that tuple's field names, - and every method whose ABI refers to a tuple with that same list of field - names will have a generated wrapper method that refers to this class. - - Any members of type `bytes`:code: should be encoded as UTF-8, which can be - accomplished via `str.encode("utf_8")`:code: - """ - - foo: int - - bar: Union[bytes, str] - - car: str - - -class AbiGenDummyComplexOutput(TypedDict): - """Python representation of a tuple or struct. - - Solidity compiler output does not include the names of structs that appear - in method definitions. A tuple found in an ABI may have been written in - Solidity as a literal, anonymous tuple, or it may have been written as a - named `struct`:code:, but there is no way to tell from the compiler - output. This class represents a tuple that appeared in a method - definition. Its name is derived from a hash of that tuple's field names, - and every method whose ABI refers to a tuple with that same list of field - names will have a generated wrapper method that refers to this class. - - Any members of type `bytes`:code: should be encoded as UTF-8, which can be - accomplished via `str.encode("utf_8")`:code: - """ - - input: AbiGenDummyComplexInput - - lorem: Union[bytes, str] - - ipsum: Union[bytes, str] - - dolor: str - - -class AbiGenDummyStructNotDirectlyUsedAnywhere(TypedDict): - """Python representation of a tuple or struct. - - Solidity compiler output does not include the names of structs that appear - in method definitions. A tuple found in an ABI may have been written in - Solidity as a literal, anonymous tuple, or it may have been written as a - named `struct`:code:, but there is no way to tell from the compiler - output. This class represents a tuple that appeared in a method - definition. Its name is derived from a hash of that tuple's field names, - and every method whose ABI refers to a tuple with that same list of field - names will have a generated wrapper method that refers to this class. - - Any members of type `bytes`:code: should be encoded as UTF-8, which can be - accomplished via `str.encode("utf_8")`:code: - """ - - aField: int - - -class AbiGenDummyNestedStructWithInnerStructNotUsedElsewhere(TypedDict): - """Python representation of a tuple or struct. - - Solidity compiler output does not include the names of structs that appear - in method definitions. A tuple found in an ABI may have been written in - Solidity as a literal, anonymous tuple, or it may have been written as a - named `struct`:code:, but there is no way to tell from the compiler - output. This class represents a tuple that appeared in a method - definition. Its name is derived from a hash of that tuple's field names, - and every method whose ABI refers to a tuple with that same list of field - names will have a generated wrapper method that refers to this class. - - Any members of type `bytes`:code: should be encoded as UTF-8, which can be - accomplished via `str.encode("utf_8")`:code: - """ - - innerStruct: AbiGenDummyStructNotDirectlyUsedAnywhere - - -class AbiGenDummyStruct(TypedDict): - """Python representation of a tuple or struct. - - Solidity compiler output does not include the names of structs that appear - in method definitions. A tuple found in an ABI may have been written in - Solidity as a literal, anonymous tuple, or it may have been written as a - named `struct`:code:, but there is no way to tell from the compiler - output. This class represents a tuple that appeared in a method - definition. Its name is derived from a hash of that tuple's field names, - and every method whose ABI refers to a tuple with that same list of field - names will have a generated wrapper method that refers to this class. - - Any members of type `bytes`:code: should be encoded as UTF-8, which can be - accomplished via `str.encode("utf_8")`:code: - """ - - someBytes: Union[bytes, str] - - anInteger: int - - aDynamicArrayOfBytes: List[Union[bytes, str]] - - aString: str - - -class AbiGenDummyNestedStruct(TypedDict): - """Python representation of a tuple or struct. - - Solidity compiler output does not include the names of structs that appear - in method definitions. A tuple found in an ABI may have been written in - Solidity as a literal, anonymous tuple, or it may have been written as a - named `struct`:code:, but there is no way to tell from the compiler - output. This class represents a tuple that appeared in a method - definition. Its name is derived from a hash of that tuple's field names, - and every method whose ABI refers to a tuple with that same list of field - names will have a generated wrapper method that refers to this class. - - Any members of type `bytes`:code: should be encoded as UTF-8, which can be - accomplished via `str.encode("utf_8")`:code: - """ - - innerStruct: AbiGenDummyStruct - - description: str - - -class AcceptsAnArrayOfBytesMethod( - ContractMethod -): # pylint: disable=invalid-name - """Various interfaces to the acceptsAnArrayOfBytes method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - validator: Validator = None, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address, validator) - self._underlying_method = contract_function - - def validate_and_normalize_inputs(self, a: List[Union[bytes, str]]): - """Validate the inputs to the acceptsAnArrayOfBytes method.""" - self.validator.assert_valid( - method_name="acceptsAnArrayOfBytes", - parameter_name="a", - argument_value=a, - ) - return a - - def call( - self, a: List[Union[bytes, str]], tx_params: Optional[TxParams] = None - ) -> None: - """Execute underlying contract method via eth_call. - - a method that accepts an array of bytes - - :param a: the array of bytes being accepted - :param tx_params: transaction parameters - - """ - (a) = self.validate_and_normalize_inputs(a) - tx_params = super().normalize_tx_params(tx_params) - self._underlying_method(a).call(tx_params.as_dict()) - - def estimate_gas( - self, a: List[Union[bytes, str]], tx_params: Optional[TxParams] = None - ) -> int: - """Estimate gas consumption of method call.""" - (a) = self.validate_and_normalize_inputs(a) - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method(a).estimateGas(tx_params.as_dict()) - - -class AcceptsBytesMethod(ContractMethod): # pylint: disable=invalid-name - """Various interfaces to the acceptsBytes method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - validator: Validator = None, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address, validator) - self._underlying_method = contract_function - - def validate_and_normalize_inputs(self, a: Union[bytes, str]): - """Validate the inputs to the acceptsBytes method.""" - self.validator.assert_valid( - method_name="acceptsBytes", parameter_name="a", argument_value=a, - ) - return a - - def call( - self, a: Union[bytes, str], tx_params: Optional[TxParams] = None - ) -> None: - """Execute underlying contract method via eth_call. - - :param tx_params: transaction parameters - - """ - (a) = self.validate_and_normalize_inputs(a) - tx_params = super().normalize_tx_params(tx_params) - self._underlying_method(a).call(tx_params.as_dict()) - - def estimate_gas( - self, a: Union[bytes, str], tx_params: Optional[TxParams] = None - ) -> int: - """Estimate gas consumption of method call.""" - (a) = self.validate_and_normalize_inputs(a) - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method(a).estimateGas(tx_params.as_dict()) - - -class ComplexInputComplexOutputMethod( - ContractMethod -): # pylint: disable=invalid-name - """Various interfaces to the complexInputComplexOutput method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - validator: Validator = None, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address, validator) - self._underlying_method = contract_function - - def validate_and_normalize_inputs( - self, complex_input: AbiGenDummyComplexInput - ): - """Validate the inputs to the complexInputComplexOutput method.""" - self.validator.assert_valid( - method_name="complexInputComplexOutput", - parameter_name="complexInput", - argument_value=complex_input, - ) - return complex_input - - def call( - self, - complex_input: AbiGenDummyComplexInput, - tx_params: Optional[TxParams] = None, - ) -> AbiGenDummyComplexOutput: - """Execute underlying contract method via eth_call. - - Tests decoding when the input and output are complex. - - :param tx_params: transaction parameters - - """ - (complex_input) = self.validate_and_normalize_inputs(complex_input) - tx_params = super().normalize_tx_params(tx_params) - returned = self._underlying_method(complex_input).call( - tx_params.as_dict() - ) - return AbiGenDummyComplexOutput( - input=returned[0], - lorem=returned[1], - ipsum=returned[2], - dolor=returned[3], - ) - - def estimate_gas( - self, - complex_input: AbiGenDummyComplexInput, - tx_params: Optional[TxParams] = None, - ) -> int: - """Estimate gas consumption of method call.""" - (complex_input) = self.validate_and_normalize_inputs(complex_input) - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method(complex_input).estimateGas( - tx_params.as_dict() - ) - - -class EcrecoverFnMethod(ContractMethod): # pylint: disable=invalid-name - """Various interfaces to the ecrecoverFn method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - validator: Validator = None, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address, validator) - self._underlying_method = contract_function - - def validate_and_normalize_inputs( - self, - _hash: Union[bytes, str], - v: int, - r: Union[bytes, str], - s: Union[bytes, str], - ): - """Validate the inputs to the ecrecoverFn method.""" - self.validator.assert_valid( - method_name="ecrecoverFn", - parameter_name="hash", - argument_value=_hash, - ) - self.validator.assert_valid( - method_name="ecrecoverFn", parameter_name="v", argument_value=v, - ) - self.validator.assert_valid( - method_name="ecrecoverFn", parameter_name="r", argument_value=r, - ) - self.validator.assert_valid( - method_name="ecrecoverFn", parameter_name="s", argument_value=s, - ) - return (_hash, v, r, s) - - def call( - self, - _hash: Union[bytes, str], - v: int, - r: Union[bytes, str], - s: Union[bytes, str], - tx_params: Optional[TxParams] = None, - ) -> str: - """Execute underlying contract method via eth_call. - - test that devdocs will be generated and that multiline devdocs will - look okay - - :param hash: description of some hash. Let's make this line super long - to demonstrate hanging indents for method params. It has to be more - than one hundred twenty columns. - :param r: ECDSA r output - :param s: ECDSA s output - :param v: some v, recovery id - :param tx_params: transaction parameters - :returns: the signerAddress that created this signature. this line too - is super long in order to demonstrate the proper hanging - indentation in generated code. - """ - (_hash, v, r, s) = self.validate_and_normalize_inputs(_hash, v, r, s) - tx_params = super().normalize_tx_params(tx_params) - returned = self._underlying_method(_hash, v, r, s).call( - tx_params.as_dict() - ) - return str(returned) - - def estimate_gas( - self, - _hash: Union[bytes, str], - v: int, - r: Union[bytes, str], - s: Union[bytes, str], - tx_params: Optional[TxParams] = None, - ) -> int: - """Estimate gas consumption of method call.""" - (_hash, v, r, s) = self.validate_and_normalize_inputs(_hash, v, r, s) - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method(_hash, v, r, s).estimateGas( - tx_params.as_dict() - ) - - -class EmitSimpleEventMethod(ContractMethod): # pylint: disable=invalid-name - """Various interfaces to the emitSimpleEvent method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address) - self._underlying_method = contract_function - - def call(self, tx_params: Optional[TxParams] = None) -> None: - """Execute underlying contract method via eth_call. - - :param tx_params: transaction parameters - :returns: the return value of the underlying method. - """ - tx_params = super().normalize_tx_params(tx_params) - self._underlying_method().call(tx_params.as_dict()) - - def send_transaction( - self, tx_params: Optional[TxParams] = None - ) -> Union[HexBytes, bytes]: - """Execute underlying contract method via eth_sendTransaction. - - :param tx_params: transaction parameters - """ - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method().transact(tx_params.as_dict()) - - def build_transaction(self, tx_params: Optional[TxParams] = None) -> dict: - """Construct calldata to be used as input to the method.""" - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method().buildTransaction(tx_params.as_dict()) - - def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int: - """Estimate gas consumption of method call.""" - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method().estimateGas(tx_params.as_dict()) - - -class MethodAcceptingArrayOfArrayOfStructsMethod( - ContractMethod -): # pylint: disable=invalid-name - """Various interfaces to the methodAcceptingArrayOfArrayOfStructs method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - validator: Validator = None, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address, validator) - self._underlying_method = contract_function - - def validate_and_normalize_inputs( - self, index_0: List[List[AbiGenDummyStruct]] - ): - """Validate the inputs to the methodAcceptingArrayOfArrayOfStructs method.""" - self.validator.assert_valid( - method_name="methodAcceptingArrayOfArrayOfStructs", - parameter_name="index_0", - argument_value=index_0, - ) - return index_0 - - def call( - self, - index_0: List[List[AbiGenDummyStruct]], - tx_params: Optional[TxParams] = None, - ) -> None: - """Execute underlying contract method via eth_call. - - :param tx_params: transaction parameters - - """ - (index_0) = self.validate_and_normalize_inputs(index_0) - tx_params = super().normalize_tx_params(tx_params) - self._underlying_method(index_0).call(tx_params.as_dict()) - - def estimate_gas( - self, - index_0: List[List[AbiGenDummyStruct]], - tx_params: Optional[TxParams] = None, - ) -> int: - """Estimate gas consumption of method call.""" - (index_0) = self.validate_and_normalize_inputs(index_0) - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method(index_0).estimateGas( - tx_params.as_dict() - ) - - -class MethodAcceptingArrayOfStructsMethod( - ContractMethod -): # pylint: disable=invalid-name - """Various interfaces to the methodAcceptingArrayOfStructs method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - validator: Validator = None, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address, validator) - self._underlying_method = contract_function - - def validate_and_normalize_inputs(self, index_0: List[AbiGenDummyStruct]): - """Validate the inputs to the methodAcceptingArrayOfStructs method.""" - self.validator.assert_valid( - method_name="methodAcceptingArrayOfStructs", - parameter_name="index_0", - argument_value=index_0, - ) - return index_0 - - def call( - self, - index_0: List[AbiGenDummyStruct], - tx_params: Optional[TxParams] = None, - ) -> None: - """Execute underlying contract method via eth_call. - - :param tx_params: transaction parameters - - """ - (index_0) = self.validate_and_normalize_inputs(index_0) - tx_params = super().normalize_tx_params(tx_params) - self._underlying_method(index_0).call(tx_params.as_dict()) - - def estimate_gas( - self, - index_0: List[AbiGenDummyStruct], - tx_params: Optional[TxParams] = None, - ) -> int: - """Estimate gas consumption of method call.""" - (index_0) = self.validate_and_normalize_inputs(index_0) - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method(index_0).estimateGas( - tx_params.as_dict() - ) - - -class MethodReturningArrayOfStructsMethod( - ContractMethod -): # pylint: disable=invalid-name - """Various interfaces to the methodReturningArrayOfStructs method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address) - self._underlying_method = contract_function - - def call( - self, tx_params: Optional[TxParams] = None - ) -> List[AbiGenDummyStruct]: - """Execute underlying contract method via eth_call. - - :param tx_params: transaction parameters - - """ - tx_params = super().normalize_tx_params(tx_params) - returned = self._underlying_method().call(tx_params.as_dict()) - return [ - AbiGenDummyStruct( - someBytes=element[0], - anInteger=element[1], - aDynamicArrayOfBytes=element[2], - aString=element[3], - ) - for element in returned - ] - - def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int: - """Estimate gas consumption of method call.""" - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method().estimateGas(tx_params.as_dict()) - - -class MethodReturningMultipleValuesMethod( - ContractMethod -): # pylint: disable=invalid-name - """Various interfaces to the methodReturningMultipleValues method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address) - self._underlying_method = contract_function - - def call(self, tx_params: Optional[TxParams] = None) -> Tuple[int, str]: - """Execute underlying contract method via eth_call. - - :param tx_params: transaction parameters - - """ - tx_params = super().normalize_tx_params(tx_params) - returned = self._underlying_method().call(tx_params.as_dict()) - return ( - returned[0], - returned[1], - ) - - def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int: - """Estimate gas consumption of method call.""" - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method().estimateGas(tx_params.as_dict()) - - -class MethodUsingNestedStructWithInnerStructNotUsedElsewhereMethod( - ContractMethod -): # pylint: disable=invalid-name - """Various interfaces to the methodUsingNestedStructWithInnerStructNotUsedElsewhere method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address) - self._underlying_method = contract_function - - def call( - self, tx_params: Optional[TxParams] = None - ) -> AbiGenDummyNestedStructWithInnerStructNotUsedElsewhere: - """Execute underlying contract method via eth_call. - - :param tx_params: transaction parameters - - """ - tx_params = super().normalize_tx_params(tx_params) - returned = self._underlying_method().call(tx_params.as_dict()) - return AbiGenDummyNestedStructWithInnerStructNotUsedElsewhere( - innerStruct=returned[0], - ) - - def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int: - """Estimate gas consumption of method call.""" - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method().estimateGas(tx_params.as_dict()) - - -class MultiInputMultiOutputMethod( - ContractMethod -): # pylint: disable=invalid-name - """Various interfaces to the multiInputMultiOutput method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - validator: Validator = None, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address, validator) - self._underlying_method = contract_function - - def validate_and_normalize_inputs( - self, index_0: int, index_1: Union[bytes, str], index_2: str - ): - """Validate the inputs to the multiInputMultiOutput method.""" - self.validator.assert_valid( - method_name="multiInputMultiOutput", - parameter_name="index_0", - argument_value=index_0, - ) - # safeguard against fractional inputs - index_0 = int(index_0) - self.validator.assert_valid( - method_name="multiInputMultiOutput", - parameter_name="index_1", - argument_value=index_1, - ) - self.validator.assert_valid( - method_name="multiInputMultiOutput", - parameter_name="index_2", - argument_value=index_2, - ) - return (index_0, index_1, index_2) - - def call( - self, - index_0: int, - index_1: Union[bytes, str], - index_2: str, - tx_params: Optional[TxParams] = None, - ) -> Tuple[Union[bytes, str], Union[bytes, str], str]: - """Execute underlying contract method via eth_call. - - Tests decoding when the input and output are complex and have more than - one argument. - - :param tx_params: transaction parameters - - """ - (index_0, index_1, index_2) = self.validate_and_normalize_inputs( - index_0, index_1, index_2 - ) - tx_params = super().normalize_tx_params(tx_params) - returned = self._underlying_method(index_0, index_1, index_2).call( - tx_params.as_dict() - ) - return ( - returned[0], - returned[1], - returned[2], - ) - - def estimate_gas( - self, - index_0: int, - index_1: Union[bytes, str], - index_2: str, - tx_params: Optional[TxParams] = None, - ) -> int: - """Estimate gas consumption of method call.""" - (index_0, index_1, index_2) = self.validate_and_normalize_inputs( - index_0, index_1, index_2 - ) - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method(index_0, index_1, index_2).estimateGas( - tx_params.as_dict() - ) - - -class NestedStructInputMethod(ContractMethod): # pylint: disable=invalid-name - """Various interfaces to the nestedStructInput method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - validator: Validator = None, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address, validator) - self._underlying_method = contract_function - - def validate_and_normalize_inputs(self, n: AbiGenDummyNestedStruct): - """Validate the inputs to the nestedStructInput method.""" - self.validator.assert_valid( - method_name="nestedStructInput", - parameter_name="n", - argument_value=n, - ) - return n - - def call( - self, n: AbiGenDummyNestedStruct, tx_params: Optional[TxParams] = None - ) -> None: - """Execute underlying contract method via eth_call. - - :param tx_params: transaction parameters - - """ - (n) = self.validate_and_normalize_inputs(n) - tx_params = super().normalize_tx_params(tx_params) - self._underlying_method(n).call(tx_params.as_dict()) - - def estimate_gas( - self, n: AbiGenDummyNestedStruct, tx_params: Optional[TxParams] = None - ) -> int: - """Estimate gas consumption of method call.""" - (n) = self.validate_and_normalize_inputs(n) - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method(n).estimateGas(tx_params.as_dict()) - - -class NestedStructOutputMethod(ContractMethod): # pylint: disable=invalid-name - """Various interfaces to the nestedStructOutput method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address) - self._underlying_method = contract_function - - def call( - self, tx_params: Optional[TxParams] = None - ) -> AbiGenDummyNestedStruct: - """Execute underlying contract method via eth_call. - - :param tx_params: transaction parameters - - """ - tx_params = super().normalize_tx_params(tx_params) - returned = self._underlying_method().call(tx_params.as_dict()) - return AbiGenDummyNestedStruct( - innerStruct=returned[0], description=returned[1], - ) - - def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int: - """Estimate gas consumption of method call.""" - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method().estimateGas(tx_params.as_dict()) - - -class NoInputNoOutputMethod(ContractMethod): # pylint: disable=invalid-name - """Various interfaces to the noInputNoOutput method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address) - self._underlying_method = contract_function - - def call(self, tx_params: Optional[TxParams] = None) -> None: - """Execute underlying contract method via eth_call. - - Tests decoding when both input and output are empty. - - :param tx_params: transaction parameters - - """ - tx_params = super().normalize_tx_params(tx_params) - self._underlying_method().call(tx_params.as_dict()) - - def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int: - """Estimate gas consumption of method call.""" - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method().estimateGas(tx_params.as_dict()) - - -class NoInputSimpleOutputMethod( - ContractMethod -): # pylint: disable=invalid-name - """Various interfaces to the noInputSimpleOutput method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address) - self._underlying_method = contract_function - - def call(self, tx_params: Optional[TxParams] = None) -> int: - """Execute underlying contract method via eth_call. - - Tests decoding when input is empty and output is non-empty. - - :param tx_params: transaction parameters - - """ - tx_params = super().normalize_tx_params(tx_params) - returned = self._underlying_method().call(tx_params.as_dict()) - return int(returned) - - def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int: - """Estimate gas consumption of method call.""" - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method().estimateGas(tx_params.as_dict()) - - -class NonPureMethodMethod(ContractMethod): # pylint: disable=invalid-name - """Various interfaces to the nonPureMethod method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address) - self._underlying_method = contract_function - - def call(self, tx_params: Optional[TxParams] = None) -> int: - """Execute underlying contract method via eth_call. - - :param tx_params: transaction parameters - :returns: the return value of the underlying method. - """ - tx_params = super().normalize_tx_params(tx_params) - returned = self._underlying_method().call(tx_params.as_dict()) - return int(returned) - - def send_transaction( - self, tx_params: Optional[TxParams] = None - ) -> Union[HexBytes, bytes]: - """Execute underlying contract method via eth_sendTransaction. - - :param tx_params: transaction parameters - """ - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method().transact(tx_params.as_dict()) - - def build_transaction(self, tx_params: Optional[TxParams] = None) -> dict: - """Construct calldata to be used as input to the method.""" - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method().buildTransaction(tx_params.as_dict()) - - def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int: - """Estimate gas consumption of method call.""" - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method().estimateGas(tx_params.as_dict()) - - -class NonPureMethodThatReturnsNothingMethod( - ContractMethod -): # pylint: disable=invalid-name - """Various interfaces to the nonPureMethodThatReturnsNothing method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address) - self._underlying_method = contract_function - - def call(self, tx_params: Optional[TxParams] = None) -> None: - """Execute underlying contract method via eth_call. - - :param tx_params: transaction parameters - :returns: the return value of the underlying method. - """ - tx_params = super().normalize_tx_params(tx_params) - self._underlying_method().call(tx_params.as_dict()) - - def send_transaction( - self, tx_params: Optional[TxParams] = None - ) -> Union[HexBytes, bytes]: - """Execute underlying contract method via eth_sendTransaction. - - :param tx_params: transaction parameters - """ - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method().transact(tx_params.as_dict()) - - def build_transaction(self, tx_params: Optional[TxParams] = None) -> dict: - """Construct calldata to be used as input to the method.""" - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method().buildTransaction(tx_params.as_dict()) - - def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int: - """Estimate gas consumption of method call.""" - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method().estimateGas(tx_params.as_dict()) - - -class OverloadedMethod2Method(ContractMethod): # pylint: disable=invalid-name - """Various interfaces to the overloadedMethod method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - validator: Validator = None, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address, validator) - self._underlying_method = contract_function - - def validate_and_normalize_inputs(self, a: str): - """Validate the inputs to the overloadedMethod method.""" - self.validator.assert_valid( - method_name="overloadedMethod", - parameter_name="a", - argument_value=a, - ) - return a - - def call(self, a: str, tx_params: Optional[TxParams] = None) -> None: - """Execute underlying contract method via eth_call. - - :param tx_params: transaction parameters - - """ - (a) = self.validate_and_normalize_inputs(a) - tx_params = super().normalize_tx_params(tx_params) - self._underlying_method(a).call(tx_params.as_dict()) - - def estimate_gas( - self, a: str, tx_params: Optional[TxParams] = None - ) -> int: - """Estimate gas consumption of method call.""" - (a) = self.validate_and_normalize_inputs(a) - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method(a).estimateGas(tx_params.as_dict()) - - -class OverloadedMethod1Method(ContractMethod): # pylint: disable=invalid-name - """Various interfaces to the overloadedMethod method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - validator: Validator = None, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address, validator) - self._underlying_method = contract_function - - def validate_and_normalize_inputs(self, a: int): - """Validate the inputs to the overloadedMethod method.""" - self.validator.assert_valid( - method_name="overloadedMethod", - parameter_name="a", - argument_value=a, - ) - return a - - def call(self, a: int, tx_params: Optional[TxParams] = None) -> None: - """Execute underlying contract method via eth_call. - - :param tx_params: transaction parameters - - """ - (a) = self.validate_and_normalize_inputs(a) - tx_params = super().normalize_tx_params(tx_params) - self._underlying_method(a).call(tx_params.as_dict()) - - def estimate_gas( - self, a: int, tx_params: Optional[TxParams] = None - ) -> int: - """Estimate gas consumption of method call.""" - (a) = self.validate_and_normalize_inputs(a) - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method(a).estimateGas(tx_params.as_dict()) - - -class PureFunctionWithConstantMethod( - ContractMethod -): # pylint: disable=invalid-name - """Various interfaces to the pureFunctionWithConstant method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address) - self._underlying_method = contract_function - - def call(self, tx_params: Optional[TxParams] = None) -> int: - """Execute underlying contract method via eth_call. - - :param tx_params: transaction parameters - - """ - tx_params = super().normalize_tx_params(tx_params) - returned = self._underlying_method().call(tx_params.as_dict()) - return int(returned) - - def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int: - """Estimate gas consumption of method call.""" - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method().estimateGas(tx_params.as_dict()) - - -class RequireWithConstantMethod( - ContractMethod -): # pylint: disable=invalid-name - """Various interfaces to the requireWithConstant method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address) - self._underlying_method = contract_function - - def call(self, tx_params: Optional[TxParams] = None) -> None: - """Execute underlying contract method via eth_call. - - :param tx_params: transaction parameters - - """ - tx_params = super().normalize_tx_params(tx_params) - self._underlying_method().call(tx_params.as_dict()) - - def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int: - """Estimate gas consumption of method call.""" - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method().estimateGas(tx_params.as_dict()) - - -class RevertWithConstantMethod(ContractMethod): # pylint: disable=invalid-name - """Various interfaces to the revertWithConstant method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address) - self._underlying_method = contract_function - - def call(self, tx_params: Optional[TxParams] = None) -> None: - """Execute underlying contract method via eth_call. - - :param tx_params: transaction parameters - - """ - tx_params = super().normalize_tx_params(tx_params) - self._underlying_method().call(tx_params.as_dict()) - - def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int: - """Estimate gas consumption of method call.""" - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method().estimateGas(tx_params.as_dict()) - - -class SimpleInputNoOutputMethod( - ContractMethod -): # pylint: disable=invalid-name - """Various interfaces to the simpleInputNoOutput method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - validator: Validator = None, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address, validator) - self._underlying_method = contract_function - - def validate_and_normalize_inputs(self, index_0: int): - """Validate the inputs to the simpleInputNoOutput method.""" - self.validator.assert_valid( - method_name="simpleInputNoOutput", - parameter_name="index_0", - argument_value=index_0, - ) - # safeguard against fractional inputs - index_0 = int(index_0) - return index_0 - - def call(self, index_0: int, tx_params: Optional[TxParams] = None) -> None: - """Execute underlying contract method via eth_call. - - Tests decoding when input is not empty but output is empty. - - :param tx_params: transaction parameters - - """ - (index_0) = self.validate_and_normalize_inputs(index_0) - tx_params = super().normalize_tx_params(tx_params) - self._underlying_method(index_0).call(tx_params.as_dict()) - - def estimate_gas( - self, index_0: int, tx_params: Optional[TxParams] = None - ) -> int: - """Estimate gas consumption of method call.""" - (index_0) = self.validate_and_normalize_inputs(index_0) - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method(index_0).estimateGas( - tx_params.as_dict() - ) - - -class SimpleInputSimpleOutputMethod( - ContractMethod -): # pylint: disable=invalid-name - """Various interfaces to the simpleInputSimpleOutput method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - validator: Validator = None, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address, validator) - self._underlying_method = contract_function - - def validate_and_normalize_inputs(self, index_0: int): - """Validate the inputs to the simpleInputSimpleOutput method.""" - self.validator.assert_valid( - method_name="simpleInputSimpleOutput", - parameter_name="index_0", - argument_value=index_0, - ) - # safeguard against fractional inputs - index_0 = int(index_0) - return index_0 - - def call(self, index_0: int, tx_params: Optional[TxParams] = None) -> int: - """Execute underlying contract method via eth_call. - - Tests decoding when both input and output are non-empty. - - :param tx_params: transaction parameters - - """ - (index_0) = self.validate_and_normalize_inputs(index_0) - tx_params = super().normalize_tx_params(tx_params) - returned = self._underlying_method(index_0).call(tx_params.as_dict()) - return int(returned) - - def estimate_gas( - self, index_0: int, tx_params: Optional[TxParams] = None - ) -> int: - """Estimate gas consumption of method call.""" - (index_0) = self.validate_and_normalize_inputs(index_0) - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method(index_0).estimateGas( - tx_params.as_dict() - ) - - -class SimplePureFunctionMethod(ContractMethod): # pylint: disable=invalid-name - """Various interfaces to the simplePureFunction method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address) - self._underlying_method = contract_function - - def call(self, tx_params: Optional[TxParams] = None) -> int: - """Execute underlying contract method via eth_call. - - :param tx_params: transaction parameters - - """ - tx_params = super().normalize_tx_params(tx_params) - returned = self._underlying_method().call(tx_params.as_dict()) - return int(returned) - - def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int: - """Estimate gas consumption of method call.""" - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method().estimateGas(tx_params.as_dict()) - - -class SimplePureFunctionWithInputMethod( - ContractMethod -): # pylint: disable=invalid-name - """Various interfaces to the simplePureFunctionWithInput method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - validator: Validator = None, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address, validator) - self._underlying_method = contract_function - - def validate_and_normalize_inputs(self, x: int): - """Validate the inputs to the simplePureFunctionWithInput method.""" - self.validator.assert_valid( - method_name="simplePureFunctionWithInput", - parameter_name="x", - argument_value=x, - ) - # safeguard against fractional inputs - x = int(x) - return x - - def call(self, x: int, tx_params: Optional[TxParams] = None) -> int: - """Execute underlying contract method via eth_call. - - :param tx_params: transaction parameters - - """ - (x) = self.validate_and_normalize_inputs(x) - tx_params = super().normalize_tx_params(tx_params) - returned = self._underlying_method(x).call(tx_params.as_dict()) - return int(returned) - - def estimate_gas( - self, x: int, tx_params: Optional[TxParams] = None - ) -> int: - """Estimate gas consumption of method call.""" - (x) = self.validate_and_normalize_inputs(x) - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method(x).estimateGas(tx_params.as_dict()) - - -class SimpleRequireMethod(ContractMethod): # pylint: disable=invalid-name - """Various interfaces to the simpleRequire method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address) - self._underlying_method = contract_function - - def call(self, tx_params: Optional[TxParams] = None) -> None: - """Execute underlying contract method via eth_call. - - :param tx_params: transaction parameters - - """ - tx_params = super().normalize_tx_params(tx_params) - self._underlying_method().call(tx_params.as_dict()) - - def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int: - """Estimate gas consumption of method call.""" - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method().estimateGas(tx_params.as_dict()) - - -class SimpleRevertMethod(ContractMethod): # pylint: disable=invalid-name - """Various interfaces to the simpleRevert method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address) - self._underlying_method = contract_function - - def call(self, tx_params: Optional[TxParams] = None) -> None: - """Execute underlying contract method via eth_call. - - :param tx_params: transaction parameters - - """ - tx_params = super().normalize_tx_params(tx_params) - self._underlying_method().call(tx_params.as_dict()) - - def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int: - """Estimate gas consumption of method call.""" - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method().estimateGas(tx_params.as_dict()) - - -class StructInputMethod(ContractMethod): # pylint: disable=invalid-name - """Various interfaces to the structInput method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - validator: Validator = None, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address, validator) - self._underlying_method = contract_function - - def validate_and_normalize_inputs(self, s: AbiGenDummyStruct): - """Validate the inputs to the structInput method.""" - self.validator.assert_valid( - method_name="structInput", parameter_name="s", argument_value=s, - ) - return s - - def call( - self, s: AbiGenDummyStruct, tx_params: Optional[TxParams] = None - ) -> None: - """Execute underlying contract method via eth_call. - - :param tx_params: transaction parameters - - """ - (s) = self.validate_and_normalize_inputs(s) - tx_params = super().normalize_tx_params(tx_params) - self._underlying_method(s).call(tx_params.as_dict()) - - def estimate_gas( - self, s: AbiGenDummyStruct, tx_params: Optional[TxParams] = None - ) -> int: - """Estimate gas consumption of method call.""" - (s) = self.validate_and_normalize_inputs(s) - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method(s).estimateGas(tx_params.as_dict()) - - -class StructOutputMethod(ContractMethod): # pylint: disable=invalid-name - """Various interfaces to the structOutput method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address) - self._underlying_method = contract_function - - def call(self, tx_params: Optional[TxParams] = None) -> AbiGenDummyStruct: - """Execute underlying contract method via eth_call. - - a method that returns a struct - - :param tx_params: transaction parameters - :returns: a Struct struct - """ - tx_params = super().normalize_tx_params(tx_params) - returned = self._underlying_method().call(tx_params.as_dict()) - return AbiGenDummyStruct( - someBytes=returned[0], - anInteger=returned[1], - aDynamicArrayOfBytes=returned[2], - aString=returned[3], - ) - - def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int: - """Estimate gas consumption of method call.""" - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method().estimateGas(tx_params.as_dict()) - - -class WithAddressInputMethod(ContractMethod): # pylint: disable=invalid-name - """Various interfaces to the withAddressInput method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - validator: Validator = None, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address, validator) - self._underlying_method = contract_function - - def validate_and_normalize_inputs( - self, x: str, a: int, b: int, y: str, c: int - ): - """Validate the inputs to the withAddressInput method.""" - self.validator.assert_valid( - method_name="withAddressInput", - parameter_name="x", - argument_value=x, - ) - x = self.validate_and_checksum_address(x) - self.validator.assert_valid( - method_name="withAddressInput", - parameter_name="a", - argument_value=a, - ) - # safeguard against fractional inputs - a = int(a) - self.validator.assert_valid( - method_name="withAddressInput", - parameter_name="b", - argument_value=b, - ) - # safeguard against fractional inputs - b = int(b) - self.validator.assert_valid( - method_name="withAddressInput", - parameter_name="y", - argument_value=y, - ) - y = self.validate_and_checksum_address(y) - self.validator.assert_valid( - method_name="withAddressInput", - parameter_name="c", - argument_value=c, - ) - # safeguard against fractional inputs - c = int(c) - return (x, a, b, y, c) - - def call( - self, - x: str, - a: int, - b: int, - y: str, - c: int, - tx_params: Optional[TxParams] = None, - ) -> str: - """Execute underlying contract method via eth_call. - - :param tx_params: transaction parameters - - """ - (x, a, b, y, c) = self.validate_and_normalize_inputs(x, a, b, y, c) - tx_params = super().normalize_tx_params(tx_params) - returned = self._underlying_method(x, a, b, y, c).call( - tx_params.as_dict() - ) - return str(returned) - - def estimate_gas( - self, - x: str, - a: int, - b: int, - y: str, - c: int, - tx_params: Optional[TxParams] = None, - ) -> int: - """Estimate gas consumption of method call.""" - (x, a, b, y, c) = self.validate_and_normalize_inputs(x, a, b, y, c) - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method(x, a, b, y, c).estimateGas( - tx_params.as_dict() - ) - - -class WithdrawMethod(ContractMethod): # pylint: disable=invalid-name - """Various interfaces to the withdraw method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - validator: Validator = None, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address, validator) - self._underlying_method = contract_function - - def validate_and_normalize_inputs(self, wad: int): - """Validate the inputs to the withdraw method.""" - self.validator.assert_valid( - method_name="withdraw", parameter_name="wad", argument_value=wad, - ) - # safeguard against fractional inputs - wad = int(wad) - return wad - - def call(self, wad: int, tx_params: Optional[TxParams] = None) -> None: - """Execute underlying contract method via eth_call. - - :param tx_params: transaction parameters - :returns: the return value of the underlying method. - """ - (wad) = self.validate_and_normalize_inputs(wad) - tx_params = super().normalize_tx_params(tx_params) - self._underlying_method(wad).call(tx_params.as_dict()) - - def send_transaction( - self, wad: int, tx_params: Optional[TxParams] = None - ) -> Union[HexBytes, bytes]: - """Execute underlying contract method via eth_sendTransaction. - - :param tx_params: transaction parameters - """ - (wad) = self.validate_and_normalize_inputs(wad) - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method(wad).transact(tx_params.as_dict()) - - def build_transaction( - self, wad: int, tx_params: Optional[TxParams] = None - ) -> dict: - """Construct calldata to be used as input to the method.""" - (wad) = self.validate_and_normalize_inputs(wad) - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method(wad).buildTransaction( - tx_params.as_dict() - ) - - def estimate_gas( - self, wad: int, tx_params: Optional[TxParams] = None - ) -> int: - """Estimate gas consumption of method call.""" - (wad) = self.validate_and_normalize_inputs(wad) - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method(wad).estimateGas(tx_params.as_dict()) - - -# pylint: disable=too-many-public-methods,too-many-instance-attributes -class AbiGenDummy: - """Wrapper class for AbiGenDummy Solidity contract. - - All method parameters of type `bytes`:code: should be encoded as UTF-8, - which can be accomplished via `str.encode("utf_8")`:code:. - """ - - accepts_an_array_of_bytes: AcceptsAnArrayOfBytesMethod - """Constructor-initialized instance of - :class:`AcceptsAnArrayOfBytesMethod`. - """ - - accepts_bytes: AcceptsBytesMethod - """Constructor-initialized instance of - :class:`AcceptsBytesMethod`. - """ - - complex_input_complex_output: ComplexInputComplexOutputMethod - """Constructor-initialized instance of - :class:`ComplexInputComplexOutputMethod`. - """ - - ecrecover_fn: EcrecoverFnMethod - """Constructor-initialized instance of - :class:`EcrecoverFnMethod`. - """ - - emit_simple_event: EmitSimpleEventMethod - """Constructor-initialized instance of - :class:`EmitSimpleEventMethod`. - """ - - method_accepting_array_of_array_of_structs: MethodAcceptingArrayOfArrayOfStructsMethod - """Constructor-initialized instance of - :class:`MethodAcceptingArrayOfArrayOfStructsMethod`. - """ - - method_accepting_array_of_structs: MethodAcceptingArrayOfStructsMethod - """Constructor-initialized instance of - :class:`MethodAcceptingArrayOfStructsMethod`. - """ - - method_returning_array_of_structs: MethodReturningArrayOfStructsMethod - """Constructor-initialized instance of - :class:`MethodReturningArrayOfStructsMethod`. - """ - - method_returning_multiple_values: MethodReturningMultipleValuesMethod - """Constructor-initialized instance of - :class:`MethodReturningMultipleValuesMethod`. - """ - - method_using_nested_struct_with_inner_struct_not_used_elsewhere: MethodUsingNestedStructWithInnerStructNotUsedElsewhereMethod - """Constructor-initialized instance of - :class:`MethodUsingNestedStructWithInnerStructNotUsedElsewhereMethod`. - """ - - multi_input_multi_output: MultiInputMultiOutputMethod - """Constructor-initialized instance of - :class:`MultiInputMultiOutputMethod`. - """ - - nested_struct_input: NestedStructInputMethod - """Constructor-initialized instance of - :class:`NestedStructInputMethod`. - """ - - nested_struct_output: NestedStructOutputMethod - """Constructor-initialized instance of - :class:`NestedStructOutputMethod`. - """ - - no_input_no_output: NoInputNoOutputMethod - """Constructor-initialized instance of - :class:`NoInputNoOutputMethod`. - """ - - no_input_simple_output: NoInputSimpleOutputMethod - """Constructor-initialized instance of - :class:`NoInputSimpleOutputMethod`. - """ - - non_pure_method: NonPureMethodMethod - """Constructor-initialized instance of - :class:`NonPureMethodMethod`. - """ - - non_pure_method_that_returns_nothing: NonPureMethodThatReturnsNothingMethod - """Constructor-initialized instance of - :class:`NonPureMethodThatReturnsNothingMethod`. - """ - - overloaded_method2: OverloadedMethod2Method - """Constructor-initialized instance of - :class:`OverloadedMethod2Method`. - """ - - overloaded_method1: OverloadedMethod1Method - """Constructor-initialized instance of - :class:`OverloadedMethod1Method`. - """ - - pure_function_with_constant: PureFunctionWithConstantMethod - """Constructor-initialized instance of - :class:`PureFunctionWithConstantMethod`. - """ - - require_with_constant: RequireWithConstantMethod - """Constructor-initialized instance of - :class:`RequireWithConstantMethod`. - """ - - revert_with_constant: RevertWithConstantMethod - """Constructor-initialized instance of - :class:`RevertWithConstantMethod`. - """ - - simple_input_no_output: SimpleInputNoOutputMethod - """Constructor-initialized instance of - :class:`SimpleInputNoOutputMethod`. - """ - - simple_input_simple_output: SimpleInputSimpleOutputMethod - """Constructor-initialized instance of - :class:`SimpleInputSimpleOutputMethod`. - """ - - simple_pure_function: SimplePureFunctionMethod - """Constructor-initialized instance of - :class:`SimplePureFunctionMethod`. - """ - - simple_pure_function_with_input: SimplePureFunctionWithInputMethod - """Constructor-initialized instance of - :class:`SimplePureFunctionWithInputMethod`. - """ - - simple_require: SimpleRequireMethod - """Constructor-initialized instance of - :class:`SimpleRequireMethod`. - """ - - simple_revert: SimpleRevertMethod - """Constructor-initialized instance of - :class:`SimpleRevertMethod`. - """ - - struct_input: StructInputMethod - """Constructor-initialized instance of - :class:`StructInputMethod`. - """ - - struct_output: StructOutputMethod - """Constructor-initialized instance of - :class:`StructOutputMethod`. - """ - - with_address_input: WithAddressInputMethod - """Constructor-initialized instance of - :class:`WithAddressInputMethod`. - """ - - withdraw: WithdrawMethod - """Constructor-initialized instance of - :class:`WithdrawMethod`. - """ - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - validator: AbiGenDummyValidator = None, - ): - """Get an instance of wrapper for smart contract. - - :param web3_or_provider: Either an instance of `web3.Web3`:code: or - `web3.providers.base.BaseProvider`:code: - :param contract_address: where the contract has been deployed - :param validator: for validation of method inputs. - """ - # pylint: disable=too-many-statements - - self.contract_address = contract_address - - if not validator: - validator = AbiGenDummyValidator( - web3_or_provider, contract_address - ) - - web3 = None - if isinstance(web3_or_provider, BaseProvider): - web3 = Web3(web3_or_provider) - elif isinstance(web3_or_provider, Web3): - web3 = web3_or_provider - else: - raise TypeError( - "Expected parameter 'web3_or_provider' to be an instance of either" - + " Web3 or BaseProvider" - ) - - # if any middleware was imported, inject it - try: - MIDDLEWARE - except NameError: - pass - else: - try: - for middleware in MIDDLEWARE: - web3.middleware_onion.inject( - middleware["function"], layer=middleware["layer"], - ) - except ValueError as value_error: - if value_error.args == ( - "You can't add the same un-named instance twice", - ): - pass - - self._web3_eth = web3.eth - - functions = self._web3_eth.contract( - address=to_checksum_address(contract_address), - abi=AbiGenDummy.abi(), - ).functions - - self.accepts_an_array_of_bytes = AcceptsAnArrayOfBytesMethod( - web3_or_provider, - contract_address, - functions.acceptsAnArrayOfBytes, - validator, - ) - - self.accepts_bytes = AcceptsBytesMethod( - web3_or_provider, - contract_address, - functions.acceptsBytes, - validator, - ) - - self.complex_input_complex_output = ComplexInputComplexOutputMethod( - web3_or_provider, - contract_address, - functions.complexInputComplexOutput, - validator, - ) - - self.ecrecover_fn = EcrecoverFnMethod( - web3_or_provider, - contract_address, - functions.ecrecoverFn, - validator, - ) - - self.emit_simple_event = EmitSimpleEventMethod( - web3_or_provider, contract_address, functions.emitSimpleEvent - ) - - self.method_accepting_array_of_array_of_structs = MethodAcceptingArrayOfArrayOfStructsMethod( - web3_or_provider, - contract_address, - functions.methodAcceptingArrayOfArrayOfStructs, - validator, - ) - - self.method_accepting_array_of_structs = MethodAcceptingArrayOfStructsMethod( - web3_or_provider, - contract_address, - functions.methodAcceptingArrayOfStructs, - validator, - ) - - self.method_returning_array_of_structs = MethodReturningArrayOfStructsMethod( - web3_or_provider, - contract_address, - functions.methodReturningArrayOfStructs, - ) - - self.method_returning_multiple_values = MethodReturningMultipleValuesMethod( - web3_or_provider, - contract_address, - functions.methodReturningMultipleValues, - ) - - self.method_using_nested_struct_with_inner_struct_not_used_elsewhere = MethodUsingNestedStructWithInnerStructNotUsedElsewhereMethod( - web3_or_provider, - contract_address, - functions.methodUsingNestedStructWithInnerStructNotUsedElsewhere, - ) - - self.multi_input_multi_output = MultiInputMultiOutputMethod( - web3_or_provider, - contract_address, - functions.multiInputMultiOutput, - validator, - ) - - self.nested_struct_input = NestedStructInputMethod( - web3_or_provider, - contract_address, - functions.nestedStructInput, - validator, - ) - - self.nested_struct_output = NestedStructOutputMethod( - web3_or_provider, contract_address, functions.nestedStructOutput - ) - - self.no_input_no_output = NoInputNoOutputMethod( - web3_or_provider, contract_address, functions.noInputNoOutput - ) - - self.no_input_simple_output = NoInputSimpleOutputMethod( - web3_or_provider, contract_address, functions.noInputSimpleOutput - ) - - self.non_pure_method = NonPureMethodMethod( - web3_or_provider, contract_address, functions.nonPureMethod - ) - - self.non_pure_method_that_returns_nothing = NonPureMethodThatReturnsNothingMethod( - web3_or_provider, - contract_address, - functions.nonPureMethodThatReturnsNothing, - ) - - self.overloaded_method2 = OverloadedMethod2Method( - web3_or_provider, - contract_address, - functions.overloadedMethod, - validator, - ) - - self.overloaded_method1 = OverloadedMethod1Method( - web3_or_provider, - contract_address, - functions.overloadedMethod, - validator, - ) - - self.pure_function_with_constant = PureFunctionWithConstantMethod( - web3_or_provider, - contract_address, - functions.pureFunctionWithConstant, - ) - - self.require_with_constant = RequireWithConstantMethod( - web3_or_provider, contract_address, functions.requireWithConstant - ) - - self.revert_with_constant = RevertWithConstantMethod( - web3_or_provider, contract_address, functions.revertWithConstant - ) - - self.simple_input_no_output = SimpleInputNoOutputMethod( - web3_or_provider, - contract_address, - functions.simpleInputNoOutput, - validator, - ) - - self.simple_input_simple_output = SimpleInputSimpleOutputMethod( - web3_or_provider, - contract_address, - functions.simpleInputSimpleOutput, - validator, - ) - - self.simple_pure_function = SimplePureFunctionMethod( - web3_or_provider, contract_address, functions.simplePureFunction - ) - - self.simple_pure_function_with_input = SimplePureFunctionWithInputMethod( - web3_or_provider, - contract_address, - functions.simplePureFunctionWithInput, - validator, - ) - - self.simple_require = SimpleRequireMethod( - web3_or_provider, contract_address, functions.simpleRequire - ) - - self.simple_revert = SimpleRevertMethod( - web3_or_provider, contract_address, functions.simpleRevert - ) - - self.struct_input = StructInputMethod( - web3_or_provider, - contract_address, - functions.structInput, - validator, - ) - - self.struct_output = StructOutputMethod( - web3_or_provider, contract_address, functions.structOutput - ) - - self.with_address_input = WithAddressInputMethod( - web3_or_provider, - contract_address, - functions.withAddressInput, - validator, - ) - - self.withdraw = WithdrawMethod( - web3_or_provider, contract_address, functions.withdraw, validator - ) - - def get_simple_event_event( - self, tx_hash: Union[HexBytes, bytes] - ) -> Tuple[AttributeDict]: - """Get log entry for SimpleEvent event. - - :param tx_hash: hash of transaction emitting SimpleEvent event - """ - tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) - return ( - self._web3_eth.contract( - address=to_checksum_address(self.contract_address), - abi=AbiGenDummy.abi(), - ) - .events.SimpleEvent() - .processReceipt(tx_receipt) - ) - - def get_withdrawal_event( - self, tx_hash: Union[HexBytes, bytes] - ) -> Tuple[AttributeDict]: - """Get log entry for Withdrawal event. - - :param tx_hash: hash of transaction emitting Withdrawal event - """ - tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) - return ( - self._web3_eth.contract( - address=to_checksum_address(self.contract_address), - abi=AbiGenDummy.abi(), - ) - .events.Withdrawal() - .processReceipt(tx_receipt) - ) - - @staticmethod - def abi(): - """Return the ABI to the underlying contract.""" - return json.loads( - '[{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"someBytes","type":"bytes"},{"indexed":false,"internalType":"string","name":"someString","type":"string"}],"name":"SimpleEvent","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"_value","type":"uint256"}],"name":"Withdrawal","type":"event"},{"constant":true,"inputs":[{"internalType":"bytes[]","name":"a","type":"bytes[]"}],"name":"acceptsAnArrayOfBytes","outputs":[],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes","name":"a","type":"bytes"}],"name":"acceptsBytes","outputs":[],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"components":[{"internalType":"uint256","name":"foo","type":"uint256"},{"internalType":"bytes","name":"bar","type":"bytes"},{"internalType":"string","name":"car","type":"string"}],"internalType":"struct AbiGenDummy.ComplexInput","name":"complexInput","type":"tuple"}],"name":"complexInputComplexOutput","outputs":[{"components":[{"components":[{"internalType":"uint256","name":"foo","type":"uint256"},{"internalType":"bytes","name":"bar","type":"bytes"},{"internalType":"string","name":"car","type":"string"}],"internalType":"struct AbiGenDummy.ComplexInput","name":"input","type":"tuple"},{"internalType":"bytes","name":"lorem","type":"bytes"},{"internalType":"bytes","name":"ipsum","type":"bytes"},{"internalType":"string","name":"dolor","type":"string"}],"internalType":"struct AbiGenDummy.ComplexOutput","name":"","type":"tuple"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"hash","type":"bytes32"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"ecrecoverFn","outputs":[{"internalType":"address","name":"signerAddress","type":"address"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":false,"inputs":[],"name":"emitSimpleEvent","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"components":[{"internalType":"bytes","name":"someBytes","type":"bytes"},{"internalType":"uint32","name":"anInteger","type":"uint32"},{"internalType":"bytes[]","name":"aDynamicArrayOfBytes","type":"bytes[]"},{"internalType":"string","name":"aString","type":"string"}],"internalType":"struct AbiGenDummy.Struct[][]","name":"index_0","type":"tuple[][]"}],"name":"methodAcceptingArrayOfArrayOfStructs","outputs":[],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"components":[{"internalType":"bytes","name":"someBytes","type":"bytes"},{"internalType":"uint32","name":"anInteger","type":"uint32"},{"internalType":"bytes[]","name":"aDynamicArrayOfBytes","type":"bytes[]"},{"internalType":"string","name":"aString","type":"string"}],"internalType":"struct AbiGenDummy.Struct[]","name":"index_0","type":"tuple[]"}],"name":"methodAcceptingArrayOfStructs","outputs":[],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[],"name":"methodReturningArrayOfStructs","outputs":[{"components":[{"internalType":"bytes","name":"someBytes","type":"bytes"},{"internalType":"uint32","name":"anInteger","type":"uint32"},{"internalType":"bytes[]","name":"aDynamicArrayOfBytes","type":"bytes[]"},{"internalType":"string","name":"aString","type":"string"}],"internalType":"struct AbiGenDummy.Struct[]","name":"","type":"tuple[]"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[],"name":"methodReturningMultipleValues","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"string","name":"","type":"string"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[],"name":"methodUsingNestedStructWithInnerStructNotUsedElsewhere","outputs":[{"components":[{"components":[{"internalType":"uint256","name":"aField","type":"uint256"}],"internalType":"struct AbiGenDummy.StructNotDirectlyUsedAnywhere","name":"innerStruct","type":"tuple"}],"internalType":"struct AbiGenDummy.NestedStructWithInnerStructNotUsedElsewhere","name":"","type":"tuple"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"index_0","type":"uint256"},{"internalType":"bytes","name":"index_1","type":"bytes"},{"internalType":"string","name":"index_2","type":"string"}],"name":"multiInputMultiOutput","outputs":[{"internalType":"bytes","name":"","type":"bytes"},{"internalType":"bytes","name":"","type":"bytes"},{"internalType":"string","name":"","type":"string"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"components":[{"components":[{"internalType":"bytes","name":"someBytes","type":"bytes"},{"internalType":"uint32","name":"anInteger","type":"uint32"},{"internalType":"bytes[]","name":"aDynamicArrayOfBytes","type":"bytes[]"},{"internalType":"string","name":"aString","type":"string"}],"internalType":"struct AbiGenDummy.Struct","name":"innerStruct","type":"tuple"},{"internalType":"string","name":"description","type":"string"}],"internalType":"struct AbiGenDummy.NestedStruct","name":"n","type":"tuple"}],"name":"nestedStructInput","outputs":[],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[],"name":"nestedStructOutput","outputs":[{"components":[{"components":[{"internalType":"bytes","name":"someBytes","type":"bytes"},{"internalType":"uint32","name":"anInteger","type":"uint32"},{"internalType":"bytes[]","name":"aDynamicArrayOfBytes","type":"bytes[]"},{"internalType":"string","name":"aString","type":"string"}],"internalType":"struct AbiGenDummy.Struct","name":"innerStruct","type":"tuple"},{"internalType":"string","name":"description","type":"string"}],"internalType":"struct AbiGenDummy.NestedStruct","name":"","type":"tuple"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[],"name":"noInputNoOutput","outputs":[],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[],"name":"noInputSimpleOutput","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":false,"inputs":[],"name":"nonPureMethod","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"nonPureMethodThatReturnsNothing","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"string","name":"a","type":"string"}],"name":"overloadedMethod","outputs":[],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"int256","name":"a","type":"int256"}],"name":"overloadedMethod","outputs":[],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[],"name":"pureFunctionWithConstant","outputs":[{"internalType":"uint256","name":"someConstant","type":"uint256"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[],"name":"requireWithConstant","outputs":[],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[],"name":"revertWithConstant","outputs":[],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"index_0","type":"uint256"}],"name":"simpleInputNoOutput","outputs":[],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"index_0","type":"uint256"}],"name":"simpleInputSimpleOutput","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[],"name":"simplePureFunction","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"x","type":"uint256"}],"name":"simplePureFunctionWithInput","outputs":[{"internalType":"uint256","name":"sum","type":"uint256"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[],"name":"simpleRequire","outputs":[],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[],"name":"simpleRevert","outputs":[],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"components":[{"internalType":"bytes","name":"someBytes","type":"bytes"},{"internalType":"uint32","name":"anInteger","type":"uint32"},{"internalType":"bytes[]","name":"aDynamicArrayOfBytes","type":"bytes[]"},{"internalType":"string","name":"aString","type":"string"}],"internalType":"struct AbiGenDummy.Struct","name":"s","type":"tuple"}],"name":"structInput","outputs":[],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[],"name":"structOutput","outputs":[{"components":[{"internalType":"bytes","name":"someBytes","type":"bytes"},{"internalType":"uint32","name":"anInteger","type":"uint32"},{"internalType":"bytes[]","name":"aDynamicArrayOfBytes","type":"bytes[]"},{"internalType":"string","name":"aString","type":"string"}],"internalType":"struct AbiGenDummy.Struct","name":"s","type":"tuple"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"x","type":"address"},{"internalType":"uint256","name":"a","type":"uint256"},{"internalType":"uint256","name":"b","type":"uint256"},{"internalType":"address","name":"y","type":"address"},{"internalType":"uint256","name":"c","type":"uint256"}],"name":"withAddressInput","outputs":[{"internalType":"address","name":"z","type":"address"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"wad","type":"uint256"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]' # noqa: E501 (line-too-long) - ) - - -# pylint: disable=too-many-lines diff --git a/packages/abi-gen/test-cli/output/python/lib_dummy/__init__.py b/packages/abi-gen/test-cli/output/python/lib_dummy/__init__.py deleted file mode 100644 index 12e96c147f..0000000000 --- a/packages/abi-gen/test-cli/output/python/lib_dummy/__init__.py +++ /dev/null @@ -1,109 +0,0 @@ -"""Generated wrapper for LibDummy Solidity contract.""" - -# pylint: disable=too-many-arguments - -import json -from typing import ( # pylint: disable=unused-import - Any, - List, - Optional, - Tuple, - Union, -) - -from eth_utils import to_checksum_address -from mypy_extensions import TypedDict # pylint: disable=unused-import -from hexbytes import HexBytes -from web3 import Web3 -from web3.contract import ContractFunction -from web3.datastructures import AttributeDict -from web3.providers.base import BaseProvider - -from zero_ex.contract_wrappers.bases import ContractMethod, Validator -from zero_ex.contract_wrappers.tx_params import TxParams - - -# Try to import a custom validator class definition; if there isn't one, -# declare one that we can instantiate for the default argument to the -# constructor for LibDummy below. -try: - # both mypy and pylint complain about what we're doing here, but this - # works just fine, so their messages have been disabled here. - from . import ( # type: ignore # pylint: disable=import-self - LibDummyValidator, - ) -except ImportError: - - class LibDummyValidator( # type: ignore - Validator - ): - """No-op input validator.""" - - -try: - from .middleware import MIDDLEWARE # type: ignore -except ImportError: - pass - - -# pylint: disable=too-many-public-methods,too-many-instance-attributes -class LibDummy: - """Wrapper class for LibDummy Solidity contract.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - validator: LibDummyValidator = None, - ): - """Get an instance of wrapper for smart contract. - - :param web3_or_provider: Either an instance of `web3.Web3`:code: or - `web3.providers.base.BaseProvider`:code: - :param contract_address: where the contract has been deployed - :param validator: for validation of method inputs. - """ - # pylint: disable=too-many-statements - - self.contract_address = contract_address - - if not validator: - validator = LibDummyValidator(web3_or_provider, contract_address) - - web3 = None - if isinstance(web3_or_provider, BaseProvider): - web3 = Web3(web3_or_provider) - elif isinstance(web3_or_provider, Web3): - web3 = web3_or_provider - else: - raise TypeError( - "Expected parameter 'web3_or_provider' to be an instance of either" - + " Web3 or BaseProvider" - ) - - # if any middleware was imported, inject it - try: - MIDDLEWARE - except NameError: - pass - else: - try: - for middleware in MIDDLEWARE: - web3.middleware_onion.inject( - middleware["function"], layer=middleware["layer"], - ) - except ValueError as value_error: - if value_error.args == ( - "You can't add the same un-named instance twice", - ): - pass - - self._web3_eth = web3.eth - - @staticmethod - def abi(): - """Return the ABI to the underlying contract.""" - return json.loads("[]") # noqa: E501 (line-too-long) - - -# pylint: disable=too-many-lines diff --git a/packages/abi-gen/test-cli/output/python/test_lib_dummy/__init__.py b/packages/abi-gen/test-cli/output/python/test_lib_dummy/__init__.py deleted file mode 100644 index 9fd3ea6e65..0000000000 --- a/packages/abi-gen/test-cli/output/python/test_lib_dummy/__init__.py +++ /dev/null @@ -1,230 +0,0 @@ -"""Generated wrapper for TestLibDummy Solidity contract.""" - -# pylint: disable=too-many-arguments - -import json -from typing import ( # pylint: disable=unused-import - Any, - List, - Optional, - Tuple, - Union, -) - -from eth_utils import to_checksum_address -from mypy_extensions import TypedDict # pylint: disable=unused-import -from hexbytes import HexBytes -from web3 import Web3 -from web3.contract import ContractFunction -from web3.datastructures import AttributeDict -from web3.providers.base import BaseProvider - -from zero_ex.contract_wrappers.bases import ContractMethod, Validator -from zero_ex.contract_wrappers.tx_params import TxParams - - -# Try to import a custom validator class definition; if there isn't one, -# declare one that we can instantiate for the default argument to the -# constructor for TestLibDummy below. -try: - # both mypy and pylint complain about what we're doing here, but this - # works just fine, so their messages have been disabled here. - from . import ( # type: ignore # pylint: disable=import-self - TestLibDummyValidator, - ) -except ImportError: - - class TestLibDummyValidator( # type: ignore - Validator - ): - """No-op input validator.""" - - -try: - from .middleware import MIDDLEWARE # type: ignore -except ImportError: - pass - - -class PublicAddConstantMethod(ContractMethod): # pylint: disable=invalid-name - """Various interfaces to the publicAddConstant method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - validator: Validator = None, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address, validator) - self._underlying_method = contract_function - - def validate_and_normalize_inputs(self, x: int): - """Validate the inputs to the publicAddConstant method.""" - self.validator.assert_valid( - method_name="publicAddConstant", - parameter_name="x", - argument_value=x, - ) - # safeguard against fractional inputs - x = int(x) - return x - - def call(self, x: int, tx_params: Optional[TxParams] = None) -> int: - """Execute underlying contract method via eth_call. - - :param tx_params: transaction parameters - - """ - (x) = self.validate_and_normalize_inputs(x) - tx_params = super().normalize_tx_params(tx_params) - returned = self._underlying_method(x).call(tx_params.as_dict()) - return int(returned) - - def estimate_gas( - self, x: int, tx_params: Optional[TxParams] = None - ) -> int: - """Estimate gas consumption of method call.""" - (x) = self.validate_and_normalize_inputs(x) - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method(x).estimateGas(tx_params.as_dict()) - - -class PublicAddOneMethod(ContractMethod): # pylint: disable=invalid-name - """Various interfaces to the publicAddOne method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - contract_function: ContractFunction, - validator: Validator = None, - ): - """Persist instance data.""" - super().__init__(web3_or_provider, contract_address, validator) - self._underlying_method = contract_function - - def validate_and_normalize_inputs(self, x: int): - """Validate the inputs to the publicAddOne method.""" - self.validator.assert_valid( - method_name="publicAddOne", parameter_name="x", argument_value=x, - ) - # safeguard against fractional inputs - x = int(x) - return x - - def call(self, x: int, tx_params: Optional[TxParams] = None) -> int: - """Execute underlying contract method via eth_call. - - :param tx_params: transaction parameters - - """ - (x) = self.validate_and_normalize_inputs(x) - tx_params = super().normalize_tx_params(tx_params) - returned = self._underlying_method(x).call(tx_params.as_dict()) - return int(returned) - - def estimate_gas( - self, x: int, tx_params: Optional[TxParams] = None - ) -> int: - """Estimate gas consumption of method call.""" - (x) = self.validate_and_normalize_inputs(x) - tx_params = super().normalize_tx_params(tx_params) - return self._underlying_method(x).estimateGas(tx_params.as_dict()) - - -# pylint: disable=too-many-public-methods,too-many-instance-attributes -class TestLibDummy: - """Wrapper class for TestLibDummy Solidity contract.""" - - public_add_constant: PublicAddConstantMethod - """Constructor-initialized instance of - :class:`PublicAddConstantMethod`. - """ - - public_add_one: PublicAddOneMethod - """Constructor-initialized instance of - :class:`PublicAddOneMethod`. - """ - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - validator: TestLibDummyValidator = None, - ): - """Get an instance of wrapper for smart contract. - - :param web3_or_provider: Either an instance of `web3.Web3`:code: or - `web3.providers.base.BaseProvider`:code: - :param contract_address: where the contract has been deployed - :param validator: for validation of method inputs. - """ - # pylint: disable=too-many-statements - - self.contract_address = contract_address - - if not validator: - validator = TestLibDummyValidator( - web3_or_provider, contract_address - ) - - web3 = None - if isinstance(web3_or_provider, BaseProvider): - web3 = Web3(web3_or_provider) - elif isinstance(web3_or_provider, Web3): - web3 = web3_or_provider - else: - raise TypeError( - "Expected parameter 'web3_or_provider' to be an instance of either" - + " Web3 or BaseProvider" - ) - - # if any middleware was imported, inject it - try: - MIDDLEWARE - except NameError: - pass - else: - try: - for middleware in MIDDLEWARE: - web3.middleware_onion.inject( - middleware["function"], layer=middleware["layer"], - ) - except ValueError as value_error: - if value_error.args == ( - "You can't add the same un-named instance twice", - ): - pass - - self._web3_eth = web3.eth - - functions = self._web3_eth.contract( - address=to_checksum_address(contract_address), - abi=TestLibDummy.abi(), - ).functions - - self.public_add_constant = PublicAddConstantMethod( - web3_or_provider, - contract_address, - functions.publicAddConstant, - validator, - ) - - self.public_add_one = PublicAddOneMethod( - web3_or_provider, - contract_address, - functions.publicAddOne, - validator, - ) - - @staticmethod - def abi(): - """Return the ABI to the underlying contract.""" - return json.loads( - '[{"constant":true,"inputs":[{"internalType":"uint256","name":"x","type":"uint256"}],"name":"publicAddConstant","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"x","type":"uint256"}],"name":"publicAddOne","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"payable":false,"stateMutability":"pure","type":"function"}]' # noqa: E501 (line-too-long) - ) - - -# pylint: disable=too-many-lines diff --git a/packages/abi-gen/test-cli/output/typescript/abi_gen_dummy.ts b/packages/abi-gen/test-cli/output/typescript/abi_gen_dummy.ts deleted file mode 100644 index 5dd3fddaf0..0000000000 --- a/packages/abi-gen/test-cli/output/typescript/abi_gen_dummy.ts +++ /dev/null @@ -1,2140 +0,0 @@ -// tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma enum-naming -// tslint:disable:whitespace no-unbound-method no-trailing-whitespace -// tslint:disable:no-unused-variable -import { - AwaitTransactionSuccessOpts, - ContractFunctionObj, - ContractTxFunctionObj, - SendTransactionOpts, - BaseContract, - SubscriptionManager, - PromiseWithTransactionHash, - methodAbiToFunctionSignature, - linkLibrariesInBytecode, -} from '@0x/base-contract'; -import { schemas } from '@0x/json-schemas'; -import { - BlockParam, - BlockParamLiteral, - BlockRange, - CallData, - ContractAbi, - ContractArtifact, - DecodedLogArgs, - LogWithDecodedArgs, - MethodAbi, - TransactionReceiptWithDecodedLogs, - TxData, - TxDataPayable, - SupportedProvider, -} from 'ethereum-types'; -import { BigNumber, classUtils, hexUtils, logUtils, providerUtils } from '@0x/utils'; -import { EventCallback, IndexedFilterValues, SimpleContractArtifact } from '@0x/types'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import { assert } from '@0x/assert'; -import * as ethers from 'ethers'; -// tslint:enable:no-unused-variable - -export type AbiGenDummyEventArgs = AbiGenDummySimpleEventEventArgs | AbiGenDummyWithdrawalEventArgs; - -export enum AbiGenDummyEvents { - SimpleEvent = 'SimpleEvent', - Withdrawal = 'Withdrawal', -} - -export interface AbiGenDummySimpleEventEventArgs extends DecodedLogArgs { - someBytes: string; - someString: string; -} - -export interface AbiGenDummyWithdrawalEventArgs extends DecodedLogArgs { - _owner: string; - _value: BigNumber; -} - -/* istanbul ignore next */ -// tslint:disable:array-type -// tslint:disable:no-parameter-reassignment -// tslint:disable-next-line:class-name -export class AbiGenDummyContract extends BaseContract { - /** - * @ignore - */ - public static deployedBytecode = - '0x608060405234801561001057600080fd5b50600436106101ef5760003560e01c806377ec31ae1161010f578063bdab1688116100a2578063e796ee9611610071578063e796ee96146103c7578063ee8b86fb146103d5578063f408fb311461028f578063fa315f9d146103e8576101ef565b8063bdab16881461038d578063cd3c0b97146103a2578063d6d7618c146103aa578063d88be12f146103bf576101ef565b80639a3b6185116100de5780639a3b618514610359578063a3c2f6b614610361578063ae2dae1714610369578063bb60736214610377576101ef565b806377ec31ae146103105780637833bec01461031e5780637a791e6e1461033e5780638ee52b4e14610346576101ef565b80634582eab2116101875780635ba3c7c0116101565780635ba3c7c0146102df57806363d69c88146102e7578063647341eb146102fa57806376f15d5b14610308576101ef565b80634582eab2146102a557806345fdbdb7146102ad578063586f84b2146102b557806359c28add146102ca576101ef565b80633687617d116101c35780633687617d1461024d57806336b323961461026f5780633e9ef66a1461028f5780634303a5421461029d576101ef565b806209e437146101f45780630527c28f146101fe5780631310e444146102115780632e1a7d4d1461023a575b600080fd5b6101fc6103f6565b005b6101fc61020c366004610d98565b610433565b61022461021f366004610ec5565b610436565b6040516102319190611526565b60405180910390f35b6101fc610248366004610ec5565b61043d565b61026061025b36600461103a565b61048e565b6040516102319392919061128f565b61028261027d366004610e51565b61052e565b60405161023191906111d2565b6101fc61020c366004610e92565b610224610610565b6101fc610617565b6101fc61067c565b6102bd6106ae565b60405161023191906114b1565b6102d26106b6565b60405161023191906114bc565b6101fc6106be565b6102826102f5366004610cbb565b610723565b6101fc61020c366004611007565b61022461072c565b6101fc61020c366004610e16565b61033161032c366004610edd565b61073a565b60405161023191906113c5565b6101fc6107f7565b610224610354366004610ec5565b6107fc565b6101fc610802565b61022461080d565b6101fc61020c366004610f77565b61037f610812565b60405161023192919061152f565b61039561084b565b60405161023191906111f3565b6101fc610850565b6103b2610887565b6040516102319190611513565b6102246109e0565b6101fc61020c366004610d0c565b6101fc6103e3366004610ec5565b61020c565b6101fc61020c366004610ec5565b6040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016104289061138e565b60405180910390fd5b565b50565b506107c790565b3373ffffffffffffffffffffffffffffffffffffffff167f7fcf532c15f0a6db0bd6d0e038bea71d30d808c7d98cb3bf7268a95bf5081b65826040516104839190611526565b60405180910390a250565b505060408051808201825260048082527f1234567800000000000000000000000000000000000000000000000000000000602080840191909152835180850185528281527f87654321000000000000000000000000000000000000000000000000000000008183015284518086019095529184527f616d657400000000000000000000000000000000000000000000000000000000908401529093909250565b600060606040518060400160405280601c81526020017f19457468657265756d205369676e6564204d6573736167653a0a33320000000081525090506000818760405160200161057f9291906111b0565b604051602081830303815290604052805190602001209050600181878787604051600081526020016040526040516105ba9493929190611271565b6020604051602081039080840390855afa1580156105dc573d6000803e3d6000fd5b50506040517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0015198975050505050505050565b6107c75b90565b604080518082018252601481527f5245564552545f574954485f434f4e5354414e54000000000000000000000000602082015290517f08c379a000000000000000000000000000000000000000000000000000000000815261042891906004016112d1565b6040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161042890611357565b6106146109e6565b6106146109fe565b604080518082018252601581527f524551554952455f574954485f434f4e5354414e540000000000000000000000602082015290517f08c379a000000000000000000000000000000000000000000000000000000000815261042891906004016112d1565b50929392505050565b600080546001019081905590565b610742610a1e565b50604080516080810182529182528051808201825260048082527f123456780000000000000000000000000000000000000000000000000000000060208381019190915280850192909252825180840184528181527f87654321000000000000000000000000000000000000000000000000000000008184015284840152825180840190935282527f616d65740000000000000000000000000000000000000000000000000000000090820152606082015290565b610431565b60010190565b600080546001019055565b600190565b60408051808201909152600581527f68656c6c6f0000000000000000000000000000000000000000000000000000006020820152600191565b606090565b7f61a6029a4c7ddee5824d171331eecbd015d26a271310a223718b837facb5b77160405161087d906112eb565b60405180910390a1565b61088f610a4c565b6040805160028082526060828101909352816020015b60608152602001906001900390816108a55790505090506040518060400160405280600581526020017f3078313233000000000000000000000000000000000000000000000000000000815250816000815181106108ff57fe5b60200260200101819052506040518060400160405280600581526020017f30783332310000000000000000000000000000000000000000000000000000008152508160018151811061094d57fe5b6020908102919091018101919091526040805160c0810182526005608082018181527f307831323300000000000000000000000000000000000000000000000000000060a0840152825281840152808201939093528051808201909152600381527f6162630000000000000000000000000000000000000000000000000000000000918101919091526060820152905090565b6104d290565b60405180602001604052806109f9610a7a565b905290565b6040518060400160405280610a11610a4c565b8152602001606081525090565b6040518060800160405280610a31610a8d565b81526020016060815260200160608152602001606081525090565b604051806080016040528060608152602001600063ffffffff16815260200160608152602001606081525090565b6040518060200160405280600081525090565b60405180606001604052806000815260200160608152602001606081525090565b600082601f830112610abe578081fd5b8135610ad1610acc8261156f565b611548565b8181529150602080830190840160005b83811015610b0e57610af98760208435890101610b73565b83526020928301929190910190600101610ae1565b5050505092915050565b600082601f830112610b28578081fd5b8135610b36610acc8261156f565b8181529150602080830190840160005b83811015610b0e57610b5e8760208435890101610bfa565b83526020928301929190910190600101610b46565b600082601f830112610b83578081fd5b813567ffffffffffffffff811115610b99578182fd5b610bca60207fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f84011601611548565b9150808252836020828501011115610be157600080fd5b8060208401602084013760009082016020015292915050565b600060808284031215610c0b578081fd5b610c156080611548565b9050813567ffffffffffffffff80821115610c2f57600080fd5b610c3b85838601610b73565b8352610c4a8560208601610ca1565b60208401526040840135915080821115610c6357600080fd5b610c6f85838601610aae565b60408401526060840135915080821115610c8857600080fd5b50610c9584828501610b73565b60608301525092915050565b803563ffffffff81168114610cb557600080fd5b92915050565b600080600080600060a08688031215610cd2578081fd5b8535610cdd816115bf565b945060208601359350604086013592506060860135610cfb816115bf565b949793965091946080013592915050565b60006020808385031215610d1e578182fd5b823567ffffffffffffffff811115610d34578283fd5b80840185601f820112610d45578384fd5b80359150610d55610acc8361156f565b82815283810190828501865b85811015610d8a57610d788a888435880101610b18565b84529286019290860190600101610d61565b509098975050505050505050565b60006020808385031215610daa578182fd5b823567ffffffffffffffff811115610dc0578283fd5b80840185601f820112610dd1578384fd5b80359150610de1610acc8361156f565b82815283810190828501865b85811015610d8a57610e048a888435880101610b73565b84529286019290860190600101610ded565b600060208284031215610e27578081fd5b813567ffffffffffffffff811115610e3d578182fd5b610e4984828501610b18565b949350505050565b60008060008060808587031215610e66578182fd5b84359350602085013560ff81168114610e7d578283fd5b93969395505050506040820135916060013590565b600060208284031215610ea3578081fd5b813567ffffffffffffffff811115610eb9578182fd5b610e4984828501610b73565b600060208284031215610ed6578081fd5b5035919050565b600060208284031215610eee578081fd5b813567ffffffffffffffff80821115610f05578283fd5b81840160608187031215610f17578384fd5b610f216060611548565b925080358352602081013582811115610f38578485fd5b610f4487828401610b73565b602085015250604081013582811115610f5b578485fd5b610f6787828401610b73565b6040850152509195945050505050565b600060208284031215610f88578081fd5b813567ffffffffffffffff80821115610f9f578283fd5b81840160408187031215610fb1578384fd5b610fbb6040611548565b9250803582811115610fcb578485fd5b610fd787828401610bfa565b845250602081013582811115610feb578485fd5b610ff787828401610b73565b6020850152509195945050505050565b600060208284031215611018578081fd5b813567ffffffffffffffff81111561102e578182fd5b610e4984828501610bfa565b60008060006060848603121561104e578081fd5b83359250602084013567ffffffffffffffff8082111561106c578283fd5b61107887838801610b73565b9350604086013591508082111561108d578283fd5b5061109a86828701610b73565b9150509250925092565b600081518084526110bc81602086016020860161158f565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169290920160200192915050565b600081516080845261110360808501826110a4565b6020915063ffffffff828501511682860152604084015185820360408701528181518084528484019150848582028501018584018794505b82851015611189577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08683030184526111758282516110a4565b60019590950194938701939150860161113b565b506060880151955088810360608a01526111a381876110a4565b9998505050505050505050565b600083516111c281846020880161158f565b9190910191825250602001919050565b73ffffffffffffffffffffffffffffffffffffffff91909116815260200190565b6000602080830181845280855180835260408601915060408482028701019250838701855b82811015611264577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc08886030184526112528583516110ee565b94509285019290850190600101611218565b5092979650505050505050565b93845260ff9290921660208401526040830152606082015260800190565b6000606082526112a260608301866110a4565b82810360208401526112b481866110a4565b83810360408501526112c681866110a4565b979650505050505050565b6000602082526112e460208301846110a4565b9392505050565b60408082526004908201527f123456780000000000000000000000000000000000000000000000000000000060608201526080602082018190526005908201527f6c6f72656d00000000000000000000000000000000000000000000000000000060a082015260c00190565b6020808252600d908201527f53494d504c455f52455645525400000000000000000000000000000000000000604082015260600190565b6020808252600e908201527f53494d504c455f52455155495245000000000000000000000000000000000000604082015260600190565b600060208252825160806020840152805160a08401526020810151606060c08501526113f56101008501826110a4565b604083015191507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff608582030160e086015261143081836110a4565b9250505060208401517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08085840301604086015261146e83836110a4565b604087015193508186820301606087015261148981856110a4565b9250506060860151925080858303016080860152506114a881836110a4565b95945050505050565b905151815260200190565b6000602082528251604060208401526114d860608401826110ee565b602085015191507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08482030160408501526114a881836110a4565b6000602082526112e460208301846110ee565b90815260200190565b600083825260406020830152610e4960408301846110a4565b60405181810167ffffffffffffffff8111828210171561156757600080fd5b604052919050565b600067ffffffffffffffff821115611585578081fd5b5060209081020190565b60005b838110156115aa578181015183820152602001611592565b838111156115b9576000848401525b50505050565b73ffffffffffffffffffffffffffffffffffffffff8116811461043357600080fdfea365627a7a72315820d4953afa8fe277a67a582a705ec911d7c404b5a84176ab0e36aa14da0e5986326c6578706572696d656e74616cf564736f6c63430005100040'; - public static contractName = 'AbiGenDummy'; - private readonly _methodABIIndex: { [name: string]: number } = {}; - private readonly _subscriptionManager: SubscriptionManager; - public static async deployFrom0xArtifactAsync( - artifact: ContractArtifact | SimpleContractArtifact, - supportedProvider: SupportedProvider, - txDefaults: Partial, - logDecodeDependencies: { [contractName: string]: ContractArtifact | SimpleContractArtifact }, - ): Promise { - assert.doesConformToSchema('txDefaults', txDefaults, schemas.txDataSchema, [ - schemas.addressSchema, - schemas.numberSchema, - schemas.jsNumber, - ]); - if (artifact.compilerOutput === undefined) { - throw new Error('Compiler output not found in the artifact file'); - } - const provider = providerUtils.standardizeOrThrow(supportedProvider); - const bytecode = artifact.compilerOutput.evm.bytecode.object; - const abi = artifact.compilerOutput.abi; - const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - if (Object.keys(logDecodeDependencies) !== undefined) { - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; - } - } - return AbiGenDummyContract.deployAsync(bytecode, abi, provider, txDefaults, logDecodeDependenciesAbiOnly); - } - - public static async deployWithLibrariesFrom0xArtifactAsync( - artifact: ContractArtifact, - libraryArtifacts: { [libraryName: string]: ContractArtifact }, - supportedProvider: SupportedProvider, - txDefaults: Partial, - logDecodeDependencies: { [contractName: string]: ContractArtifact | SimpleContractArtifact }, - ): Promise { - assert.doesConformToSchema('txDefaults', txDefaults, schemas.txDataSchema, [ - schemas.addressSchema, - schemas.numberSchema, - schemas.jsNumber, - ]); - if (artifact.compilerOutput === undefined) { - throw new Error('Compiler output not found in the artifact file'); - } - const provider = providerUtils.standardizeOrThrow(supportedProvider); - const abi = artifact.compilerOutput.abi; - const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - if (Object.keys(logDecodeDependencies) !== undefined) { - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; - } - } - const libraryAddresses = await AbiGenDummyContract._deployLibrariesAsync( - artifact, - libraryArtifacts, - new Web3Wrapper(provider), - txDefaults, - ); - const bytecode = linkLibrariesInBytecode(artifact, libraryAddresses); - return AbiGenDummyContract.deployAsync(bytecode, abi, provider, txDefaults, logDecodeDependenciesAbiOnly); - } - - public static async deployAsync( - bytecode: string, - abi: ContractAbi, - supportedProvider: SupportedProvider, - txDefaults: Partial, - logDecodeDependencies: { [contractName: string]: ContractAbi }, - ): Promise { - assert.isHexString('bytecode', bytecode); - assert.doesConformToSchema('txDefaults', txDefaults, schemas.txDataSchema, [ - schemas.addressSchema, - schemas.numberSchema, - schemas.jsNumber, - ]); - const provider = providerUtils.standardizeOrThrow(supportedProvider); - const constructorAbi = BaseContract._lookupConstructorAbi(abi); - [] = BaseContract._formatABIDataItemList(constructorAbi.inputs, [], BaseContract._bigNumberToString); - const iface = new ethers.utils.Interface(abi); - const deployInfo = iface.deployFunction; - const txData = deployInfo.encode(bytecode, []); - const web3Wrapper = new Web3Wrapper(provider); - const txDataWithDefaults = await BaseContract._applyDefaultsToContractTxDataAsync( - { - data: txData, - ...txDefaults, - }, - web3Wrapper.estimateGasAsync.bind(web3Wrapper), - ); - const txHash = await web3Wrapper.sendTransactionAsync(txDataWithDefaults); - logUtils.log(`transactionHash: ${txHash}`); - const txReceipt = await web3Wrapper.awaitTransactionSuccessAsync(txHash); - logUtils.log(`AbiGenDummy successfully deployed at ${txReceipt.contractAddress}`); - const contractInstance = new AbiGenDummyContract( - txReceipt.contractAddress as string, - provider, - txDefaults, - logDecodeDependencies, - ); - contractInstance.constructorArgs = []; - return contractInstance; - } - - /** - * @returns The contract ABI - */ - public static ABI(): ContractAbi { - const abi = [ - { - anonymous: false, - inputs: [ - { - name: 'someBytes', - type: 'bytes', - indexed: false, - }, - { - name: 'someString', - type: 'string', - indexed: false, - }, - ], - name: 'SimpleEvent', - outputs: [], - type: 'event', - }, - { - anonymous: false, - inputs: [ - { - name: '_owner', - type: 'address', - indexed: true, - }, - { - name: '_value', - type: 'uint256', - indexed: false, - }, - ], - name: 'Withdrawal', - outputs: [], - type: 'event', - }, - { - constant: true, - inputs: [ - { - name: 'a', - type: 'bytes[]', - }, - ], - name: 'acceptsAnArrayOfBytes', - outputs: [], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: true, - inputs: [ - { - name: 'a', - type: 'bytes', - }, - ], - name: 'acceptsBytes', - outputs: [], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: true, - inputs: [ - { - name: 'complexInput', - type: 'tuple', - components: [ - { - name: 'foo', - type: 'uint256', - }, - { - name: 'bar', - type: 'bytes', - }, - { - name: 'car', - type: 'string', - }, - ], - }, - ], - name: 'complexInputComplexOutput', - outputs: [ - { - name: '', - type: 'tuple', - components: [ - { - name: 'input', - type: 'tuple', - components: [ - { - name: 'foo', - type: 'uint256', - }, - { - name: 'bar', - type: 'bytes', - }, - { - name: 'car', - type: 'string', - }, - ], - }, - { - name: 'lorem', - type: 'bytes', - }, - { - name: 'ipsum', - type: 'bytes', - }, - { - name: 'dolor', - type: 'string', - }, - ], - }, - ], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: true, - inputs: [ - { - name: 'hash', - type: 'bytes32', - }, - { - name: 'v', - type: 'uint8', - }, - { - name: 'r', - type: 'bytes32', - }, - { - name: 's', - type: 'bytes32', - }, - ], - name: 'ecrecoverFn', - outputs: [ - { - name: 'signerAddress', - type: 'address', - }, - ], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: false, - inputs: [], - name: 'emitSimpleEvent', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', - }, - { - constant: true, - inputs: [ - { - name: 'index_0', - type: 'tuple[][]', - components: [ - { - name: 'someBytes', - type: 'bytes', - }, - { - name: 'anInteger', - type: 'uint32', - }, - { - name: 'aDynamicArrayOfBytes', - type: 'bytes[]', - }, - { - name: 'aString', - type: 'string', - }, - ], - }, - ], - name: 'methodAcceptingArrayOfArrayOfStructs', - outputs: [], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: true, - inputs: [ - { - name: 'index_0', - type: 'tuple[]', - components: [ - { - name: 'someBytes', - type: 'bytes', - }, - { - name: 'anInteger', - type: 'uint32', - }, - { - name: 'aDynamicArrayOfBytes', - type: 'bytes[]', - }, - { - name: 'aString', - type: 'string', - }, - ], - }, - ], - name: 'methodAcceptingArrayOfStructs', - outputs: [], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: true, - inputs: [], - name: 'methodReturningArrayOfStructs', - outputs: [ - { - name: '', - type: 'tuple[]', - components: [ - { - name: 'someBytes', - type: 'bytes', - }, - { - name: 'anInteger', - type: 'uint32', - }, - { - name: 'aDynamicArrayOfBytes', - type: 'bytes[]', - }, - { - name: 'aString', - type: 'string', - }, - ], - }, - ], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: true, - inputs: [], - name: 'methodReturningMultipleValues', - outputs: [ - { - name: '', - type: 'uint256', - }, - { - name: '', - type: 'string', - }, - ], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: true, - inputs: [], - name: 'methodUsingNestedStructWithInnerStructNotUsedElsewhere', - outputs: [ - { - name: '', - type: 'tuple', - components: [ - { - name: 'innerStruct', - type: 'tuple', - components: [ - { - name: 'aField', - type: 'uint256', - }, - ], - }, - ], - }, - ], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: true, - inputs: [ - { - name: 'index_0', - type: 'uint256', - }, - { - name: 'index_1', - type: 'bytes', - }, - { - name: 'index_2', - type: 'string', - }, - ], - name: 'multiInputMultiOutput', - outputs: [ - { - name: '', - type: 'bytes', - }, - { - name: '', - type: 'bytes', - }, - { - name: '', - type: 'string', - }, - ], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: true, - inputs: [ - { - name: 'n', - type: 'tuple', - components: [ - { - name: 'innerStruct', - type: 'tuple', - components: [ - { - name: 'someBytes', - type: 'bytes', - }, - { - name: 'anInteger', - type: 'uint32', - }, - { - name: 'aDynamicArrayOfBytes', - type: 'bytes[]', - }, - { - name: 'aString', - type: 'string', - }, - ], - }, - { - name: 'description', - type: 'string', - }, - ], - }, - ], - name: 'nestedStructInput', - outputs: [], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: true, - inputs: [], - name: 'nestedStructOutput', - outputs: [ - { - name: '', - type: 'tuple', - components: [ - { - name: 'innerStruct', - type: 'tuple', - components: [ - { - name: 'someBytes', - type: 'bytes', - }, - { - name: 'anInteger', - type: 'uint32', - }, - { - name: 'aDynamicArrayOfBytes', - type: 'bytes[]', - }, - { - name: 'aString', - type: 'string', - }, - ], - }, - { - name: 'description', - type: 'string', - }, - ], - }, - ], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: true, - inputs: [], - name: 'noInputNoOutput', - outputs: [], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: true, - inputs: [], - name: 'noInputSimpleOutput', - outputs: [ - { - name: '', - type: 'uint256', - }, - ], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: false, - inputs: [], - name: 'nonPureMethod', - outputs: [ - { - name: '', - type: 'uint256', - }, - ], - payable: false, - stateMutability: 'nonpayable', - type: 'function', - }, - { - constant: false, - inputs: [], - name: 'nonPureMethodThatReturnsNothing', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', - }, - { - constant: true, - inputs: [ - { - name: 'a', - type: 'string', - }, - ], - name: 'overloadedMethod', - outputs: [], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: true, - inputs: [ - { - name: 'a', - type: 'int256', - }, - ], - name: 'overloadedMethod', - outputs: [], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: true, - inputs: [], - name: 'pureFunctionWithConstant', - outputs: [ - { - name: 'someConstant', - type: 'uint256', - }, - ], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: true, - inputs: [], - name: 'requireWithConstant', - outputs: [], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: true, - inputs: [], - name: 'revertWithConstant', - outputs: [], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: true, - inputs: [ - { - name: 'index_0', - type: 'uint256', - }, - ], - name: 'simpleInputNoOutput', - outputs: [], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: true, - inputs: [ - { - name: 'index_0', - type: 'uint256', - }, - ], - name: 'simpleInputSimpleOutput', - outputs: [ - { - name: '', - type: 'uint256', - }, - ], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: true, - inputs: [], - name: 'simplePureFunction', - outputs: [ - { - name: 'result', - type: 'uint256', - }, - ], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: true, - inputs: [ - { - name: 'x', - type: 'uint256', - }, - ], - name: 'simplePureFunctionWithInput', - outputs: [ - { - name: 'sum', - type: 'uint256', - }, - ], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: true, - inputs: [], - name: 'simpleRequire', - outputs: [], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: true, - inputs: [], - name: 'simpleRevert', - outputs: [], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: true, - inputs: [ - { - name: 's', - type: 'tuple', - components: [ - { - name: 'someBytes', - type: 'bytes', - }, - { - name: 'anInteger', - type: 'uint32', - }, - { - name: 'aDynamicArrayOfBytes', - type: 'bytes[]', - }, - { - name: 'aString', - type: 'string', - }, - ], - }, - ], - name: 'structInput', - outputs: [], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: true, - inputs: [], - name: 'structOutput', - outputs: [ - { - name: 's', - type: 'tuple', - components: [ - { - name: 'someBytes', - type: 'bytes', - }, - { - name: 'anInteger', - type: 'uint32', - }, - { - name: 'aDynamicArrayOfBytes', - type: 'bytes[]', - }, - { - name: 'aString', - type: 'string', - }, - ], - }, - ], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: true, - inputs: [ - { - name: 'x', - type: 'address', - }, - { - name: 'a', - type: 'uint256', - }, - { - name: 'b', - type: 'uint256', - }, - { - name: 'y', - type: 'address', - }, - { - name: 'c', - type: 'uint256', - }, - ], - name: 'withAddressInput', - outputs: [ - { - name: 'z', - type: 'address', - }, - ], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: false, - inputs: [ - { - name: 'wad', - type: 'uint256', - }, - ], - name: 'withdraw', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', - }, - ] as ContractAbi; - return abi; - } - - protected static async _deployLibrariesAsync( - artifact: ContractArtifact, - libraryArtifacts: { [libraryName: string]: ContractArtifact }, - web3Wrapper: Web3Wrapper, - txDefaults: Partial, - libraryAddresses: { [libraryName: string]: string } = {}, - ): Promise<{ [libraryName: string]: string }> { - const links = artifact.compilerOutput.evm.bytecode.linkReferences; - // Go through all linked libraries, recursively deploying them if necessary. - for (const link of Object.values(links)) { - for (const libraryName of Object.keys(link)) { - if (!libraryAddresses[libraryName]) { - // Library not yet deployed. - const libraryArtifact = libraryArtifacts[libraryName]; - if (!libraryArtifact) { - throw new Error(`Missing artifact for linked library "${libraryName}"`); - } - // Deploy any dependent libraries used by this library. - await AbiGenDummyContract._deployLibrariesAsync( - libraryArtifact, - libraryArtifacts, - web3Wrapper, - txDefaults, - libraryAddresses, - ); - // Deploy this library. - const linkedLibraryBytecode = linkLibrariesInBytecode(libraryArtifact, libraryAddresses); - const txDataWithDefaults = await BaseContract._applyDefaultsToContractTxDataAsync( - { - data: linkedLibraryBytecode, - ...txDefaults, - }, - web3Wrapper.estimateGasAsync.bind(web3Wrapper), - ); - const txHash = await web3Wrapper.sendTransactionAsync(txDataWithDefaults); - logUtils.log(`transactionHash: ${txHash}`); - const { contractAddress } = await web3Wrapper.awaitTransactionSuccessAsync(txHash); - logUtils.log(`${libraryArtifact.contractName} successfully deployed at ${contractAddress}`); - libraryAddresses[libraryArtifact.contractName] = contractAddress as string; - } - } - } - return libraryAddresses; - } - - public getFunctionSignature(methodName: string): string { - const index = this._methodABIIndex[methodName]; - const methodAbi = AbiGenDummyContract.ABI()[index] as MethodAbi; // tslint:disable-line:no-unnecessary-type-assertion - const functionSignature = methodAbiToFunctionSignature(methodAbi); - return functionSignature; - } - - public getABIDecodedTransactionData(methodName: string, callData: string): T { - const functionSignature = this.getFunctionSignature(methodName); - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder(functionSignature); - const abiDecodedCallData = abiEncoder.strictDecode(callData); - return abiDecodedCallData; - } - - public getABIDecodedReturnData(methodName: string, callData: string): T { - const functionSignature = this.getFunctionSignature(methodName); - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder(functionSignature); - const abiDecodedCallData = abiEncoder.strictDecodeReturnValue(callData); - return abiDecodedCallData; - } - - public getSelector(methodName: string): string { - const functionSignature = this.getFunctionSignature(methodName); - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder(functionSignature); - return abiEncoder.getSelector(); - } - - /** - * a method that accepts an array of bytes - * @param a the array of bytes being accepted - */ - public acceptsAnArrayOfBytes(a: string[]): ContractFunctionObj { - const self = (this as any) as AbiGenDummyContract; - assert.isArray('a', a); - const functionSignature = 'acceptsAnArrayOfBytes(bytes[])'; - - return { - async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, [a]); - }, - }; - } - public acceptsBytes(a: string): ContractFunctionObj { - const self = (this as any) as AbiGenDummyContract; - assert.isString('a', a); - const functionSignature = 'acceptsBytes(bytes)'; - - return { - async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, [a]); - }, - }; - } - /** - * Tests decoding when the input and output are complex. - */ - public complexInputComplexOutput(complexInput: { - foo: BigNumber; - bar: string; - car: string; - }): ContractFunctionObj<{ - input: { foo: BigNumber; bar: string; car: string }; - lorem: string; - ipsum: string; - dolor: string; - }> { - const self = (this as any) as AbiGenDummyContract; - - const functionSignature = 'complexInputComplexOutput((uint256,bytes,string))'; - - return { - async callAsync( - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<{ - input: { foo: BigNumber; bar: string; car: string }; - lorem: string; - ipsum: string; - dolor: string; - }> { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue<{ - input: { foo: BigNumber; bar: string; car: string }; - lorem: string; - ipsum: string; - dolor: string; - }>(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, [complexInput]); - }, - }; - } - /** - * test that devdocs will be generated and - * that multiline devdocs will look okay - * @param hash description of some hash. Let's make this line super long to - * demonstrate hanging indents for method params. It has to be more than - * one hundred twenty columns. - * @param v some v, recovery id - * @param r ECDSA r output - * @param s ECDSA s output - * @returns the signerAddress that created this signature. this line too is super long in order to demonstrate the proper hanging indentation in generated code. - */ - public ecrecoverFn(hash: string, v: number | BigNumber, r: string, s: string): ContractFunctionObj { - const self = (this as any) as AbiGenDummyContract; - assert.isString('hash', hash); - assert.isNumberOrBigNumber('v', v); - assert.isString('r', r); - assert.isString('s', s); - const functionSignature = 'ecrecoverFn(bytes32,uint8,bytes32,bytes32)'; - - return { - async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, [hash, v, r, s]); - }, - }; - } - public emitSimpleEvent(): ContractTxFunctionObj { - const self = (this as any) as AbiGenDummyContract; - const functionSignature = 'emitSimpleEvent()'; - - return { - async sendTransactionAsync( - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - const txDataWithDefaults = await self._applyDefaultsToTxDataAsync( - { data: this.getABIEncodedTransactionData(), ...txData }, - this.estimateGasAsync.bind(this), - ); - if (opts.shouldValidate !== false) { - await this.callAsync(txDataWithDefaults); - } - return self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); - }, - awaitTransactionSuccessAsync( - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - return self._promiseWithTransactionHash(this.sendTransactionAsync(txData, opts), opts); - }, - async estimateGasAsync(txData?: Partial | undefined): Promise { - const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({ - data: this.getABIEncodedTransactionData(), - ...txData, - }); - return self._web3Wrapper.estimateGasAsync(txDataWithDefaults); - }, - async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { - BaseContract._assertCallParams(callData, defaultBlock); - const rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, []); - }, - }; - } - public methodAcceptingArrayOfArrayOfStructs( - index_0: Array<{ - someBytes: string; - anInteger: number | BigNumber; - aDynamicArrayOfBytes: string[]; - aString: string; - }>[], - ): ContractFunctionObj { - const self = (this as any) as AbiGenDummyContract; - assert.isArray('index_0', index_0); - const functionSignature = 'methodAcceptingArrayOfArrayOfStructs((bytes,uint32,bytes[],string)[][])'; - - return { - async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, [index_0]); - }, - }; - } - public methodAcceptingArrayOfStructs( - index_0: Array<{ - someBytes: string; - anInteger: number | BigNumber; - aDynamicArrayOfBytes: string[]; - aString: string; - }>, - ): ContractFunctionObj { - const self = (this as any) as AbiGenDummyContract; - assert.isArray('index_0', index_0); - const functionSignature = 'methodAcceptingArrayOfStructs((bytes,uint32,bytes[],string)[])'; - - return { - async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, [index_0]); - }, - }; - } - public methodReturningArrayOfStructs(): ContractFunctionObj< - Array<{ someBytes: string; anInteger: number; aDynamicArrayOfBytes: string[]; aString: string }> - > { - const self = (this as any) as AbiGenDummyContract; - const functionSignature = 'methodReturningArrayOfStructs()'; - - return { - async callAsync( - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise< - Array<{ someBytes: string; anInteger: number; aDynamicArrayOfBytes: string[]; aString: string }> - > { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue< - Array<{ someBytes: string; anInteger: number; aDynamicArrayOfBytes: string[]; aString: string }> - >(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, []); - }, - }; - } - public methodReturningMultipleValues(): ContractFunctionObj<[BigNumber, string]> { - const self = (this as any) as AbiGenDummyContract; - const functionSignature = 'methodReturningMultipleValues()'; - - return { - async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise<[BigNumber, string]> { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue<[BigNumber, string]>(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, []); - }, - }; - } - public methodUsingNestedStructWithInnerStructNotUsedElsewhere(): ContractFunctionObj<{ - innerStruct: { aField: BigNumber }; - }> { - const self = (this as any) as AbiGenDummyContract; - const functionSignature = 'methodUsingNestedStructWithInnerStructNotUsedElsewhere()'; - - return { - async callAsync( - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<{ innerStruct: { aField: BigNumber } }> { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue<{ innerStruct: { aField: BigNumber } }>(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, []); - }, - }; - } - /** - * Tests decoding when the input and output are complex and have more than one argument. - */ - public multiInputMultiOutput( - index_0: BigNumber, - index_1: string, - index_2: string, - ): ContractFunctionObj<[string, string, string]> { - const self = (this as any) as AbiGenDummyContract; - assert.isBigNumber('index_0', index_0); - assert.isString('index_1', index_1); - assert.isString('index_2', index_2); - const functionSignature = 'multiInputMultiOutput(uint256,bytes,string)'; - - return { - async callAsync( - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[string, string, string]> { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue<[string, string, string]>(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, [index_0, index_1, index_2]); - }, - }; - } - public nestedStructInput(n: { - innerStruct: { - someBytes: string; - anInteger: number | BigNumber; - aDynamicArrayOfBytes: string[]; - aString: string; - }; - description: string; - }): ContractFunctionObj { - const self = (this as any) as AbiGenDummyContract; - - const functionSignature = 'nestedStructInput(((bytes,uint32,bytes[],string),string))'; - - return { - async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, [n]); - }, - }; - } - public nestedStructOutput(): ContractFunctionObj<{ - innerStruct: { someBytes: string; anInteger: number; aDynamicArrayOfBytes: string[]; aString: string }; - description: string; - }> { - const self = (this as any) as AbiGenDummyContract; - const functionSignature = 'nestedStructOutput()'; - - return { - async callAsync( - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<{ - innerStruct: { someBytes: string; anInteger: number; aDynamicArrayOfBytes: string[]; aString: string }; - description: string; - }> { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue<{ - innerStruct: { - someBytes: string; - anInteger: number; - aDynamicArrayOfBytes: string[]; - aString: string; - }; - description: string; - }>(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, []); - }, - }; - } - /** - * Tests decoding when both input and output are empty. - */ - public noInputNoOutput(): ContractFunctionObj { - const self = (this as any) as AbiGenDummyContract; - const functionSignature = 'noInputNoOutput()'; - - return { - async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, []); - }, - }; - } - /** - * Tests decoding when input is empty and output is non-empty. - */ - public noInputSimpleOutput(): ContractFunctionObj { - const self = (this as any) as AbiGenDummyContract; - const functionSignature = 'noInputSimpleOutput()'; - - return { - async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, []); - }, - }; - } - public nonPureMethod(): ContractTxFunctionObj { - const self = (this as any) as AbiGenDummyContract; - const functionSignature = 'nonPureMethod()'; - - return { - async sendTransactionAsync( - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - const txDataWithDefaults = await self._applyDefaultsToTxDataAsync( - { data: this.getABIEncodedTransactionData(), ...txData }, - this.estimateGasAsync.bind(this), - ); - if (opts.shouldValidate !== false) { - await this.callAsync(txDataWithDefaults); - } - return self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); - }, - awaitTransactionSuccessAsync( - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - return self._promiseWithTransactionHash(this.sendTransactionAsync(txData, opts), opts); - }, - async estimateGasAsync(txData?: Partial | undefined): Promise { - const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({ - data: this.getABIEncodedTransactionData(), - ...txData, - }); - return self._web3Wrapper.estimateGasAsync(txDataWithDefaults); - }, - async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { - BaseContract._assertCallParams(callData, defaultBlock); - const rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, []); - }, - }; - } - public nonPureMethodThatReturnsNothing(): ContractTxFunctionObj { - const self = (this as any) as AbiGenDummyContract; - const functionSignature = 'nonPureMethodThatReturnsNothing()'; - - return { - async sendTransactionAsync( - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - const txDataWithDefaults = await self._applyDefaultsToTxDataAsync( - { data: this.getABIEncodedTransactionData(), ...txData }, - this.estimateGasAsync.bind(this), - ); - if (opts.shouldValidate !== false) { - await this.callAsync(txDataWithDefaults); - } - return self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); - }, - awaitTransactionSuccessAsync( - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - return self._promiseWithTransactionHash(this.sendTransactionAsync(txData, opts), opts); - }, - async estimateGasAsync(txData?: Partial | undefined): Promise { - const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({ - data: this.getABIEncodedTransactionData(), - ...txData, - }); - return self._web3Wrapper.estimateGasAsync(txDataWithDefaults); - }, - async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { - BaseContract._assertCallParams(callData, defaultBlock); - const rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, []); - }, - }; - } - public overloadedMethod2(a: string): ContractFunctionObj { - const self = (this as any) as AbiGenDummyContract; - assert.isString('a', a); - const functionSignature = 'overloadedMethod(string)'; - - return { - async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, [a]); - }, - }; - } - public overloadedMethod1(a: BigNumber): ContractFunctionObj { - const self = (this as any) as AbiGenDummyContract; - assert.isBigNumber('a', a); - const functionSignature = 'overloadedMethod(int256)'; - - return { - async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, [a]); - }, - }; - } - public pureFunctionWithConstant(): ContractFunctionObj { - const self = (this as any) as AbiGenDummyContract; - const functionSignature = 'pureFunctionWithConstant()'; - - return { - async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, []); - }, - }; - } - public requireWithConstant(): ContractFunctionObj { - const self = (this as any) as AbiGenDummyContract; - const functionSignature = 'requireWithConstant()'; - - return { - async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, []); - }, - }; - } - public revertWithConstant(): ContractFunctionObj { - const self = (this as any) as AbiGenDummyContract; - const functionSignature = 'revertWithConstant()'; - - return { - async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, []); - }, - }; - } - /** - * Tests decoding when input is not empty but output is empty. - */ - public simpleInputNoOutput(index_0: BigNumber): ContractFunctionObj { - const self = (this as any) as AbiGenDummyContract; - assert.isBigNumber('index_0', index_0); - const functionSignature = 'simpleInputNoOutput(uint256)'; - - return { - async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, [index_0]); - }, - }; - } - /** - * Tests decoding when both input and output are non-empty. - */ - public simpleInputSimpleOutput(index_0: BigNumber): ContractFunctionObj { - const self = (this as any) as AbiGenDummyContract; - assert.isBigNumber('index_0', index_0); - const functionSignature = 'simpleInputSimpleOutput(uint256)'; - - return { - async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, [index_0]); - }, - }; - } - public simplePureFunction(): ContractFunctionObj { - const self = (this as any) as AbiGenDummyContract; - const functionSignature = 'simplePureFunction()'; - - return { - async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, []); - }, - }; - } - public simplePureFunctionWithInput(x: BigNumber): ContractFunctionObj { - const self = (this as any) as AbiGenDummyContract; - assert.isBigNumber('x', x); - const functionSignature = 'simplePureFunctionWithInput(uint256)'; - - return { - async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, [x]); - }, - }; - } - public simpleRequire(): ContractFunctionObj { - const self = (this as any) as AbiGenDummyContract; - const functionSignature = 'simpleRequire()'; - - return { - async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, []); - }, - }; - } - public simpleRevert(): ContractFunctionObj { - const self = (this as any) as AbiGenDummyContract; - const functionSignature = 'simpleRevert()'; - - return { - async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, []); - }, - }; - } - public structInput(s: { - someBytes: string; - anInteger: number | BigNumber; - aDynamicArrayOfBytes: string[]; - aString: string; - }): ContractFunctionObj { - const self = (this as any) as AbiGenDummyContract; - - const functionSignature = 'structInput((bytes,uint32,bytes[],string))'; - - return { - async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, [s]); - }, - }; - } - /** - * a method that returns a struct - * @returns a Struct struct - */ - public structOutput(): ContractFunctionObj<{ - someBytes: string; - anInteger: number; - aDynamicArrayOfBytes: string[]; - aString: string; - }> { - const self = (this as any) as AbiGenDummyContract; - const functionSignature = 'structOutput()'; - - return { - async callAsync( - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<{ someBytes: string; anInteger: number; aDynamicArrayOfBytes: string[]; aString: string }> { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue<{ - someBytes: string; - anInteger: number; - aDynamicArrayOfBytes: string[]; - aString: string; - }>(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, []); - }, - }; - } - public withAddressInput( - x: string, - a: BigNumber, - b: BigNumber, - y: string, - c: BigNumber, - ): ContractFunctionObj { - const self = (this as any) as AbiGenDummyContract; - assert.isString('x', x); - assert.isBigNumber('a', a); - assert.isBigNumber('b', b); - assert.isString('y', y); - assert.isBigNumber('c', c); - const functionSignature = 'withAddressInput(address,uint256,uint256,address,uint256)'; - - return { - async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, [x.toLowerCase(), a, b, y.toLowerCase(), c]); - }, - }; - } - public withdraw(wad: BigNumber): ContractTxFunctionObj { - const self = (this as any) as AbiGenDummyContract; - assert.isBigNumber('wad', wad); - const functionSignature = 'withdraw(uint256)'; - - return { - async sendTransactionAsync( - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - const txDataWithDefaults = await self._applyDefaultsToTxDataAsync( - { data: this.getABIEncodedTransactionData(), ...txData }, - this.estimateGasAsync.bind(this), - ); - if (opts.shouldValidate !== false) { - await this.callAsync(txDataWithDefaults); - } - return self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); - }, - awaitTransactionSuccessAsync( - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - return self._promiseWithTransactionHash(this.sendTransactionAsync(txData, opts), opts); - }, - async estimateGasAsync(txData?: Partial | undefined): Promise { - const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({ - data: this.getABIEncodedTransactionData(), - ...txData, - }); - return self._web3Wrapper.estimateGasAsync(txDataWithDefaults); - }, - async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { - BaseContract._assertCallParams(callData, defaultBlock); - const rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, [wad]); - }, - }; - } - - /** - * Subscribe to an event type emitted by the AbiGenDummy contract. - * @param eventName The AbiGenDummy contract event you would like to subscribe to. - * @param indexFilterValues An object where the keys are indexed args returned by the event and - * the value is the value you are interested in. E.g `{maker: aUserAddressHex}` - * @param callback Callback that gets called when a log is added/removed - * @param isVerbose Enable verbose subscription warnings (e.g recoverable network issues encountered) - * @return Subscription token used later to unsubscribe - */ - public subscribe( - eventName: AbiGenDummyEvents, - indexFilterValues: IndexedFilterValues, - callback: EventCallback, - isVerbose: boolean = false, - blockPollingIntervalMs?: number, - ): string { - assert.doesBelongToStringEnum('eventName', eventName, AbiGenDummyEvents); - assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); - assert.isFunction('callback', callback); - const subscriptionToken = this._subscriptionManager.subscribe( - this.address, - eventName, - indexFilterValues, - AbiGenDummyContract.ABI(), - callback, - isVerbose, - blockPollingIntervalMs, - ); - return subscriptionToken; - } - - /** - * Cancel a subscription - * @param subscriptionToken Subscription token returned by `subscribe()` - */ - public unsubscribe(subscriptionToken: string): void { - this._subscriptionManager.unsubscribe(subscriptionToken); - } - - /** - * Cancels all existing subscriptions - */ - public unsubscribeAll(): void { - this._subscriptionManager.unsubscribeAll(); - } - - /** - * Gets historical logs without creating a subscription - * @param eventName The AbiGenDummy contract event you would like to subscribe to. - * @param blockRange Block range to get logs from. - * @param indexFilterValues An object where the keys are indexed args returned by the event and - * the value is the value you are interested in. E.g `{_from: aUserAddressHex}` - * @return Array of logs that match the parameters - */ - public async getLogsAsync( - eventName: AbiGenDummyEvents, - blockRange: BlockRange, - indexFilterValues: IndexedFilterValues, - ): Promise>> { - assert.doesBelongToStringEnum('eventName', eventName, AbiGenDummyEvents); - assert.doesConformToSchema('blockRange', blockRange, schemas.blockRangeSchema); - assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); - const logs = await this._subscriptionManager.getLogsAsync( - this.address, - eventName, - blockRange, - indexFilterValues, - AbiGenDummyContract.ABI(), - ); - return logs; - } - - constructor( - address: string, - supportedProvider: SupportedProvider, - txDefaults?: Partial, - logDecodeDependencies?: { [contractName: string]: ContractAbi }, - deployedBytecode: string | undefined = AbiGenDummyContract.deployedBytecode, - ) { - super( - 'AbiGenDummy', - AbiGenDummyContract.ABI(), - address, - supportedProvider, - txDefaults, - logDecodeDependencies, - deployedBytecode, - ); - classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); - this._subscriptionManager = new SubscriptionManager( - AbiGenDummyContract.ABI(), - this._web3Wrapper, - ); - AbiGenDummyContract.ABI().forEach((item, index) => { - if (item.type === 'function') { - const methodAbi = item as MethodAbi; - this._methodABIIndex[methodAbi.name] = index; - } - }); - } -} - -// tslint:disable:max-file-line-count -// tslint:enable:no-unbound-method no-parameter-reassignment no-consecutive-blank-lines ordered-imports align -// tslint:enable:trailing-comma whitespace no-trailing-whitespace diff --git a/packages/abi-gen/test-cli/output/typescript/lib_dummy.ts b/packages/abi-gen/test-cli/output/typescript/lib_dummy.ts deleted file mode 100644 index ae07b236b3..0000000000 --- a/packages/abi-gen/test-cli/output/typescript/lib_dummy.ts +++ /dev/null @@ -1,258 +0,0 @@ -// tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma enum-naming -// tslint:disable:whitespace no-unbound-method no-trailing-whitespace -// tslint:disable:no-unused-variable -import { - AwaitTransactionSuccessOpts, - ContractFunctionObj, - ContractTxFunctionObj, - SendTransactionOpts, - BaseContract, - PromiseWithTransactionHash, - methodAbiToFunctionSignature, - linkLibrariesInBytecode, -} from '@0x/base-contract'; -import { schemas } from '@0x/json-schemas'; -import { - BlockParam, - BlockParamLiteral, - BlockRange, - CallData, - ContractAbi, - ContractArtifact, - DecodedLogArgs, - MethodAbi, - TransactionReceiptWithDecodedLogs, - TxData, - TxDataPayable, - SupportedProvider, -} from 'ethereum-types'; -import { BigNumber, classUtils, hexUtils, logUtils, providerUtils } from '@0x/utils'; -import { EventCallback, IndexedFilterValues, SimpleContractArtifact } from '@0x/types'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import { assert } from '@0x/assert'; -import * as ethers from 'ethers'; -// tslint:enable:no-unused-variable - -/* istanbul ignore next */ -// tslint:disable:array-type -// tslint:disable:no-parameter-reassignment -// tslint:disable-next-line:class-name -export class LibDummyContract extends BaseContract { - /** - * @ignore - */ - public static deployedBytecode: string | undefined; - public static contractName = 'LibDummy'; - private readonly _methodABIIndex: { [name: string]: number } = {}; - public static async deployFrom0xArtifactAsync( - artifact: ContractArtifact | SimpleContractArtifact, - supportedProvider: SupportedProvider, - txDefaults: Partial, - logDecodeDependencies: { [contractName: string]: ContractArtifact | SimpleContractArtifact }, - ): Promise { - assert.doesConformToSchema('txDefaults', txDefaults, schemas.txDataSchema, [ - schemas.addressSchema, - schemas.numberSchema, - schemas.jsNumber, - ]); - if (artifact.compilerOutput === undefined) { - throw new Error('Compiler output not found in the artifact file'); - } - const provider = providerUtils.standardizeOrThrow(supportedProvider); - const bytecode = artifact.compilerOutput.evm.bytecode.object; - const abi = artifact.compilerOutput.abi; - const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - if (Object.keys(logDecodeDependencies) !== undefined) { - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; - } - } - return LibDummyContract.deployAsync(bytecode, abi, provider, txDefaults, logDecodeDependenciesAbiOnly); - } - - public static async deployWithLibrariesFrom0xArtifactAsync( - artifact: ContractArtifact, - libraryArtifacts: { [libraryName: string]: ContractArtifact }, - supportedProvider: SupportedProvider, - txDefaults: Partial, - logDecodeDependencies: { [contractName: string]: ContractArtifact | SimpleContractArtifact }, - ): Promise { - assert.doesConformToSchema('txDefaults', txDefaults, schemas.txDataSchema, [ - schemas.addressSchema, - schemas.numberSchema, - schemas.jsNumber, - ]); - if (artifact.compilerOutput === undefined) { - throw new Error('Compiler output not found in the artifact file'); - } - const provider = providerUtils.standardizeOrThrow(supportedProvider); - const abi = artifact.compilerOutput.abi; - const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - if (Object.keys(logDecodeDependencies) !== undefined) { - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; - } - } - const libraryAddresses = await LibDummyContract._deployLibrariesAsync( - artifact, - libraryArtifacts, - new Web3Wrapper(provider), - txDefaults, - ); - const bytecode = linkLibrariesInBytecode(artifact, libraryAddresses); - return LibDummyContract.deployAsync(bytecode, abi, provider, txDefaults, logDecodeDependenciesAbiOnly); - } - - public static async deployAsync( - bytecode: string, - abi: ContractAbi, - supportedProvider: SupportedProvider, - txDefaults: Partial, - logDecodeDependencies: { [contractName: string]: ContractAbi }, - ): Promise { - assert.isHexString('bytecode', bytecode); - assert.doesConformToSchema('txDefaults', txDefaults, schemas.txDataSchema, [ - schemas.addressSchema, - schemas.numberSchema, - schemas.jsNumber, - ]); - const provider = providerUtils.standardizeOrThrow(supportedProvider); - const constructorAbi = BaseContract._lookupConstructorAbi(abi); - [] = BaseContract._formatABIDataItemList(constructorAbi.inputs, [], BaseContract._bigNumberToString); - const iface = new ethers.utils.Interface(abi); - const deployInfo = iface.deployFunction; - const txData = deployInfo.encode(bytecode, []); - const web3Wrapper = new Web3Wrapper(provider); - const txDataWithDefaults = await BaseContract._applyDefaultsToContractTxDataAsync( - { - data: txData, - ...txDefaults, - }, - web3Wrapper.estimateGasAsync.bind(web3Wrapper), - ); - const txHash = await web3Wrapper.sendTransactionAsync(txDataWithDefaults); - logUtils.log(`transactionHash: ${txHash}`); - const txReceipt = await web3Wrapper.awaitTransactionSuccessAsync(txHash); - logUtils.log(`LibDummy successfully deployed at ${txReceipt.contractAddress}`); - const contractInstance = new LibDummyContract( - txReceipt.contractAddress as string, - provider, - txDefaults, - logDecodeDependencies, - ); - contractInstance.constructorArgs = []; - return contractInstance; - } - - /** - * @returns The contract ABI - */ - public static ABI(): ContractAbi { - const abi = [] as ContractAbi; - return abi; - } - - protected static async _deployLibrariesAsync( - artifact: ContractArtifact, - libraryArtifacts: { [libraryName: string]: ContractArtifact }, - web3Wrapper: Web3Wrapper, - txDefaults: Partial, - libraryAddresses: { [libraryName: string]: string } = {}, - ): Promise<{ [libraryName: string]: string }> { - const links = artifact.compilerOutput.evm.bytecode.linkReferences; - // Go through all linked libraries, recursively deploying them if necessary. - for (const link of Object.values(links)) { - for (const libraryName of Object.keys(link)) { - if (!libraryAddresses[libraryName]) { - // Library not yet deployed. - const libraryArtifact = libraryArtifacts[libraryName]; - if (!libraryArtifact) { - throw new Error(`Missing artifact for linked library "${libraryName}"`); - } - // Deploy any dependent libraries used by this library. - await LibDummyContract._deployLibrariesAsync( - libraryArtifact, - libraryArtifacts, - web3Wrapper, - txDefaults, - libraryAddresses, - ); - // Deploy this library. - const linkedLibraryBytecode = linkLibrariesInBytecode(libraryArtifact, libraryAddresses); - const txDataWithDefaults = await BaseContract._applyDefaultsToContractTxDataAsync( - { - data: linkedLibraryBytecode, - ...txDefaults, - }, - web3Wrapper.estimateGasAsync.bind(web3Wrapper), - ); - const txHash = await web3Wrapper.sendTransactionAsync(txDataWithDefaults); - logUtils.log(`transactionHash: ${txHash}`); - const { contractAddress } = await web3Wrapper.awaitTransactionSuccessAsync(txHash); - logUtils.log(`${libraryArtifact.contractName} successfully deployed at ${contractAddress}`); - libraryAddresses[libraryArtifact.contractName] = contractAddress as string; - } - } - } - return libraryAddresses; - } - - public getFunctionSignature(methodName: string): string { - const index = this._methodABIIndex[methodName]; - const methodAbi = LibDummyContract.ABI()[index] as MethodAbi; // tslint:disable-line:no-unnecessary-type-assertion - const functionSignature = methodAbiToFunctionSignature(methodAbi); - return functionSignature; - } - - public getABIDecodedTransactionData(methodName: string, callData: string): T { - const functionSignature = this.getFunctionSignature(methodName); - const self = (this as any) as LibDummyContract; - const abiEncoder = self._lookupAbiEncoder(functionSignature); - const abiDecodedCallData = abiEncoder.strictDecode(callData); - return abiDecodedCallData; - } - - public getABIDecodedReturnData(methodName: string, callData: string): T { - const functionSignature = this.getFunctionSignature(methodName); - const self = (this as any) as LibDummyContract; - const abiEncoder = self._lookupAbiEncoder(functionSignature); - const abiDecodedCallData = abiEncoder.strictDecodeReturnValue(callData); - return abiDecodedCallData; - } - - public getSelector(methodName: string): string { - const functionSignature = this.getFunctionSignature(methodName); - const self = (this as any) as LibDummyContract; - const abiEncoder = self._lookupAbiEncoder(functionSignature); - return abiEncoder.getSelector(); - } - - constructor( - address: string, - supportedProvider: SupportedProvider, - txDefaults?: Partial, - logDecodeDependencies?: { [contractName: string]: ContractAbi }, - deployedBytecode: string | undefined = LibDummyContract.deployedBytecode, - ) { - super( - 'LibDummy', - LibDummyContract.ABI(), - address, - supportedProvider, - txDefaults, - logDecodeDependencies, - deployedBytecode, - ); - classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); - LibDummyContract.ABI().forEach((item, index) => { - if (item.type === 'function') { - const methodAbi = item as MethodAbi; - this._methodABIIndex[methodAbi.name] = index; - } - }); - } -} - -// tslint:disable:max-file-line-count -// tslint:enable:no-unbound-method no-parameter-reassignment no-consecutive-blank-lines ordered-imports align -// tslint:enable:trailing-comma whitespace no-trailing-whitespace diff --git a/packages/abi-gen/test-cli/output/typescript/test_lib_dummy.ts b/packages/abi-gen/test-cli/output/typescript/test_lib_dummy.ts deleted file mode 100644 index 3f6c20e62b..0000000000 --- a/packages/abi-gen/test-cli/output/typescript/test_lib_dummy.ts +++ /dev/null @@ -1,351 +0,0 @@ -// tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma enum-naming -// tslint:disable:whitespace no-unbound-method no-trailing-whitespace -// tslint:disable:no-unused-variable -import { - AwaitTransactionSuccessOpts, - ContractFunctionObj, - ContractTxFunctionObj, - SendTransactionOpts, - BaseContract, - PromiseWithTransactionHash, - methodAbiToFunctionSignature, - linkLibrariesInBytecode, -} from '@0x/base-contract'; -import { schemas } from '@0x/json-schemas'; -import { - BlockParam, - BlockParamLiteral, - BlockRange, - CallData, - ContractAbi, - ContractArtifact, - DecodedLogArgs, - MethodAbi, - TransactionReceiptWithDecodedLogs, - TxData, - TxDataPayable, - SupportedProvider, -} from 'ethereum-types'; -import { BigNumber, classUtils, hexUtils, logUtils, providerUtils } from '@0x/utils'; -import { EventCallback, IndexedFilterValues, SimpleContractArtifact } from '@0x/types'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import { assert } from '@0x/assert'; -import * as ethers from 'ethers'; -// tslint:enable:no-unused-variable - -/* istanbul ignore next */ -// tslint:disable:array-type -// tslint:disable:no-parameter-reassignment -// tslint:disable-next-line:class-name -export class TestLibDummyContract extends BaseContract { - /** - * @ignore - */ - public static deployedBytecode = - '0x6080604052348015600f57600080fd5b506004361060325760003560e01c806322935e921460375780632b82fdf0146063575b600080fd5b605160048036036020811015604b57600080fd5b5035607d565b60408051918252519081900360200190f35b605160048036036020811015607757600080fd5b5035608c565b60006086826095565b92915050565b6000608682609c565b6104d20190565b6001019056fea265627a7a72315820863e53f0da474a1275d583d88852313fe053941e79bddd5279abd812b31e020c64736f6c634300050c0032'; - public static contractName = 'TestLibDummy'; - private readonly _methodABIIndex: { [name: string]: number } = {}; - public static async deployFrom0xArtifactAsync( - artifact: ContractArtifact | SimpleContractArtifact, - supportedProvider: SupportedProvider, - txDefaults: Partial, - logDecodeDependencies: { [contractName: string]: ContractArtifact | SimpleContractArtifact }, - ): Promise { - assert.doesConformToSchema('txDefaults', txDefaults, schemas.txDataSchema, [ - schemas.addressSchema, - schemas.numberSchema, - schemas.jsNumber, - ]); - if (artifact.compilerOutput === undefined) { - throw new Error('Compiler output not found in the artifact file'); - } - const provider = providerUtils.standardizeOrThrow(supportedProvider); - const bytecode = artifact.compilerOutput.evm.bytecode.object; - const abi = artifact.compilerOutput.abi; - const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - if (Object.keys(logDecodeDependencies) !== undefined) { - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; - } - } - return TestLibDummyContract.deployAsync(bytecode, abi, provider, txDefaults, logDecodeDependenciesAbiOnly); - } - - public static async deployWithLibrariesFrom0xArtifactAsync( - artifact: ContractArtifact, - libraryArtifacts: { [libraryName: string]: ContractArtifact }, - supportedProvider: SupportedProvider, - txDefaults: Partial, - logDecodeDependencies: { [contractName: string]: ContractArtifact | SimpleContractArtifact }, - ): Promise { - assert.doesConformToSchema('txDefaults', txDefaults, schemas.txDataSchema, [ - schemas.addressSchema, - schemas.numberSchema, - schemas.jsNumber, - ]); - if (artifact.compilerOutput === undefined) { - throw new Error('Compiler output not found in the artifact file'); - } - const provider = providerUtils.standardizeOrThrow(supportedProvider); - const abi = artifact.compilerOutput.abi; - const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - if (Object.keys(logDecodeDependencies) !== undefined) { - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; - } - } - const libraryAddresses = await TestLibDummyContract._deployLibrariesAsync( - artifact, - libraryArtifacts, - new Web3Wrapper(provider), - txDefaults, - ); - const bytecode = linkLibrariesInBytecode(artifact, libraryAddresses); - return TestLibDummyContract.deployAsync(bytecode, abi, provider, txDefaults, logDecodeDependenciesAbiOnly); - } - - public static async deployAsync( - bytecode: string, - abi: ContractAbi, - supportedProvider: SupportedProvider, - txDefaults: Partial, - logDecodeDependencies: { [contractName: string]: ContractAbi }, - ): Promise { - assert.isHexString('bytecode', bytecode); - assert.doesConformToSchema('txDefaults', txDefaults, schemas.txDataSchema, [ - schemas.addressSchema, - schemas.numberSchema, - schemas.jsNumber, - ]); - const provider = providerUtils.standardizeOrThrow(supportedProvider); - const constructorAbi = BaseContract._lookupConstructorAbi(abi); - [] = BaseContract._formatABIDataItemList(constructorAbi.inputs, [], BaseContract._bigNumberToString); - const iface = new ethers.utils.Interface(abi); - const deployInfo = iface.deployFunction; - const txData = deployInfo.encode(bytecode, []); - const web3Wrapper = new Web3Wrapper(provider); - const txDataWithDefaults = await BaseContract._applyDefaultsToContractTxDataAsync( - { - data: txData, - ...txDefaults, - }, - web3Wrapper.estimateGasAsync.bind(web3Wrapper), - ); - const txHash = await web3Wrapper.sendTransactionAsync(txDataWithDefaults); - logUtils.log(`transactionHash: ${txHash}`); - const txReceipt = await web3Wrapper.awaitTransactionSuccessAsync(txHash); - logUtils.log(`TestLibDummy successfully deployed at ${txReceipt.contractAddress}`); - const contractInstance = new TestLibDummyContract( - txReceipt.contractAddress as string, - provider, - txDefaults, - logDecodeDependencies, - ); - contractInstance.constructorArgs = []; - return contractInstance; - } - - /** - * @returns The contract ABI - */ - public static ABI(): ContractAbi { - const abi = [ - { - constant: true, - inputs: [ - { - name: 'x', - type: 'uint256', - }, - ], - name: 'publicAddConstant', - outputs: [ - { - name: 'result', - type: 'uint256', - }, - ], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - { - constant: true, - inputs: [ - { - name: 'x', - type: 'uint256', - }, - ], - name: 'publicAddOne', - outputs: [ - { - name: 'result', - type: 'uint256', - }, - ], - payable: false, - stateMutability: 'pure', - type: 'function', - }, - ] as ContractAbi; - return abi; - } - - protected static async _deployLibrariesAsync( - artifact: ContractArtifact, - libraryArtifacts: { [libraryName: string]: ContractArtifact }, - web3Wrapper: Web3Wrapper, - txDefaults: Partial, - libraryAddresses: { [libraryName: string]: string } = {}, - ): Promise<{ [libraryName: string]: string }> { - const links = artifact.compilerOutput.evm.bytecode.linkReferences; - // Go through all linked libraries, recursively deploying them if necessary. - for (const link of Object.values(links)) { - for (const libraryName of Object.keys(link)) { - if (!libraryAddresses[libraryName]) { - // Library not yet deployed. - const libraryArtifact = libraryArtifacts[libraryName]; - if (!libraryArtifact) { - throw new Error(`Missing artifact for linked library "${libraryName}"`); - } - // Deploy any dependent libraries used by this library. - await TestLibDummyContract._deployLibrariesAsync( - libraryArtifact, - libraryArtifacts, - web3Wrapper, - txDefaults, - libraryAddresses, - ); - // Deploy this library. - const linkedLibraryBytecode = linkLibrariesInBytecode(libraryArtifact, libraryAddresses); - const txDataWithDefaults = await BaseContract._applyDefaultsToContractTxDataAsync( - { - data: linkedLibraryBytecode, - ...txDefaults, - }, - web3Wrapper.estimateGasAsync.bind(web3Wrapper), - ); - const txHash = await web3Wrapper.sendTransactionAsync(txDataWithDefaults); - logUtils.log(`transactionHash: ${txHash}`); - const { contractAddress } = await web3Wrapper.awaitTransactionSuccessAsync(txHash); - logUtils.log(`${libraryArtifact.contractName} successfully deployed at ${contractAddress}`); - libraryAddresses[libraryArtifact.contractName] = contractAddress as string; - } - } - } - return libraryAddresses; - } - - public getFunctionSignature(methodName: string): string { - const index = this._methodABIIndex[methodName]; - const methodAbi = TestLibDummyContract.ABI()[index] as MethodAbi; // tslint:disable-line:no-unnecessary-type-assertion - const functionSignature = methodAbiToFunctionSignature(methodAbi); - return functionSignature; - } - - public getABIDecodedTransactionData(methodName: string, callData: string): T { - const functionSignature = this.getFunctionSignature(methodName); - const self = (this as any) as TestLibDummyContract; - const abiEncoder = self._lookupAbiEncoder(functionSignature); - const abiDecodedCallData = abiEncoder.strictDecode(callData); - return abiDecodedCallData; - } - - public getABIDecodedReturnData(methodName: string, callData: string): T { - const functionSignature = this.getFunctionSignature(methodName); - const self = (this as any) as TestLibDummyContract; - const abiEncoder = self._lookupAbiEncoder(functionSignature); - const abiDecodedCallData = abiEncoder.strictDecodeReturnValue(callData); - return abiDecodedCallData; - } - - public getSelector(methodName: string): string { - const functionSignature = this.getFunctionSignature(methodName); - const self = (this as any) as TestLibDummyContract; - const abiEncoder = self._lookupAbiEncoder(functionSignature); - return abiEncoder.getSelector(); - } - - public publicAddConstant(x: BigNumber): ContractFunctionObj { - const self = (this as any) as TestLibDummyContract; - assert.isBigNumber('x', x); - const functionSignature = 'publicAddConstant(uint256)'; - - return { - async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, [x]); - }, - }; - } - public publicAddOne(x: BigNumber): ContractFunctionObj { - const self = (this as any) as TestLibDummyContract; - assert.isBigNumber('x', x); - const functionSignature = 'publicAddOne(uint256)'; - - return { - async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { - BaseContract._assertCallParams(callData, defaultBlock); - let rawCallResult; - if (self._deployedBytecodeIfExists) { - rawCallResult = await self._evmExecAsync(this.getABIEncodedTransactionData()); - } else { - rawCallResult = await self._performCallAsync( - { data: this.getABIEncodedTransactionData(), ...callData }, - defaultBlock, - ); - } - const abiEncoder = self._lookupAbiEncoder(functionSignature); - BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); - return abiEncoder.strictDecodeReturnValue(rawCallResult); - }, - getABIEncodedTransactionData(): string { - return self._strictEncodeArguments(functionSignature, [x]); - }, - }; - } - - constructor( - address: string, - supportedProvider: SupportedProvider, - txDefaults?: Partial, - logDecodeDependencies?: { [contractName: string]: ContractAbi }, - deployedBytecode: string | undefined = TestLibDummyContract.deployedBytecode, - ) { - super( - 'TestLibDummy', - TestLibDummyContract.ABI(), - address, - supportedProvider, - txDefaults, - logDecodeDependencies, - deployedBytecode, - ); - classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); - TestLibDummyContract.ABI().forEach((item, index) => { - if (item.type === 'function') { - const methodAbi = item as MethodAbi; - this._methodABIIndex[methodAbi.name] = index; - } - }); - } -} - -// tslint:disable:max-file-line-count -// tslint:enable:no-unbound-method no-parameter-reassignment no-consecutive-blank-lines ordered-imports align -// tslint:enable:trailing-comma whitespace no-trailing-whitespace diff --git a/packages/abi-gen/test-cli/test_typescript/src/artifacts.ts b/packages/abi-gen/test-cli/test_typescript/src/artifacts.ts deleted file mode 100644 index ba52e8aef6..0000000000 --- a/packages/abi-gen/test-cli/test_typescript/src/artifacts.ts +++ /dev/null @@ -1,15 +0,0 @@ -/* - * ----------------------------------------------------------------------------- - * Warning: This file is auto-generated by contracts-gen. Don't edit manually. - * ----------------------------------------------------------------------------- - */ -import { ContractArtifact } from 'ethereum-types'; - -import * as AbiGenDummy from '../../fixtures/artifacts/AbiGenDummy.json'; -import * as LibDummy from '../../fixtures/artifacts/LibDummy.json'; -import * as TestLibDummy from '../../fixtures/artifacts/TestLibDummy.json'; -export const artifacts = { - AbiGenDummy: AbiGenDummy as ContractArtifact, - LibDummy: LibDummy as ContractArtifact, - TestLibDummy: TestLibDummy as ContractArtifact, -}; diff --git a/packages/abi-gen/test-cli/test_typescript/src/index.ts b/packages/abi-gen/test-cli/test_typescript/src/index.ts deleted file mode 100644 index cb85aa0d18..0000000000 --- a/packages/abi-gen/test-cli/test_typescript/src/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { artifacts } from './artifacts'; -export * from './wrappers'; diff --git a/packages/abi-gen/test-cli/test_typescript/src/wrappers.ts b/packages/abi-gen/test-cli/test_typescript/src/wrappers.ts deleted file mode 100644 index ef6044fc87..0000000000 --- a/packages/abi-gen/test-cli/test_typescript/src/wrappers.ts +++ /dev/null @@ -1,8 +0,0 @@ -/* - * ----------------------------------------------------------------------------- - * Warning: This file is auto-generated by contracts-gen. Don't edit manually. - * ----------------------------------------------------------------------------- - */ -export * from '../../output/typescript/abi_gen_dummy'; -export * from '../../output/typescript/lib_dummy'; -export * from '../../output/typescript/test_lib_dummy'; diff --git a/packages/abi-gen/test-cli/test_typescript/test/abi_gen_dummy_test.ts b/packages/abi-gen/test-cli/test_typescript/test/abi_gen_dummy_test.ts deleted file mode 100644 index 5dfc7eb503..0000000000 --- a/packages/abi-gen/test-cli/test_typescript/test/abi_gen_dummy_test.ts +++ /dev/null @@ -1,329 +0,0 @@ -import { ContractFunctionObj } from '@0x/base-contract'; -import { BlockchainLifecycle, devConstants, web3Factory } from '@0x/dev-utils'; -import { Web3ProviderEngine } from '@0x/subproviders'; -import { BigNumber, providerUtils, StringRevertError } from '@0x/utils'; -import { BlockParamLiteral, Web3Wrapper } from '@0x/web3-wrapper'; -import * as chai from 'chai'; -import * as chaiAsPromised from 'chai-as-promised'; -import * as ChaiBigNumber from 'chai-bignumber'; -import * as dirtyChai from 'dirty-chai'; -import * as Sinon from 'sinon'; - -import { - AbiGenDummyContract, - AbiGenDummyEvents, - AbiGenDummyWithdrawalEventArgs, - artifacts, - TestLibDummyContract, -} from '../src'; - -const txDefaults = { - from: devConstants.TESTRPC_FIRST_ADDRESS, - gas: devConstants.GAS_LIMIT, -}; - -const provider: Web3ProviderEngine = web3Factory.getRpcProvider({ shouldUseInProcessGanache: true }); -const web3Wrapper = new Web3Wrapper(provider); - -chai.config.includeStack = true; -chai.use(ChaiBigNumber()); -chai.use(dirtyChai); -chai.use(chaiAsPromised); -const expect = chai.expect; -const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper); - -describe('AbiGenDummy Contract', () => { - let abiGenDummy: AbiGenDummyContract; - const runTestAsync = async ( - contractMethodName: string, - contractMethod: ContractFunctionObj, - input: any, - output: any, - ) => { - const transaction = contractMethod.getABIEncodedTransactionData(); - // try decoding transaction - const decodedInput = abiGenDummy.getABIDecodedTransactionData(contractMethodName, transaction); - expect(decodedInput, 'decoded input').to.be.deep.equal(input); - // execute transaction - const rawOutput = await web3Wrapper.callAsync({ - to: abiGenDummy.address, - data: transaction, - }); - // try decoding output - const decodedOutput = abiGenDummy.getABIDecodedReturnData(contractMethodName, rawOutput); - expect(decodedOutput, 'decoded output').to.be.deep.equal(output); - }; - before(async () => { - providerUtils.startProviderEngine(provider); - abiGenDummy = await AbiGenDummyContract.deployFrom0xArtifactAsync( - artifacts.AbiGenDummy, - provider, - txDefaults, - artifacts, - ); - await blockchainLifecycle.startAsync(); - }); - after(async () => { - await blockchainLifecycle.revertAsync(); - }); - describe('simplePureFunction', () => { - it('should call simplePureFunction', async () => { - const result = await abiGenDummy.simplePureFunction().callAsync(); - expect(result).to.deep.equal(new BigNumber(1)); - }); - }); - describe('simplePureFunctionWithInput', () => { - it('should call simplePureFunctionWithInput', async () => { - const result = await abiGenDummy.simplePureFunctionWithInput(new BigNumber(5)).callAsync(); - expect(result).to.deep.equal(new BigNumber(6)); - }); - }); - describe('pureFunctionWithConstant', () => { - it('should call pureFunctionWithConstant', async () => { - const result = await abiGenDummy.pureFunctionWithConstant().callAsync(); - expect(result).to.deep.equal(new BigNumber(1234)); - }); - }); - describe('simpleRevert', () => { - it('should call simpleRevert', async () => { - expect(abiGenDummy.simpleRevert().callAsync()) - .to.eventually.be.rejectedWith(StringRevertError) - .and.deep.equal(new StringRevertError('SIMPLE_REVERT')); - }); - }); - describe('revertWithConstant', () => { - it('should call revertWithConstant', async () => { - expect(abiGenDummy.revertWithConstant().callAsync()) - .to.eventually.be.rejectedWith(StringRevertError) - .and.deep.equal(new StringRevertError('REVERT_WITH_CONSTANT')); - }); - }); - describe('simpleRequire', () => { - it('should call simpleRequire', async () => { - expect(abiGenDummy.simpleRequire().callAsync()) - .to.eventually.be.rejectedWith(StringRevertError) - .and.deep.equal(new StringRevertError('SIMPLE_REQUIRE')); - }); - }); - describe('requireWithConstant', () => { - it('should call requireWithConstant', async () => { - expect(abiGenDummy.requireWithConstant().callAsync()) - .to.eventually.be.rejectedWith(StringRevertError) - .and.deep.equal(new StringRevertError('REQUIRE_WITH_CONSTANT')); - }); - }); - - describe('struct handling', () => { - const sampleStruct = { - aDynamicArrayOfBytes: ['0x3078313233', '0x3078333231'], - anInteger: new BigNumber(5), - aString: 'abc', - someBytes: '0x3078313233', - }; - it('should be able to handle struct output', async () => { - const result = await abiGenDummy.structOutput().callAsync(); - expect(result).to.deep.equal(sampleStruct); - }); - }); - - describe('ecrecoverFn', () => { - it('should implement ecrecover', async () => { - const signerAddress = devConstants.TESTRPC_FIRST_ADDRESS; - const message = '0x6927e990021d23b1eb7b8789f6a6feaf98fe104bb0cf8259421b79f9a34222b0'; - const signature = await web3Wrapper.signMessageAsync(signerAddress, message); - - // tslint:disable:custom-no-magic-numbers - const r = `0x${signature.slice(2, 66)}`; - const s = `0x${signature.slice(66, 130)}`; - const v = signature.slice(130, 132); - const v_decimal = parseInt(v, 16) + 27; // v: (0 or 1) => (27 or 28) - // tslint:enable:custom-no-magic-numbers - - const result = await abiGenDummy.ecrecoverFn(message, v_decimal, r, s).callAsync(); - expect(result).to.equal(signerAddress); - }); - }); - - describe('event subscription', () => { - const indexFilterValues = {}; - const emptyCallback = () => {}; // tslint:disable-line:no-empty - let stubs: Sinon.SinonStub[] = []; - - afterEach(() => { - stubs.forEach(s => s.restore()); - stubs = []; - }); - it('should return a subscription token', done => { - const subscriptionToken = abiGenDummy.subscribe( - AbiGenDummyEvents.Withdrawal, - indexFilterValues, - emptyCallback, - ); - expect(subscriptionToken).to.be.a('string'); - done(); - }); - it('should allow unsubscribeAll to be called successfully after an error', done => { - abiGenDummy.subscribe(AbiGenDummyEvents.Withdrawal, indexFilterValues, emptyCallback); - stubs.push( - Sinon.stub((abiGenDummy as any)._web3Wrapper, 'getBlockIfExistsAsync').throws( - new Error('JSON RPC error'), - ), - ); - abiGenDummy.unsubscribeAll(); - done(); - }); - }); - - describe('getLogsAsync', () => { - const blockRange = { - fromBlock: 0, - toBlock: BlockParamLiteral.Latest, - }; - it('should get logs with decoded args emitted by EventWithStruct', async () => { - await abiGenDummy.emitSimpleEvent().awaitTransactionSuccessAsync(); - const eventName = AbiGenDummyEvents.SimpleEvent; - const indexFilterValues = {}; - const logs = await abiGenDummy.getLogsAsync(eventName, blockRange, indexFilterValues); - expect(logs).to.have.length(1); - expect(logs[0].event).to.be.equal(eventName); - }); - it('should only get the logs with the correct event name', async () => { - await abiGenDummy.emitSimpleEvent().awaitTransactionSuccessAsync(); - const differentEventName = AbiGenDummyEvents.Withdrawal; - const indexFilterValues = {}; - const logs = await abiGenDummy.getLogsAsync(differentEventName, blockRange, indexFilterValues); - expect(logs).to.have.length(0); - }); - it('should only get the logs with the correct indexed fields', async () => { - const [addressOne, addressTwo] = await web3Wrapper.getAvailableAddressesAsync(); - await abiGenDummy.withdraw(new BigNumber(1)).awaitTransactionSuccessAsync({ from: addressOne }); - await abiGenDummy.withdraw(new BigNumber(1)).awaitTransactionSuccessAsync({ from: addressTwo }); - const eventName = AbiGenDummyEvents.Withdrawal; - const indexFilterValues = { - _owner: addressOne, - }; - const logs = await abiGenDummy.getLogsAsync( - eventName, - blockRange, - indexFilterValues, - ); - expect(logs).to.have.length(1); - const args = logs[0].args; - expect(args._owner).to.be.equal(addressOne); - }); - }); - - describe('withAddressInput', () => { - it('should normalize address inputs to lowercase', async () => { - const xAddress = devConstants.TESTRPC_FIRST_ADDRESS.toUpperCase(); - const yAddress = devConstants.TESTRPC_FIRST_ADDRESS; - const a = new BigNumber(1); - const b = new BigNumber(2); - const c = new BigNumber(3); - const output = await abiGenDummy.withAddressInput(xAddress, a, b, yAddress, c).callAsync(); - - expect(output).to.equal(xAddress.toLowerCase()); - }); - }); - - describe('Encoding/Decoding Transaction Data and Return Values', () => { - it('should successfully encode/decode (no input / no output)', async () => { - const input = undefined; - const output = undefined; - await runTestAsync('noInputNoOutput', abiGenDummy.noInputNoOutput(), input, output); - }); - it('should successfully encode/decode (no input / simple output)', async () => { - const input = undefined; - const output = new BigNumber(1991); - await runTestAsync('noInputSimpleOutput', abiGenDummy.noInputSimpleOutput(), input, output); - }); - it('should successfully encode/decode (simple input / no output)', async () => { - const input = new BigNumber(1991); - const output = undefined; - await runTestAsync('simpleInputNoOutput', abiGenDummy.simpleInputNoOutput(input), input, output); - }); - it('should successfully encode/decode (simple input / simple output)', async () => { - const input = new BigNumber(16); - const output = new BigNumber(1991); - await runTestAsync('simpleInputSimpleOutput', abiGenDummy.simpleInputSimpleOutput(input), input, output); - }); - it('should successfully encode/decode (complex input / complex output)', async () => { - const input = { - foo: new BigNumber(1991), - bar: '0x1234', - car: 'zoom zoom', - }; - const output = { - input, - lorem: '0x12345678', - ipsum: '0x87654321', - dolor: 'amet', - }; - await runTestAsync( - 'complexInputComplexOutput', - abiGenDummy.complexInputComplexOutput(input), - input, - output, - ); - }); - it('should successfully encode/decode (multi-input / multi-output)', async () => { - const input = [new BigNumber(1991), '0x1234', 'zoom zoom']; - const output = ['0x12345678', '0x87654321', 'amet']; - const transaction = abiGenDummy - .multiInputMultiOutput(input[0] as BigNumber, input[1] as string, input[2] as string) - .getABIEncodedTransactionData(); - // try decoding transaction - const decodedInput = abiGenDummy.getABIDecodedTransactionData('multiInputMultiOutput', transaction); - expect(decodedInput, 'decoded input').to.be.deep.equal(input); - // execute transaction - const rawOutput = await web3Wrapper.callAsync({ - to: abiGenDummy.address, - data: transaction, - }); - // try decoding output - const decodedOutput = abiGenDummy.getABIDecodedReturnData('multiInputMultiOutput', rawOutput); - expect(decodedOutput, 'decoded output').to.be.deep.equal(output); - }); - }); - describe('awaitTransactionSuccessAsync', async () => { - it('should successfully call the non pure function', async () => { - expect( - abiGenDummy.nonPureMethod().awaitTransactionSuccessAsync({}, { pollingIntervalMs: 10, timeoutMs: 100 }), - ).to.be.fulfilled(''); - }); - }); -}); - -describe('Lib dummy contract', () => { - let libDummy: TestLibDummyContract; - before(async () => { - await blockchainLifecycle.startAsync(); - }); - after(async () => { - await blockchainLifecycle.revertAsync(); - }); - before(async () => { - libDummy = await TestLibDummyContract.deployFrom0xArtifactAsync( - artifacts.TestLibDummy, - provider, - txDefaults, - artifacts, - ); - }); - beforeEach(async () => { - await blockchainLifecycle.startAsync(); - }); - afterEach(async () => { - await blockchainLifecycle.revertAsync(); - }); - - it('should call a library function', async () => { - const result = await libDummy.publicAddOne(new BigNumber(1)).callAsync(); - expect(result).to.deep.equal(new BigNumber(2)); - }); - - it('should call a library function referencing a constant', async () => { - const result = await libDummy.publicAddConstant(new BigNumber(1)).callAsync(); - expect(result).to.deep.equal(new BigNumber(1235)); - }); -}); diff --git a/packages/abi-gen/test-cli/tsconfig.json b/packages/abi-gen/test-cli/tsconfig.json deleted file mode 100644 index 7c39bd36d2..0000000000 --- a/packages/abi-gen/test-cli/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "../../../tsconfig.json", - "compilerOptions": { - "resolveJsonModule": true, - "outDir": "./test_typescript/lib", - "rootDir": "." - }, - "files": [ - "./fixtures/artifacts/AbiGenDummy.json", - "./fixtures/artifacts/LibDummy.json", - "./fixtures/artifacts/TestLibDummy.json" - ], - "exclude": ["./test_typescript/lib"], - "include": ["./output/typescript/**/*", "./test_typescript/**/*"] -} diff --git a/packages/abi-gen/test/utils_test.ts b/packages/abi-gen/test/utils_test.ts deleted file mode 100644 index f13d2ab227..0000000000 --- a/packages/abi-gen/test/utils_test.ts +++ /dev/null @@ -1,98 +0,0 @@ -import * as chai from 'chai'; -import * as dirtyChai from 'dirty-chai'; -import * as fs from 'fs'; -import 'mocha'; -import * as tmp from 'tmp'; - -import { utils } from '../src/utils'; - -tmp.setGracefulCleanup(); // remove tmp files even if there are failures - -chai.use(dirtyChai); - -const expect = chai.expect; - -describe('makeOutputFileName()', () => { - it('should handle Metacoin usage', () => { - expect(utils.makeOutputFileName('Metacoin')).to.equal('metacoin'); - }); - it('should handle special zrx_token case', () => { - expect(utils.makeOutputFileName('ZRXToken')).to.equal('zrx_token'); - }); - it('should handle special erc_token case', () => { - expect(utils.makeOutputFileName('ERC20Token')).to.equal('erc20_token'); - }); -}); - -describe('writeOutputFile()', () => { - let tempFilePath: string; - before(() => { - tempFilePath = tmp.fileSync( - { discardDescriptor: true }, // close file (so we can update it) - ).name; - }); - it('should write content to output file', () => { - const content = 'hello world'; - - utils.writeOutputFile(tempFilePath, content); - - expect(fs.readFileSync(tempFilePath).toString()).to.equal(content); - }); -}); - -describe('isOutputFileUpToDate()', () => { - it('should throw ENOENT when there is no abi file', () => { - expect(utils.isOutputFileUpToDate.bind('', 'nonexistant1', ['nonexistant2'])).to.throw('ENOENT'); - }); - - describe('when the abi input file exists', () => { - let abiFile: string; - before(() => { - abiFile = tmp.fileSync( - { discardDescriptor: true }, // close file (set timestamp) - ).name; - }); - - describe('without an existing output file', () => { - it('should return false', () => { - expect(utils.isOutputFileUpToDate('nonexistant_file', [abiFile])).to.be.false(); - }); - }); - - describe('with an existing output file', () => { - let outputFile: string; - before(() => { - outputFile = tmp.fileSync( - { discardDescriptor: true }, // close file (set timestamp) - ).name; - const abiFileModTimeMs = fs.statSync(abiFile).mtimeMs; - const outfileModTimeMs = abiFileModTimeMs + 1; - fs.utimesSync(outputFile, outfileModTimeMs, outfileModTimeMs); - }); - - it('should return true when output file is newer than abi file', async () => { - expect(utils.isOutputFileUpToDate(outputFile, [abiFile])).to.be.true(); - }); - - it('should return false when output file exists but is older than abi file', () => { - const outFileModTimeMs = fs.statSync(outputFile).mtimeMs; - const abiFileModTimeMs = outFileModTimeMs + 1; - fs.utimesSync(abiFile, abiFileModTimeMs, abiFileModTimeMs); - - expect(utils.isOutputFileUpToDate(outputFile, [abiFile])).to.be.false(); - }); - it('should return false when any source file is newer than output file', () => { - const templateFile = tmp.fileSync( - { discardDescriptor: true }, // close file (set timestamp) - ).name; - - const templateFileModTimeMs = fs.statSync(outputFile).mtimeMs + 1; - const abiFileModTimeMs = fs.statSync(outputFile).mtimeMs; - fs.utimesSync(templateFile, templateFileModTimeMs, templateFileModTimeMs); - fs.utimesSync(abiFile, abiFileModTimeMs, abiFileModTimeMs); - - expect(utils.isOutputFileUpToDate(outputFile, [abiFile, templateFile])).to.be.false(); - }); - }); - }); -}); diff --git a/packages/abi-gen/tsconfig.json b/packages/abi-gen/tsconfig.json deleted file mode 100644 index 0ac45cd5fd..0000000000 --- a/packages/abi-gen/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../tsconfig", - "compilerOptions": { - "outDir": "lib", - "rootDir": "." - }, - "exclude": [ - "./test-cli/**/*", - "./src/artifacts.ts", - "./src/wrappers.ts", - "prior two elements refer to code generated by contracts-gen for test fixture contracts" - ], - "include": ["./src/**/*", "./test/*"] -} diff --git a/packages/abi-gen/tslint.json b/packages/abi-gen/tslint.json deleted file mode 100644 index 7367a3a8a8..0000000000 --- a/packages/abi-gen/tslint.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "extends": ["@0x/tslint-config"], - "linterOptions": { - "exclude": ["./test-cli/fixtures/**/*", "**/lib/**/*"] - } -} diff --git a/packages/assert/.npmignore b/packages/assert/.npmignore deleted file mode 100644 index ea588d4859..0000000000 --- a/packages/assert/.npmignore +++ /dev/null @@ -1,9 +0,0 @@ -# Blacklist all files -.* -* -# Whitelist lib -!lib/**/* -# Blacklist tests and publish scripts -/lib/test/* -/lib/monorepo_scripts/ -# Package specific ignore diff --git a/packages/assert/CHANGELOG.json b/packages/assert/CHANGELOG.json deleted file mode 100644 index cdae925bdb..0000000000 --- a/packages/assert/CHANGELOG.json +++ /dev/null @@ -1,658 +0,0 @@ -[ - { - "timestamp": 1594788383, - "version": "3.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1592969527, - "version": "3.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1582623685, - "version": "3.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1581204851, - "version": "3.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1580988106, - "version": "3.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1579682890, - "version": "3.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1578272714, - "version": "3.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1576540892, - "version": "3.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1575931811, - "version": "3.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.0.0", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1575296764 - }, - { - "version": "2.2.0-beta.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1575290197 - }, - { - "version": "2.2.0-beta.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1574030254 - }, - { - "version": "2.2.0-beta.1", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1573159180 - }, - { - "version": "2.2.0-beta.0", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1570135330 - }, - { - "timestamp": 1568744790, - "version": "2.1.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1567521715, - "version": "2.1.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1566446343, - "version": "2.1.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1565296576, - "version": "2.1.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1564604963, - "version": "2.1.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563957393, - "version": "2.1.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.1.0", - "changes": [ - { - "note": "Add new assertions: `isArray`, `isBlockParam` and `isNumberOrBigNumber`", - "pr": 1823 - }, - { - "note": "Add `isNumberLike()` assertion", - "pr": 1819 - } - ], - "timestamp": 1563006338 - }, - { - "timestamp": 1557507213, - "version": "2.0.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1554997931 - }, - { - "timestamp": 1553183790, - "version": "2.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1553091633, - "version": "2.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551479279, - "version": "2.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551220833, - "version": "2.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551130135, - "version": "2.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1549733923, - "version": "2.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1549547375 - }, - { - "timestamp": 1549452781, - "version": "2.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.0", - "changes": [ - { - "note": "Upgrade the bignumber.js to v8.0.2", - "pr": 1517 - } - ], - "timestamp": 1549373905 - }, - { - "timestamp": 1547561734, - "version": "1.0.23", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547225310, - "version": "1.0.22", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547040760, - "version": "1.0.21", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.20", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544739608 - }, - { - "version": "1.0.19", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544570656 - }, - { - "timestamp": 1542821676, - "version": "1.0.18", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542208198, - "version": "1.0.17", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542028948, - "version": "1.0.16", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.15", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1541740904 - }, - { - "timestamp": 1539871071, - "version": "1.0.14", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.13", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1538693146 - }, - { - "timestamp": 1538157789, - "version": "1.0.12", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537907159, - "version": "1.0.11", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537875740, - "version": "1.0.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537541580, - "version": "1.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1536142250, - "version": "1.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1535377027, - "version": "1.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1535133899, - "version": "1.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1534210131, - "version": "1.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532619515, - "version": "1.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532614997, - "version": "1.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532605697, - "version": "1.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532357734, - "version": "1.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532043000, - "version": "1.0.0", - "changes": [ - { - "note": "Fix bug in string enum assertion. We erroneously were checking against the enum keys, not values", - "pr": 821 - } - ] - }, - { - "timestamp": 1531919263, - "version": "0.2.14", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1531149657, - "version": "0.2.13", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1529397769, - "version": "0.2.12", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.2.11", - "changes": [ - { - "note": "Incorrect publish that was unpublished" - } - ], - "timestamp": 1527810075 - }, - { - "timestamp": 1527008270, - "version": "0.2.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1525477860, - "version": "0.2.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1525428773, - "version": "0.2.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1524044013, - "version": "0.2.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1523462196, - "version": "0.2.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1522673609, - "version": "0.2.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1522658513, - "version": "0.2.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.2.0", - "changes": [ - { - "note": "Rename `isHttpUrl` to `isWebUri`", - "pr": 412 - } - ], - "timestamp": 1520434800 - }, - { - "version": "0.1.0", - "changes": [ - { - "note": "Remove isETHAddressHex checksum address check and assume address will be lowercased ", - "pr": 373 - }, - { - "note": "Add an optional parameter `subSchemas` to `doesConformToSchema` method", - "pr": 385 - } - ], - "timestamp": 1520089200 - }, - { - "version": "0.0.18", - "changes": [ - { - "note": "Fix publishing issue where .npmignore was not properly excluding undesired content", - "pr": 389 - } - ], - "timestamp": 1486566000 - }, - { - "version": "0.0.4", - "changes": [ - { - "note": "Re-publish Assert previously published under NPM package @0xproject/0x-assert" - }, - { - "note": "Added assertion isValidBaseUnitAmount which checks both that the value is a valid bigNumber and that it does not contain decimals." - } - ], - "timestamp": 1510585200 - } -] diff --git a/packages/assert/CHANGELOG.md b/packages/assert/CHANGELOG.md deleted file mode 100644 index 1eb0ba9bdc..0000000000 --- a/packages/assert/CHANGELOG.md +++ /dev/null @@ -1,293 +0,0 @@ - - -CHANGELOG - -## v3.0.9 - _July 15, 2020_ - - * Dependencies updated - -## v3.0.8 - _June 24, 2020_ - - * Dependencies updated - -## v3.0.7 - _February 25, 2020_ - - * Dependencies updated - -## v3.0.6 - _February 8, 2020_ - - * Dependencies updated - -## v3.0.5 - _February 6, 2020_ - - * Dependencies updated - -## v3.0.4 - _January 22, 2020_ - - * Dependencies updated - -## v3.0.3 - _January 6, 2020_ - - * Dependencies updated - -## v3.0.2 - _December 17, 2019_ - - * Dependencies updated - -## v3.0.1 - _December 9, 2019_ - - * Dependencies updated - -## v3.0.0 - _December 2, 2019_ - - * Dependencies updated - -## v2.2.0-beta.3 - _December 2, 2019_ - - * Dependencies updated - -## v2.2.0-beta.2 - _November 17, 2019_ - - * Dependencies updated - -## v2.2.0-beta.1 - _November 7, 2019_ - - * Dependencies updated - -## v2.2.0-beta.0 - _October 3, 2019_ - - * Dependencies updated - -## v2.1.6 - _September 17, 2019_ - - * Dependencies updated - -## v2.1.5 - _September 3, 2019_ - - * Dependencies updated - -## v2.1.4 - _August 22, 2019_ - - * Dependencies updated - -## v2.1.3 - _August 8, 2019_ - - * Dependencies updated - -## v2.1.2 - _July 31, 2019_ - - * Dependencies updated - -## v2.1.1 - _July 24, 2019_ - - * Dependencies updated - -## v2.1.0 - _July 13, 2019_ - - * Add new assertions: `isArray`, `isBlockParam` and `isNumberOrBigNumber` (#1823) - * Add `isNumberLike()` assertion (#1819) - -## v2.0.10 - _May 10, 2019_ - - * Dependencies updated - -## v2.0.9 - _April 11, 2019_ - - * Dependencies updated - -## v2.0.8 - _March 21, 2019_ - - * Dependencies updated - -## v2.0.7 - _March 20, 2019_ - - * Dependencies updated - -## v2.0.6 - _March 1, 2019_ - - * Dependencies updated - -## v2.0.5 - _February 26, 2019_ - - * Dependencies updated - -## v2.0.4 - _February 25, 2019_ - - * Dependencies updated - -## v2.0.3 - _February 9, 2019_ - - * Dependencies updated - -## v2.0.2 - _February 7, 2019_ - - * Dependencies updated - -## v2.0.1 - _February 6, 2019_ - - * Dependencies updated - -## v2.0.0 - _February 5, 2019_ - - * Upgrade the bignumber.js to v8.0.2 (#1517) - -## v1.0.23 - _January 15, 2019_ - - * Dependencies updated - -## v1.0.22 - _January 11, 2019_ - - * Dependencies updated - -## v1.0.21 - _January 9, 2019_ - - * Dependencies updated - -## v1.0.20 - _December 13, 2018_ - - * Dependencies updated - -## v1.0.19 - _December 11, 2018_ - - * Dependencies updated - -## v1.0.18 - _November 21, 2018_ - - * Dependencies updated - -## v1.0.17 - _November 14, 2018_ - - * Dependencies updated - -## v1.0.16 - _November 12, 2018_ - - * Dependencies updated - -## v1.0.15 - _November 9, 2018_ - - * Dependencies updated - -## v1.0.14 - _October 18, 2018_ - - * Dependencies updated - -## v1.0.13 - _October 4, 2018_ - - * Dependencies updated - -## v1.0.12 - _September 28, 2018_ - - * Dependencies updated - -## v1.0.11 - _September 25, 2018_ - - * Dependencies updated - -## v1.0.10 - _September 25, 2018_ - - * Dependencies updated - -## v1.0.9 - _September 21, 2018_ - - * Dependencies updated - -## v1.0.8 - _September 5, 2018_ - - * Dependencies updated - -## v1.0.7 - _August 27, 2018_ - - * Dependencies updated - -## v1.0.6 - _August 24, 2018_ - - * Dependencies updated - -## v1.0.5 - _August 14, 2018_ - - * Dependencies updated - -## v1.0.4 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.3 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.2 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.1 - _July 23, 2018_ - - * Dependencies updated - -## v1.0.0 - _July 19, 2018_ - - * Fix bug in string enum assertion. We erroneously were checking against the enum keys, not values (#821) - -## v0.2.14 - _July 18, 2018_ - - * Dependencies updated - -## v0.2.13 - _July 9, 2018_ - - * Dependencies updated - -## v0.2.12 - _June 19, 2018_ - - * Dependencies updated - -## v0.2.11 - _May 31, 2018_ - - * Incorrect publish that was unpublished - -## v0.2.10 - _May 22, 2018_ - - * Dependencies updated - -## v0.2.9 - _May 4, 2018_ - - * Dependencies updated - -## v0.2.8 - _May 4, 2018_ - - * Dependencies updated - -## v0.2.7 - _April 18, 2018_ - - * Dependencies updated - -## v0.2.6 - _April 11, 2018_ - - * Dependencies updated - -## v0.2.5 - _April 2, 2018_ - - * Dependencies updated - -## v0.2.4 - _April 2, 2018_ - - * Dependencies updated - -## v0.2.0 - _March 7, 2018_ - - * Rename `isHttpUrl` to `isWebUri` (#412) - -## v0.1.0 - _March 3, 2018_ - - * Remove isETHAddressHex checksum address check and assume address will be lowercased (#373) - * Add an optional parameter `subSchemas` to `doesConformToSchema` method (#385) - -## v0.0.18 - _February 8, 2017_ - - * Fix publishing issue where .npmignore was not properly excluding undesired content (#389) - -## v0.0.4 - _November 13, 2017_ - - * Re-publish Assert previously published under NPM package @0xproject/0x-assert - * Added assertion isValidBaseUnitAmount which checks both that the value is a valid bigNumber and that it does not contain decimals. diff --git a/packages/assert/README.md b/packages/assert/README.md deleted file mode 100644 index 647586f15e..0000000000 --- a/packages/assert/README.md +++ /dev/null @@ -1,77 +0,0 @@ -## @0x/assert - -Standard type and schema assertions to be used across all 0x projects and packages - -## Installation - -```bash -yarn add @0x/assert -``` - -## Usage - -```typescript -import { assert } from '@0x/assert'; - -assert.isValidBaseUnitAmount('baseUnitAmount', baseUnitAmount); -``` - -If your project is in [TypeScript](https://www.typescriptlang.org/), add the following to your `tsconfig.json`: - -```json -"compilerOptions": { - "typeRoots": ["node_modules/@0x/typescript-typings/types", "node_modules/@types"], -} -``` - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install dependencies - -If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: - -```bash -yarn config set workspaces-experimental true -``` - -Then install dependencies - -```bash -yarn install -``` - -### Build - -To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory: - -```bash -PKG=@0x/assert yarn build -``` - -Or continuously rebuild on change: - -```bash -PKG=@0x/assert yarn watch -``` - -### Clean - -```bash -yarn clean -``` - -### Lint - -```bash -yarn lint -``` - -### Run Tests - -```bash -yarn test -``` diff --git a/packages/assert/coverage/.gitkeep b/packages/assert/coverage/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/assert/package.json b/packages/assert/package.json deleted file mode 100644 index 84a9005c30..0000000000 --- a/packages/assert/package.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "name": "@0x/assert", - "version": "3.0.9", - "engines": { - "node": ">=6.12" - }, - "description": "Provides a standard way of performing type and schema validation across 0x projects", - "main": "lib/src/index.js", - "types": "lib/src/index.d.ts", - "scripts": { - "build": "tsc -b", - "build:ci": "yarn build", - "clean": "shx rm -rf lib test_temp", - "lint": "tslint --format stylish --project .", - "fix": "tslint --fix --format stylish --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" - }, - "license": "Apache-2.0", - "repository": { - "type": "git", - "url": "https://github.com/0xProject/0x-monorepo.git" - }, - "bugs": { - "url": "https://github.com/0xProject/0x-monorepo/issues" - }, - "homepage": "https://github.com/0xProject/0x-monorepo/packages/assert/README.md", - "devDependencies": { - "@0x/tslint-config": "^4.1.0", - "@types/lodash": "4.14.104", - "@types/mocha": "^5.2.7", - "@types/valid-url": "^1.0.2", - "chai": "^4.0.1", - "dirty-chai": "^2.0.1", - "make-promises-safe": "^1.1.0", - "mocha": "^6.2.0", - "npm-run-all": "^4.1.2", - "nyc": "^11.0.1", - "shx": "^0.2.2", - "tslint": "5.11.0", - "typescript": "3.0.1" - }, - "dependencies": { - "@0x/json-schemas": "^5.1.0", - "@0x/typescript-typings": "^5.1.1", - "@0x/utils": "^5.5.1", - "lodash": "^4.17.11", - "valid-url": "^1.0.9" - }, - "publishConfig": { - "access": "public" - }, - "gitHead": "4f91bfd907996b2f4dd383778b50c479c2602b56" -} diff --git a/packages/assert/src/globals.d.ts b/packages/assert/src/globals.d.ts deleted file mode 100644 index 94e63a32de..0000000000 --- a/packages/assert/src/globals.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -declare module '*.json' { - const json: any; - /* tslint:disable */ - export default json; - /* tslint:enable */ -} diff --git a/packages/assert/src/index.ts b/packages/assert/src/index.ts deleted file mode 100644 index d99902e297..0000000000 --- a/packages/assert/src/index.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { Schema, SchemaValidator } from '@0x/json-schemas'; -import { addressUtils, BigNumber, logUtils } from '@0x/utils'; -import * as _ from 'lodash'; -import * as validUrl from 'valid-url'; - -const HEX_REGEX = /^0x[0-9A-F]*$/i; - -export const assert = { - isBigNumber(variableName: string, value: BigNumber): void { - const isBigNumber = BigNumber.isBigNumber(value); - assert.assert(isBigNumber, assert.typeAssertionMessage(variableName, 'BigNumber', value)); - }, - isNumberLike(variableName: string, value: BigNumber | number): void { - const isBigNumber = BigNumber.isBigNumber(value); - const isNumber = typeof value === 'number'; - assert.assert(isBigNumber || isNumber, assert.typeAssertionMessage(variableName, 'BigNumber | number', value)); - }, - isValidBaseUnitAmount(variableName: string, value: BigNumber): void { - assert.isBigNumber(variableName, value); - const isNegative = value.isLessThan(0); - assert.assert(!isNegative, `${variableName} cannot be a negative number, found value: ${value.toNumber()}`); - const hasDecimals = value.decimalPlaces() !== 0; - assert.assert( - !hasDecimals, - `${variableName} should be in baseUnits (no decimals), found value: ${value.toNumber()}`, - ); - }, - isString(variableName: string, value: string): void { - assert.assert(_.isString(value), assert.typeAssertionMessage(variableName, 'string', value)); - }, - isFunction(variableName: string, value: any): void { - assert.assert(_.isFunction(value), assert.typeAssertionMessage(variableName, 'function', value)); - }, - isHexString(variableName: string, value: string): void { - assert.assert( - _.isString(value) && HEX_REGEX.test(value), - assert.typeAssertionMessage(variableName, 'HexString', value), - ); - }, - isETHAddressHex(variableName: string, value: string): void { - assert.assert(_.isString(value), assert.typeAssertionMessage(variableName, 'string', value)); - assert.assert(addressUtils.isAddress(value), assert.typeAssertionMessage(variableName, 'ETHAddressHex', value)); - }, - doesBelongToStringEnum( - variableName: string, - value: string, - stringEnum: any /* There is no base type for every string enum */, - ): void { - const enumValues = _.values(stringEnum); - const doesBelongToStringEnum = _.includes(enumValues, value); - const enumValuesAsStrings = _.map(enumValues, enumValue => `'${enumValue}'`); - const enumValuesAsString = enumValuesAsStrings.join(', '); - assert.assert( - doesBelongToStringEnum, - `Expected ${variableName} to be one of: ${enumValuesAsString}, encountered: ${value}`, - ); - }, - hasAtMostOneUniqueValue(value: any[], errMsg: string): void { - assert.assert(_.uniq(value).length <= 1, errMsg); - }, - isNumber(variableName: string, value: number): void { - assert.assert(_.isFinite(value), assert.typeAssertionMessage(variableName, 'number', value)); - }, - isNumberOrBigNumber(variableName: string, value: any): void { - if (_.isFinite(value)) { - return; - } else { - assert.assert( - BigNumber.isBigNumber(value), - assert.typeAssertionMessage(variableName, 'number or BigNumber', value), - ); - } - }, - isBoolean(variableName: string, value: boolean): void { - assert.assert(_.isBoolean(value), assert.typeAssertionMessage(variableName, 'boolean', value)); - }, - isWeb3Provider(variableName: string, value: any): void { - logUtils.warn('DEPRECATED: Please use providerUtils.standardizeOrThrow() instead'); - const isWeb3Provider = _.isFunction(value.send) || _.isFunction(value.sendAsync); - assert.assert(isWeb3Provider, assert.typeAssertionMessage(variableName, 'Provider', value)); - }, - doesConformToSchema(variableName: string, value: any, schema: Schema, subSchemas?: Schema[]): void { - if (value === undefined) { - throw new Error(`${variableName} can't be undefined`); - } - const schemaValidator = new SchemaValidator(); - if (subSchemas !== undefined) { - _.map(subSchemas, schemaValidator.addSchema.bind(schemaValidator)); - } - const validationResult = schemaValidator.validate(value, schema); - const hasValidationErrors = validationResult.errors.length > 0; - const msg = `Expected ${variableName} to conform to schema ${schema.id} -Encountered: ${JSON.stringify(value, null, '\t')} -Validation errors: ${validationResult.errors.join(', ')}`; - assert.assert(!hasValidationErrors, msg); - }, - isWebUri(variableName: string, value: any): void { - const isValidUrl = validUrl.isWebUri(value) !== undefined; - assert.assert(isValidUrl, assert.typeAssertionMessage(variableName, 'web uri', value)); - }, - isUri(variableName: string, value: any): void { - const isValidUri = validUrl.isUri(value) !== undefined; - assert.assert(isValidUri, assert.typeAssertionMessage(variableName, 'uri', value)); - }, - isBlockParam(variableName: string, value: any): void { - if (Number.isInteger(value) && value >= 0) { - return; - } - if (value === 'earliest' || value === 'latest' || value === 'pending') { - return; - } - throw new Error(assert.typeAssertionMessage(variableName, 'BlockParam', value)); - }, - isArray(variableName: string, value: any): void { - if (!Array.isArray(value)) { - throw new Error(assert.typeAssertionMessage(variableName, 'Array', value)); - } - }, - assert(condition: boolean, message: string): void { - if (!condition) { - throw new Error(message); - } - }, - typeAssertionMessage(variableName: string, type: string, value: any): string { - return `Expected ${variableName} to be of type ${type}, encountered: ${value}`; - }, -}; diff --git a/packages/assert/test/assert_test.ts b/packages/assert/test/assert_test.ts deleted file mode 100644 index 346677b2dd..0000000000 --- a/packages/assert/test/assert_test.ts +++ /dev/null @@ -1,265 +0,0 @@ -import { schemas } from '@0x/json-schemas'; -import { BigNumber } from '@0x/utils'; -import * as chai from 'chai'; -import * as dirtyChai from 'dirty-chai'; -import 'mocha'; - -import { assert } from '../src/index'; - -chai.config.includeStack = true; -chai.use(dirtyChai); -const expect = chai.expect; - -// tslint:disable:custom-no-magic-numbers -describe('Assertions', () => { - const variableName = 'variable'; - describe('#isBigNumber', () => { - it('should not throw for valid input', () => { - const validInputs = [new BigNumber(23), new BigNumber('45')]; - validInputs.forEach(input => expect(assert.isBigNumber.bind(assert, variableName, input)).to.not.throw()); - }); - it('should throw for invalid input', () => { - const invalidInputs = ['test', 42, false, { random: 'test' }, undefined]; - invalidInputs.forEach(input => expect(assert.isBigNumber.bind(assert, variableName, input)).to.throw()); - }); - }); - describe('#isNumberLike', () => { - it('should not throw for valid input', () => { - const validInputs = [new BigNumber(23), 23]; - validInputs.forEach(input => expect(assert.isNumberLike.bind(assert, variableName, input)).to.not.throw()); - }); - it('should throw for invalid input', () => { - const invalidInputs = ['test', false, { random: 'test' }, undefined]; - invalidInputs.forEach(input => expect(assert.isNumberLike.bind(assert, variableName, input)).to.throw()); - }); - }); - describe('#isValidBaseUnitAmount', () => { - it('should not throw for valid input', () => { - const validInputs = [new BigNumber(23), new BigNumber('45000000')]; - validInputs.forEach(input => - expect(assert.isValidBaseUnitAmount.bind(assert, variableName, input)).to.not.throw(), - ); - }); - it('should throw for invalid input', () => { - const invalidInputs = [0, undefined, new BigNumber(3.145), 3.145, new BigNumber(-400)]; - invalidInputs.forEach(input => - expect(assert.isValidBaseUnitAmount.bind(assert, variableName, input)).to.throw(), - ); - }); - }); - describe('#isString', () => { - it('should not throw for valid input', () => { - const validInputs = ['hello', 'goodbye']; - validInputs.forEach(input => expect(assert.isString.bind(assert, variableName, input)).to.not.throw()); - }); - it('should throw for invalid input', () => { - const invalidInputs = [42, false, { random: 'test' }, undefined, new BigNumber(45)]; - invalidInputs.forEach(input => expect(assert.isString.bind(assert, variableName, input)).to.throw()); - }); - }); - describe('#isFunction', () => { - it('should not throw for valid input', () => { - const validInputs = [BigNumber, assert.isString.bind(assert)]; - validInputs.forEach(input => expect(assert.isFunction.bind(assert, variableName, input)).to.not.throw()); - }); - it('should throw for invalid input', () => { - const invalidInputs = [42, false, { random: 'test' }, undefined, new BigNumber(45)]; - invalidInputs.forEach(input => expect(assert.isFunction.bind(assert, variableName, input)).to.throw()); - }); - }); - describe('#isHexString', () => { - it('should not throw for valid input', () => { - const validInputs = [ - '0x61a3ed31B43c8780e905a260a35faefEc527be7516aa11c0256729b5b351bc33', - '0x40349190569279751135161d22529dc25add4f6069af05be04cacbda2ace2254', - ]; - validInputs.forEach(input => expect(assert.isHexString.bind(assert, variableName, input)).to.not.throw()); - }); - it('should throw for invalid input', () => { - const invalidInputs = [ - 42, - false, - { random: 'test' }, - undefined, - new BigNumber(45), - '0x61a3ed31B43c8780e905a260a35faYfEc527be7516aa11c0256729b5b351bc33', - ]; - invalidInputs.forEach(input => expect(assert.isHexString.bind(assert, variableName, input)).to.throw()); - }); - }); - describe('#isETHAddressHex', () => { - it('should not throw for valid input', () => { - const validInputs = [ - '0x0000000000000000000000000000000000000000', - '0x6fffd0ae3f7d88c9b4925323f54c6e4b2918c5fd', - '0x12459c951127e0c374ff9105dda097662a027093', - ]; - validInputs.forEach(input => - expect(assert.isETHAddressHex.bind(assert, variableName, input)).to.not.throw(), - ); - }); - it('should throw for invalid input', () => { - const invalidInputs = [ - 42, - false, - { random: 'test' }, - undefined, - new BigNumber(45), - '0x6FFFd0ae3f7d88c9b4925323f54c6e4b2918c5fd', - '0x6FFFd0ae3f7d88c9b4925323f54c6e4', - ]; - invalidInputs.forEach(input => expect(assert.isETHAddressHex.bind(assert, variableName, input)).to.throw()); - }); - }); - describe('#doesBelongToStringEnum', () => { - enum TestEnums { - Test1 = 'Test1', - Test2 = 'Test2', - } - it('should not throw for valid input', () => { - const validInputs = [TestEnums.Test1, TestEnums.Test2]; - validInputs.forEach(input => - expect(assert.doesBelongToStringEnum.bind(assert, variableName, input, TestEnums)).to.not.throw(), - ); - }); - it('should throw for invalid input', () => { - const invalidInputs = [42, false, { random: 'test' }, undefined, new BigNumber(45)]; - invalidInputs.forEach(input => - expect(assert.doesBelongToStringEnum.bind(assert, variableName, input, TestEnums)).to.throw(), - ); - }); - }); - describe('#hasAtMostOneUniqueValue', () => { - const errorMsg = 'more than one unique value'; - it('should not throw for valid input', () => { - const validInputs = [['hello'], ['goodbye', 'goodbye', 'goodbye']]; - validInputs.forEach(input => - expect(assert.hasAtMostOneUniqueValue.bind(assert, input, errorMsg)).to.not.throw(), - ); - }); - it('should throw for invalid input', () => { - const invalidInputs = [['hello', 'goodbye'], ['goodbye', 42, false, false]]; - invalidInputs.forEach(input => - expect(assert.hasAtMostOneUniqueValue.bind(assert, input, errorMsg)).to.throw(), - ); - }); - }); - describe('#isNumber', () => { - it('should not throw for valid input', () => { - const validInputs = [42, 0, 21e42]; - validInputs.forEach(input => expect(assert.isNumber.bind(assert, variableName, input)).to.not.throw()); - }); - it('should throw for invalid input', () => { - const invalidInputs = [false, { random: 'test' }, undefined, new BigNumber(45)]; - invalidInputs.forEach(input => expect(assert.isNumber.bind(assert, variableName, input)).to.throw()); - }); - }); - describe('#isBoolean', () => { - it('should not throw for valid input', () => { - const validInputs = [true, false]; - validInputs.forEach(input => expect(assert.isBoolean.bind(assert, variableName, input)).to.not.throw()); - }); - it('should throw for invalid input', () => { - const invalidInputs = [42, { random: 'test' }, undefined, new BigNumber(45)]; - invalidInputs.forEach(input => expect(assert.isBoolean.bind(assert, variableName, input)).to.throw()); - }); - }); - describe('#isWeb3Provider', () => { - it('should not throw for valid input', () => { - const validInputs = [{ send: () => 45 }, { sendAsync: () => 45 }]; - validInputs.forEach(input => - expect(assert.isWeb3Provider.bind(assert, variableName, input)).to.not.throw(), - ); - }); - it('should throw for invalid input', () => { - const invalidInputs = [42, { random: 'test' }, undefined, new BigNumber(45)]; - invalidInputs.forEach(input => expect(assert.isWeb3Provider.bind(assert, variableName, input)).to.throw()); - }); - }); - describe('#doesConformToSchema', () => { - const schema = schemas.addressSchema; - it('should not throw for valid input', () => { - const validInputs = [ - '0x6fffd0ae3f7d88c9b4925323f54c6e4b2918c5fd', - '0x12459c951127e0c374ff9105dda097662a027093', - ]; - validInputs.forEach(input => - expect(assert.doesConformToSchema.bind(assert, variableName, input, schema)).to.not.throw(), - ); - }); - it('should throw for invalid input', () => { - const invalidInputs = [42, { random: 'test' }, undefined, new BigNumber(45)]; - invalidInputs.forEach(input => - expect(assert.doesConformToSchema.bind(assert, variableName, input, schema)).to.throw(), - ); - }); - }); - describe('#isWebUri', () => { - it('should not throw for valid input', () => { - const validInputs = [ - 'http://www.google.com', - 'https://api.example-relayer.net', - 'https://api.radarrelay.com/0x/v0/', - 'https://zeroex.beta.radarrelay.com:8000/0x/v0/', - ]; - validInputs.forEach(input => expect(assert.isWebUri.bind(assert, variableName, input)).to.not.throw()); - }); - it('should throw for invalid input', () => { - const invalidInputs = [ - 42, - { random: 'test' }, - undefined, - new BigNumber(45), - 'ws://www.api.example-relayer.net', - 'www.google.com', - 'api.example-relayer.net', - 'user:password@api.example-relayer.net', - '//api.example-relayer.net', - ]; - invalidInputs.forEach(input => expect(assert.isWebUri.bind(assert, variableName, input)).to.throw()); - }); - }); - describe('#isUri', () => { - it('should not throw for valid input', () => { - const validInputs = [ - 'http://www.google.com', - 'https://api.example-relayer.net', - 'https://api.radarrelay.com/0x/v0/', - 'https://zeroex.beta.radarrelay.com:8000/0x/v0/', - 'ws://www.api.example-relayer.net', - 'wss://www.api.example-relayer.net', - 'user:password@api.example-relayer.net', - ]; - validInputs.forEach(input => expect(assert.isUri.bind(assert, variableName, input)).to.not.throw()); - }); - it('should throw for invalid input', () => { - const invalidInputs = [ - 42, - { random: 'test' }, - undefined, - new BigNumber(45), - 'www.google.com', - 'api.example-relayer.net', - '//api.example-relayer.net', - ]; - invalidInputs.forEach(input => expect(assert.isUri.bind(assert, variableName, input)).to.throw()); - }); - }); - describe('#assert', () => { - const assertMessage = 'assert not satisfied'; - it('should not throw for valid input', () => { - expect(assert.assert.bind(assert, true, assertMessage)).to.not.throw(); - }); - it('should throw for invalid input', () => { - expect(assert.assert.bind(assert, false, assertMessage)).to.throw(); - }); - }); - describe('#typeAssertionMessage', () => { - it('should render correct message', () => { - expect(assert.typeAssertionMessage('variable', 'string', 'number')).to.equal( - `Expected variable to be of type string, encountered: number`, - ); - }); - }); -}); -// tslint:enable:custom-no-magic-numbers diff --git a/packages/assert/tsconfig.json b/packages/assert/tsconfig.json deleted file mode 100644 index 2ee711adcc..0000000000 --- a/packages/assert/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../tsconfig", - "compilerOptions": { - "outDir": "lib", - "rootDir": "." - }, - "include": ["./src/**/*", "./test/**/*"] -} diff --git a/packages/assert/tslint.json b/packages/assert/tslint.json deleted file mode 100644 index dd9053357e..0000000000 --- a/packages/assert/tslint.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": ["@0x/tslint-config"] -} diff --git a/packages/base-contract/.npmignore b/packages/base-contract/.npmignore deleted file mode 100644 index 760ab23334..0000000000 --- a/packages/base-contract/.npmignore +++ /dev/null @@ -1,10 +0,0 @@ -# Blacklist all files -.* -* -# Whitelist lib -!lib/**/* -# Blacklist tests and publish scripts -/lib/test/* -/lib/monorepo_scripts/ -# Package specific ignore - diff --git a/packages/base-contract/CHANGELOG.json b/packages/base-contract/CHANGELOG.json deleted file mode 100644 index 278b6f9387..0000000000 --- a/packages/base-contract/CHANGELOG.json +++ /dev/null @@ -1,765 +0,0 @@ -[ - { - "timestamp": 1594788383, - "version": "6.2.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1592969527, - "version": "6.2.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1582623685, - "version": "6.2.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "6.2.0", - "changes": [ - { - "note": "Ignore bytecode with unlinked library references in constructor", - "pr": 2463 - }, - { - "note": "Add exported function `linkLibrariesInBytecode()`", - "pr": 2463 - } - ], - "timestamp": 1581204851 - }, - { - "timestamp": 1580988106, - "version": "6.1.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "6.1.1", - "changes": [ - { - "note": "Throw Error when revert is StringRevertError", - "pr": 2453 - } - ], - "timestamp": 1580811564 - }, - { - "version": "6.1.0", - "changes": [ - { - "note": "Support catching empty reverts on live networks.", - "pr": 2433 - } - ], - "timestamp": 1579682890 - }, - { - "timestamp": 1578272714, - "version": "6.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1576540892, - "version": "6.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1575931811, - "version": "6.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "6.0.0", - "changes": [ - { - "note": "Moved shared logic into `BaseContract` helpers to reduce size.", - "pr": 2343 - }, - { - "note": "Make `evmExecAsync` protected and rename to `_evmExecAsync`", - "pr": 2243 - }, - { - "note": "Remove duplicate types `IndexedFilterValues`, `DecodedLogEvent`, `EventCallback`", - "pr": 2243 - }, - { - "note": "Added ContractFunctionObj type and supporting types", - "pr": 2325 - }, - { - "note": "Added AwaitTransactionSuccessOpts and SendTransactionOpts", - "pr": 2325 - }, - { - "note": "Automatically decode and throw rich reverts in `_throwIfRevertWithReasonCallResult`", - "pr": 1761 - }, - { - "note": "Remove dependency on ethers.js", - "pr": 1761 - }, - { - "note": "Add more RevertError decoding functions", - "pr": 1819 - }, - { - "note": "Make the Promise returned by `awaitTransactionSuccessAsync` compatible with base Promise type", - "pr": 1885 - }, - { - "note": "Properly encode `BigNumber` indexed filter values in `getTopicsForIndexedArgs()`", - "pr": 2155 - } - ], - "timestamp": 1575296764 - }, - { - "version": "5.5.0-beta.4", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1575290197 - }, - { - "version": "5.5.0-beta.3", - "changes": [ - { - "note": "Moved shared logic into `BaseContract` helpers to reduce size.", - "pr": 2343 - } - ], - "timestamp": 1574238768 - }, - { - "version": "5.5.0-beta.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1574030254 - }, - { - "version": "5.5.0-beta.1", - "changes": [ - { - "note": "Make `evmExecAsync` protected and rename to `_evmExecAsync`", - "pr": 2243 - }, - { - "note": "Remove duplicate types `IndexedFilterValues`, `DecodedLogEvent`, `EventCallback`", - "pr": 2243 - }, - { - "note": "Added ContractFunctionObj type and supporting types", - "pr": 2325 - }, - { - "note": "Added AwaitTransactionSuccessOpts and SendTransactionOpts", - "pr": 2325 - } - ], - "timestamp": 1573159180 - }, - { - "version": "5.5.0-beta.0", - "changes": [ - { - "note": "Automatically decode and throw rich reverts in `_throwIfRevertWithReasonCallResult`", - "pr": 1761 - }, - { - "note": "Remove dependency on ethers.js", - "pr": 1761 - }, - { - "note": "Add more RevertError decoding functions", - "pr": 1819 - }, - { - "note": "Make the Promise returned by `awaitTransactionSuccessAsync` compatible with base Promise type", - "pr": 1885 - }, - { - "note": "Properly encode `BigNumber` indexed filter values in `getTopicsForIndexedArgs()`", - "pr": 2155 - } - ], - "timestamp": 1570135330 - }, - { - "version": "5.4.0", - "changes": [ - { - "note": "Add `evmExecAsync` to use local EVM instead of eth_call for pure functions", - "pr": 2108 - } - ], - "timestamp": 1568744790 - }, - { - "timestamp": 1567521715, - "version": "5.3.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "5.3.2", - "changes": [ - { - "note": "Updated to ethereumjs-blockstream@^7.0.0", - "pr": 2089 - } - ], - "timestamp": 1566446343 - }, - { - "timestamp": 1565296576, - "version": "5.3.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "5.3.0", - "changes": [ - { - "note": "Updated interface to `deployFrom0xArtifactAsync` to include log decode dependencies.", - "pr": 1995 - }, - { - "note": "Updated interface to `deployAsync` to include log decode dependencies.", - "pr": 1995 - } - ], - "timestamp": 1564604963 - }, - { - "version": "5.2.0", - "changes": [ - { - "note": "Add SubscriptionManager", - "pr": 1970 - } - ] - }, - { - "timestamp": 1563957393, - "version": "5.1.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563006338, - "version": "5.1.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "5.1.0", - "changes": [ - { - "note": "Export `PromiseWithTransactionHash` type", - "pr": 1797 - } - ], - "timestamp": 1557507213 - }, - { - "version": "5.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1554997931 - }, - { - "timestamp": 1553183790, - "version": "5.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1553091633, - "version": "5.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551479279, - "version": "5.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551220833, - "version": "5.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "5.0.0", - "changes": [ - { - "note": "Add support for EIP1193 providers & Web3.js providers >= 1.0-beta.38", - "pr": 1627 - }, - { - "note": "Update provider params to type SupportedProvider which outlines all supported providers", - "pr": 1627 - } - ], - "timestamp": 1551130135 - }, - { - "timestamp": 1549733923, - "version": "4.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "4.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1549547375 - }, - { - "timestamp": 1549452781, - "version": "4.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "4.0.0", - "changes": [ - { - "note": "Upgrade the bignumber.js to v8.0.2", - "pr": 1517 - } - ], - "timestamp": 1549373905 - }, - { - "timestamp": 1547561734, - "version": "3.0.13", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547225310, - "version": "3.0.12", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547040760, - "version": "3.0.11", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.0.10", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544739608 - }, - { - "version": "3.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544570656 - }, - { - "timestamp": 1543401373, - "version": "3.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542821676, - "version": "3.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542208198, - "version": "3.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542134075, - "version": "3.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542028948, - "version": "3.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1541740904 - }, - { - "timestamp": 1539871071, - "version": "3.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1538693146 - }, - { - "version": "3.0.0", - "changes": [ - { - "note": "Change the way we detect BN to work with the newest ethers.js", - "pr": 1069 - }, - { - "note": "Add baseContract._throwIfRevertWithReasonCallResult", - "pr": 1069 - } - ], - "timestamp": 1538157789 - }, - { - "timestamp": 1537907159, - "version": "2.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537875740, - "version": "2.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537541580, - "version": "2.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1536142250, - "version": "2.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1535377027, - "version": "2.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1535133899, - "version": "2.0.0", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.0-rc.1", - "changes": [ - { - "pr": 915, - "note": "Added strict encoding/decoding checks for sendTransaction and call" - } - ], - "timestamp": 1534210131 - }, - { - "timestamp": 1532619515, - "version": "1.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532614997, - "version": "1.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532605697, - "version": "1.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532357734, - "version": "1.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532043000, - "version": "1.0.0", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1531919263, - "version": "0.3.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1531149657, - "version": "0.3.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.3.4", - "changes": [ - { - "note": "Update EthersJs to fix the `value.toLowerCase()` is not a function bug caused by `ethers.js` breaking patch version https://github.com/ethers-io/ethers.js/issues/201" - } - ], - "timestamp": 1529397769 - }, - { - "timestamp": 1527810075, - "version": "0.3.3", - "changes": [ - { - "note": "Incorrect publish that was unpublished" - } - ] - }, - { - "timestamp": 1527008270, - "version": "0.3.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1525477860, - "version": "0.3.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.3.0", - "changes": [ - { - "note": "Update ethers-contracts to ethers.js", - "pr": 540 - } - ], - "timestamp": 1525428773 - }, - { - "timestamp": 1524044013, - "version": "0.2.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.2.0", - "changes": [ - { - "note": "Contract wrappers now accept Provider and defaults instead of Web3Wrapper", - "pr": 501 - } - ], - "timestamp": 1523462196 - }, - { - "version": "0.1.0", - "changes": [ - { - "note": "Add tests for traversing ABI tree", - "pr": 485 - }, - { - "note": "Fix ABI tuples traversing", - "pr": 485 - }, - { - "note": "Fix ABI arrays traversing", - "pr": 485 - } - ], - "timestamp": 1522673609 - }, - { - "timestamp": 1522658513, - "version": "0.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.0.2", - "changes": [ - { - "note": "Initial release" - } - ], - "timestamp": 1520089200 - } -] diff --git a/packages/base-contract/CHANGELOG.md b/packages/base-contract/CHANGELOG.md deleted file mode 100644 index f1c1063cce..0000000000 --- a/packages/base-contract/CHANGELOG.md +++ /dev/null @@ -1,320 +0,0 @@ - - -CHANGELOG - -## v6.2.3 - _July 15, 2020_ - - * Dependencies updated - -## v6.2.2 - _June 24, 2020_ - - * Dependencies updated - -## v6.2.1 - _February 25, 2020_ - - * Dependencies updated - -## v6.2.0 - _February 8, 2020_ - - * Ignore bytecode with unlinked library references in constructor (#2463) - * Add exported function `linkLibrariesInBytecode()` (#2463) - -## v6.1.2 - _February 6, 2020_ - - * Dependencies updated - -## v6.1.1 - _February 4, 2020_ - - * Throw Error when revert is StringRevertError (#2453) - -## v6.1.0 - _January 22, 2020_ - - * Support catching empty reverts on live networks. (#2433) - -## v6.0.3 - _January 6, 2020_ - - * Dependencies updated - -## v6.0.2 - _December 17, 2019_ - - * Dependencies updated - -## v6.0.1 - _December 9, 2019_ - - * Dependencies updated - -## v6.0.0 - _December 2, 2019_ - - * Moved shared logic into `BaseContract` helpers to reduce size. (#2343) - * Make `evmExecAsync` protected and rename to `_evmExecAsync` (#2243) - * Remove duplicate types `IndexedFilterValues`, `DecodedLogEvent`, `EventCallback` (#2243) - * Added ContractFunctionObj type and supporting types (#2325) - * Added AwaitTransactionSuccessOpts and SendTransactionOpts (#2325) - * Automatically decode and throw rich reverts in `_throwIfRevertWithReasonCallResult` (#1761) - * Remove dependency on ethers.js (#1761) - * Add more RevertError decoding functions (#1819) - * Make the Promise returned by `awaitTransactionSuccessAsync` compatible with base Promise type (#1885) - * Properly encode `BigNumber` indexed filter values in `getTopicsForIndexedArgs()` (#2155) - -## v5.5.0-beta.4 - _December 2, 2019_ - - * Dependencies updated - -## v5.5.0-beta.3 - _November 20, 2019_ - - * Moved shared logic into `BaseContract` helpers to reduce size. (#2343) - -## v5.5.0-beta.2 - _November 17, 2019_ - - * Dependencies updated - -## v5.5.0-beta.1 - _November 7, 2019_ - - * Make `evmExecAsync` protected and rename to `_evmExecAsync` (#2243) - * Remove duplicate types `IndexedFilterValues`, `DecodedLogEvent`, `EventCallback` (#2243) - * Added ContractFunctionObj type and supporting types (#2325) - * Added AwaitTransactionSuccessOpts and SendTransactionOpts (#2325) - -## v5.5.0-beta.0 - _October 3, 2019_ - - * Automatically decode and throw rich reverts in `_throwIfRevertWithReasonCallResult` (#1761) - * Remove dependency on ethers.js (#1761) - * Add more RevertError decoding functions (#1819) - * Make the Promise returned by `awaitTransactionSuccessAsync` compatible with base Promise type (#1885) - * Properly encode `BigNumber` indexed filter values in `getTopicsForIndexedArgs()` (#2155) - -## v5.4.0 - _September 17, 2019_ - - * Add `evmExecAsync` to use local EVM instead of eth_call for pure functions (#2108) - -## v5.3.3 - _September 3, 2019_ - - * Dependencies updated - -## v5.3.2 - _August 22, 2019_ - - * Updated to ethereumjs-blockstream@^7.0.0 (#2089) - -## v5.3.1 - _August 8, 2019_ - - * Dependencies updated - -## v5.3.0 - _July 31, 2019_ - - * Updated interface to `deployFrom0xArtifactAsync` to include log decode dependencies. (#1995) - * Updated interface to `deployAsync` to include log decode dependencies. (#1995) - -## v5.2.0 - _Invalid date_ - - * Add SubscriptionManager (#1970) - -## v5.1.2 - _July 24, 2019_ - - * Dependencies updated - -## v5.1.1 - _July 13, 2019_ - - * Dependencies updated - -## v5.1.0 - _May 10, 2019_ - - * Export `PromiseWithTransactionHash` type (#1797) - -## v5.0.5 - _April 11, 2019_ - - * Dependencies updated - -## v5.0.4 - _March 21, 2019_ - - * Dependencies updated - -## v5.0.3 - _March 20, 2019_ - - * Dependencies updated - -## v5.0.2 - _March 1, 2019_ - - * Dependencies updated - -## v5.0.1 - _February 26, 2019_ - - * Dependencies updated - -## v5.0.0 - _February 25, 2019_ - - * Add support for EIP1193 providers & Web3.js providers >= 1.0-beta.38 (#1627) - * Update provider params to type SupportedProvider which outlines all supported providers (#1627) - -## v4.0.3 - _February 9, 2019_ - - * Dependencies updated - -## v4.0.2 - _February 7, 2019_ - - * Dependencies updated - -## v4.0.1 - _February 6, 2019_ - - * Dependencies updated - -## v4.0.0 - _February 5, 2019_ - - * Upgrade the bignumber.js to v8.0.2 (#1517) - -## v3.0.13 - _January 15, 2019_ - - * Dependencies updated - -## v3.0.12 - _January 11, 2019_ - - * Dependencies updated - -## v3.0.11 - _January 9, 2019_ - - * Dependencies updated - -## v3.0.10 - _December 13, 2018_ - - * Dependencies updated - -## v3.0.9 - _December 11, 2018_ - - * Dependencies updated - -## v3.0.8 - _November 28, 2018_ - - * Dependencies updated - -## v3.0.7 - _November 21, 2018_ - - * Dependencies updated - -## v3.0.6 - _November 14, 2018_ - - * Dependencies updated - -## v3.0.5 - _November 13, 2018_ - - * Dependencies updated - -## v3.0.4 - _November 12, 2018_ - - * Dependencies updated - -## v3.0.3 - _November 9, 2018_ - - * Dependencies updated - -## v3.0.2 - _October 18, 2018_ - - * Dependencies updated - -## v3.0.1 - _October 4, 2018_ - - * Dependencies updated - -## v3.0.0 - _September 28, 2018_ - - * Change the way we detect BN to work with the newest ethers.js (#1069) - * Add baseContract._throwIfRevertWithReasonCallResult (#1069) - -## v2.0.5 - _September 25, 2018_ - - * Dependencies updated - -## v2.0.4 - _September 25, 2018_ - - * Dependencies updated - -## v2.0.3 - _September 21, 2018_ - - * Dependencies updated - -## v2.0.2 - _September 5, 2018_ - - * Dependencies updated - -## v2.0.1 - _August 27, 2018_ - - * Dependencies updated - -## v2.0.0 - _August 24, 2018_ - - * Dependencies updated - -## v2.0.0-rc.1 - _August 14, 2018_ - - * Added strict encoding/decoding checks for sendTransaction and call (#915) - -## v1.0.4 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.3 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.2 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.1 - _July 23, 2018_ - - * Dependencies updated - -## v1.0.0 - _July 19, 2018_ - - * Dependencies updated - -## v0.3.6 - _July 18, 2018_ - - * Dependencies updated - -## v0.3.5 - _July 9, 2018_ - - * Dependencies updated - -## v0.3.4 - _June 19, 2018_ - - * Update EthersJs to fix the `value.toLowerCase()` is not a function bug caused by `ethers.js` breaking patch version https://github.com/ethers-io/ethers.js/issues/201 - -## v0.3.3 - _May 31, 2018_ - - * Incorrect publish that was unpublished - -## v0.3.2 - _May 22, 2018_ - - * Dependencies updated - -## v0.3.1 - _May 4, 2018_ - - * Dependencies updated - -## v0.3.0 - _May 4, 2018_ - - * Update ethers-contracts to ethers.js (#540) - -## v0.2.1 - _April 18, 2018_ - - * Dependencies updated - -## v0.2.0 - _April 11, 2018_ - - * Contract wrappers now accept Provider and defaults instead of Web3Wrapper (#501) - -## v0.1.0 - _April 2, 2018_ - - * Add tests for traversing ABI tree (#485) - * Fix ABI tuples traversing (#485) - * Fix ABI arrays traversing (#485) - -## v0.0.6 - _April 2, 2018_ - - * Dependencies updated - -## v0.0.2 - _March 3, 2018_ - - * Initial release diff --git a/packages/base-contract/README.md b/packages/base-contract/README.md deleted file mode 100644 index b6ea05b740..0000000000 --- a/packages/base-contract/README.md +++ /dev/null @@ -1,63 +0,0 @@ -## @0x/base-contract - -BaseContract to derive all auto-generated wrappers from - -## Installation - -```bash -yarn add @0x/base-contract -``` - -If your project is in [TypeScript](https://www.typescriptlang.org/), add the following to your `tsconfig.json`: - -```json -"compilerOptions": { - "typeRoots": ["node_modules/@0x/typescript-typings/types", "node_modules/@types"], -} -``` - -## Usage - -```javascript -import { BaseContract } from '@0x/base-contract'; -``` - -## Contributing - -We strongly recommend that the community help us make improvements and determine the future direction of the protocol. To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install Dependencies - -If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: - -```bash -yarn config set workspaces-experimental true -``` - -Then install dependencies - -```bash -yarn install -``` - -### Build - -To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory: - -```bash -PKG=@0x/base-contract yarn build -``` - -Or continuously rebuild on change: - -```bash -PKG=@0x/base-contract yarn watch -``` - -### Lint - -```bash -yarn lint -``` diff --git a/packages/base-contract/coverage/.gitkeep b/packages/base-contract/coverage/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/base-contract/package.json b/packages/base-contract/package.json deleted file mode 100644 index 12cf35f607..0000000000 --- a/packages/base-contract/package.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "name": "@0x/base-contract", - "version": "6.2.3", - "engines": { - "node": ">=6.12" - }, - "description": "0x Base TS contract", - "main": "lib/src/index.js", - "types": "lib/src/index.d.ts", - "scripts": { - "build": "tsc -b", - "build:ci": "yarn build", - "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 --format stylish --project .", - "fix": "tslint --format stylish --fix --project ." - }, - "license": "Apache-2.0", - "repository": { - "type": "git", - "url": "https://github.com/0xProject/0x-monorepo.git" - }, - "bugs": { - "url": "https://github.com/0xProject/0x-monorepo/issues" - }, - "homepage": "https://github.com/0xProject/0x-monorepo/packages/base-contract/README.md", - "devDependencies": { - "@0x/tslint-config": "^4.1.0", - "@0x/types": "^3.2.0", - "@0x/typescript-typings": "^5.1.1", - "@types/lodash": "4.14.104", - "@types/mocha": "^5.2.7", - "chai": "^4.0.1", - "ethereum-types": "^3.2.0", - "make-promises-safe": "^1.1.0", - "mocha": "^6.2.0", - "npm-run-all": "^4.1.2", - "shx": "^0.2.2", - "tslint": "5.11.0", - "typescript": "3.0.1" - }, - "dependencies": { - "@0x/assert": "^3.0.9", - "@0x/json-schemas": "^5.1.0", - "@0x/utils": "^5.5.1", - "@0x/web3-wrapper": "^7.2.0", - "ethereumjs-account": "^3.0.0", - "ethereumjs-blockstream": "^7.0.0", - "ethereumjs-util": "^5.1.1", - "ethereumjs-vm": "^4.0.0", - "ethers": "~4.0.4", - "js-sha3": "^0.7.0", - "uuid": "^3.3.2" - }, - "resolutions": { - "merkle-patricia-tree": "^2.3.2" - }, - "publishConfig": { - "access": "public" - }, - "gitHead": "4f91bfd907996b2f4dd383778b50c479c2602b56" -} diff --git a/packages/base-contract/src/globals.d.ts b/packages/base-contract/src/globals.d.ts deleted file mode 100644 index 94e63a32de..0000000000 --- a/packages/base-contract/src/globals.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -declare module '*.json' { - const json: any; - /* tslint:disable */ - export default json; - /* tslint:enable */ -} diff --git a/packages/base-contract/src/index.ts b/packages/base-contract/src/index.ts deleted file mode 100644 index 83313bf027..0000000000 --- a/packages/base-contract/src/index.ts +++ /dev/null @@ -1,405 +0,0 @@ -import { assert } from '@0x/assert'; -import { schemas } from '@0x/json-schemas'; -import { - AbiEncoder, - abiUtils, - BigNumber, - decodeBytesAsRevertError, - decodeThrownErrorAsRevertError, - providerUtils, - RevertError, - StringRevertError, -} from '@0x/utils'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import { - AbiDefinition, - AbiType, - BlockParam, - CallData, - ConstructorAbi, - ContractAbi, - DataItem, - MethodAbi, - SupportedProvider, - TransactionReceiptWithDecodedLogs, - TxData, - TxDataPayable, -} from 'ethereum-types'; -import Account from 'ethereumjs-account'; -import * as util from 'ethereumjs-util'; -import { default as VM } from 'ethereumjs-vm'; -import PStateManager from 'ethereumjs-vm/dist/state/promisified'; - -export { linkLibrariesInBytecode, methodAbiToFunctionSignature } from './utils'; - -import { AwaitTransactionSuccessOpts } from './types'; -import { formatABIDataItem } from './utils'; - -export { SubscriptionManager } from './subscription_manager'; - -export { - ContractEvent, - SendTransactionOpts, - AwaitTransactionSuccessOpts, - ContractFunctionObj, - ContractTxFunctionObj, - SubscriptionErrors, -} from './types'; - -export interface AbiEncoderByFunctionSignature { - [key: string]: AbiEncoder.Method; -} - -const ARBITRARY_PRIVATE_KEY = 'e331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109'; - -// tslint:disable: max-classes-per-file -/** - * @dev A promise-compatible type that exposes a `txHash` field. - * Not used by BaseContract, but generated contracts will return it in - * `awaitTransactionSuccessAsync()`. - * Maybe there's a better place for this. - */ -export class PromiseWithTransactionHash implements Promise { - public readonly txHashPromise: Promise; - private readonly _promise: Promise; - constructor(txHashPromise: Promise, promise: Promise) { - this.txHashPromise = txHashPromise; - this._promise = promise; - } - // tslint:disable:promise-function-async - // tslint:disable:async-suffix - public then( - onFulfilled?: (v: T) => TResult | Promise, - onRejected?: (reason: any) => Promise, - ): Promise { - return this._promise.then(onFulfilled, onRejected); - } - public catch(onRejected?: (reason: any) => Promise): Promise { - return this._promise.catch(onRejected); - } - public finally(onFinally?: (() => void) | null): Promise { - return this._promise.finally(onFinally); - } - // tslint:enable:promise-function-async - // tslint:enable:async-suffix - get [Symbol.toStringTag](): 'Promise' { - return this._promise[Symbol.toStringTag]; - } -} - -export class BaseContract { - protected _abiEncoderByFunctionSignature: AbiEncoderByFunctionSignature; - protected _web3Wrapper: Web3Wrapper; - public abi: ContractAbi; - public address: string; - public contractName: string; - public constructorArgs: any[] = []; - public _deployedBytecodeIfExists?: Buffer; - private _evmIfExists?: VM; - private _evmAccountIfExists?: Buffer; - protected static _formatABIDataItemList( - abis: DataItem[], - values: any[], - formatter: (type: string, value: any) => any, - ): any { - return values.map((value: any, i: number) => formatABIDataItem(abis[i], value, formatter)); - } - protected static _lowercaseAddress(type: string, value: string): string { - return type === 'address' ? value.toLowerCase() : value; - } - protected static _bigNumberToString(_type: string, value: any): any { - return BigNumber.isBigNumber(value) ? value.toString() : value; - } - protected static _lookupConstructorAbi(abi: ContractAbi): ConstructorAbi { - const constructorAbiIfExists = abi.find( - (abiDefinition: AbiDefinition) => abiDefinition.type === AbiType.Constructor, - // tslint:disable-next-line:no-unnecessary-type-assertion - ) as ConstructorAbi | undefined; - if (constructorAbiIfExists !== undefined) { - return constructorAbiIfExists; - } else { - // If the constructor is not explicitly defined, it won't be included in the ABI. It is - // still callable however, so we construct what the ABI would look like were it to exist. - const defaultConstructorAbi: ConstructorAbi = { - type: AbiType.Constructor, - stateMutability: 'nonpayable', - payable: false, - inputs: [], - }; - return defaultConstructorAbi; - } - } - protected static _throwIfCallResultIsRevertError(rawCallResult: string): void { - // Try to decode the call result as a revert error. - let revert: RevertError; - try { - revert = decodeBytesAsRevertError(rawCallResult); - } catch (err) { - // Can't decode it as a revert error, so assume it didn't revert. - return; - } - throw revert; - } - protected static _throwIfThrownErrorIsRevertError(error: Error): void { - // Try to decode a thrown error. - let revertError: RevertError; - try { - revertError = decodeThrownErrorAsRevertError(error); - } catch (err) { - // Can't decode it. - return; - } - // Re-cast StringRevertErrors as plain Errors for backwards-compatibility. - if (revertError instanceof StringRevertError) { - throw new Error(revertError.values.message as string); - } - throw revertError; - } - protected static _throwIfUnexpectedEmptyCallResult(rawCallResult: string, methodAbi: AbiEncoder.Method): void { - // With live nodes, we will receive an empty call result if: - // 1. The function has no return value. - // 2. The contract reverts without data. - // 3. The contract reverts with an invalid opcode (`assert(false)` or `invalid()`). - if (!rawCallResult || rawCallResult === '0x') { - const returnValueDataItem = methodAbi.getReturnValueDataItem(); - if (returnValueDataItem.components === undefined || returnValueDataItem.components.length === 0) { - // Expected no result (which makes it hard to tell if the call reverted). - return; - } - throw new Error(`Function "${methodAbi.getSignature()}" reverted with no data`); - } - } - // Throws if the given arguments cannot be safely/correctly encoded based on - // the given inputAbi. An argument may not be considered safely encodeable - // if it overflows the corresponding Solidity type, there is a bug in the - // encoder, or the encoder performs unsafe type coercion. - public static strictArgumentEncodingCheck(inputAbi: DataItem[], args: any[]): string { - const abiEncoder = AbiEncoder.create(inputAbi); - const params = abiUtils.parseEthersParams(inputAbi); - const rawEncoded = abiEncoder.encode(args); - const rawDecoded = abiEncoder.decodeAsArray(rawEncoded); - for (let i = 0; i < rawDecoded.length; i++) { - const original = args[i]; - const decoded = rawDecoded[i]; - if (!abiUtils.isAbiDataEqual(params.names[i], params.types[i], original, decoded)) { - throw new Error( - `Cannot safely encode argument: ${params.names[i]} (${original}) of type ${ - params.types[i] - }. (Possible type overflow or other encoding error)`, - ); - } - } - return rawEncoded; - } - protected static async _applyDefaultsToContractTxDataAsync>( - txData: T, - estimateGasAsync?: (txData: T) => Promise, - ): Promise { - const txDataWithDefaults = BaseContract._removeUndefinedProperties(txData); - if (txDataWithDefaults.gas === undefined && estimateGasAsync !== undefined) { - txDataWithDefaults.gas = await estimateGasAsync(txDataWithDefaults); - } - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - return txDataWithDefaults as TxData; - } - protected static _assertCallParams(callData: Partial, defaultBlock?: BlockParam): void { - assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ - schemas.addressSchema, - schemas.numberSchema, - schemas.jsNumber, - ]); - if (defaultBlock !== undefined) { - assert.isBlockParam('defaultBlock', defaultBlock); - } - } - private static _removeUndefinedProperties(props: any): T { - const clonedProps = { ...props }; - Object.keys(clonedProps).forEach(key => clonedProps[key] === undefined && delete clonedProps[key]); - return clonedProps; - } - protected _promiseWithTransactionHash( - txHashPromise: Promise, - opts: AwaitTransactionSuccessOpts, - ): PromiseWithTransactionHash { - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return this._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - } - protected async _applyDefaultsToTxDataAsync>( - txData: T, - estimateGasAsync?: (txData: T) => Promise, - ): Promise { - // Gas amount sourced with the following priorities: - // 1. Optional param passed in to public method call - // 2. Global config passed in at library instantiation - // 3. Gas estimate calculation + safety margin - // tslint:disable-next-line:no-object-literal-type-assertion - const txDataWithDefaults = { - to: this.address, - ...this._web3Wrapper.getContractDefaults(), - ...BaseContract._removeUndefinedProperties(txData), - } as T; - if (txDataWithDefaults.gas === undefined && estimateGasAsync !== undefined) { - txDataWithDefaults.gas = await estimateGasAsync(txDataWithDefaults); - } - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - return txDataWithDefaults as TxData; - } - protected async _evmExecAsync(encodedData: string): Promise { - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - const addressBuf = Buffer.from(this.address.substr(2), 'hex'); - // should only run once, the first time it is called - if (this._evmIfExists === undefined) { - const vm = new VM({}); - const psm = new PStateManager(vm.stateManager); - - // create an account with 1 ETH - const accountPk = Buffer.from(ARBITRARY_PRIVATE_KEY, 'hex'); - const accountAddress = util.privateToAddress(accountPk); - const account = new Account({ balance: 1e18 }); - await psm.putAccount(accountAddress, account); - - // 'deploy' the contract - if (this._deployedBytecodeIfExists === undefined) { - const contractCode = await this._web3Wrapper.getContractCodeAsync(this.address); - this._deployedBytecodeIfExists = Buffer.from(contractCode.substr(2), 'hex'); - } - await psm.putContractCode(addressBuf, this._deployedBytecodeIfExists); - - // save for later - this._evmIfExists = vm; - this._evmAccountIfExists = accountAddress; - } - let rawCallResult; - try { - const result = await this._evmIfExists.runCall({ - to: addressBuf, - caller: this._evmAccountIfExists, - origin: this._evmAccountIfExists, - data: encodedDataBytes, - }); - rawCallResult = `0x${result.execResult.returnValue.toString('hex')}`; - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - return rawCallResult; - } - protected async _performCallAsync(callData: Partial, defaultBlock?: BlockParam): Promise { - const callDataWithDefaults = await this._applyDefaultsToTxDataAsync(callData); - let rawCallResult: string; - try { - rawCallResult = await this._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - return rawCallResult; - } - protected _lookupAbiEncoder(functionSignature: string): AbiEncoder.Method { - const abiEncoder = this._abiEncoderByFunctionSignature[functionSignature]; - if (abiEncoder === undefined) { - throw new Error(`Failed to lookup method with function signature '${functionSignature}'`); - } - return abiEncoder; - } - protected _lookupAbi(functionSignature: string): MethodAbi { - const methodAbi = this.abi.find((abiDefinition: AbiDefinition) => { - if (abiDefinition.type !== AbiType.Function) { - return false; - } - // tslint:disable-next-line:no-unnecessary-type-assertion - const abiFunctionSignature = new AbiEncoder.Method(abiDefinition as MethodAbi).getSignature(); - if (abiFunctionSignature === functionSignature) { - return true; - } - return false; - }) as MethodAbi; - return methodAbi; - } - protected _strictEncodeArguments(functionSignature: string, functionArguments: any): string { - const abiEncoder = this._lookupAbiEncoder(functionSignature); - const inputAbi = abiEncoder.getDataItem().components; - if (inputAbi === undefined) { - throw new Error(`Undefined Method Input ABI`); - } - const abiEncodedArguments = abiEncoder.encode(functionArguments); - return abiEncodedArguments; - } - /// @dev Constructs a contract wrapper. - /// @param contractName Name of contract. - /// @param abi of the contract. - /// @param address of the deployed contract. - /// @param supportedProvider for communicating with an ethereum node. - /// @param logDecodeDependencies the name and ABI of contracts whose event logs are - /// decoded by this wrapper. - /// @param deployedBytecode the deployedBytecode of the contract, used for executing - /// pure Solidity functions in memory. This is different from the bytecode. - constructor( - contractName: string, - abi: ContractAbi, - address: string, - supportedProvider: SupportedProvider, - callAndTxnDefaults?: Partial, - logDecodeDependencies?: { [contractName: string]: ContractAbi }, - deployedBytecode?: string, - ) { - assert.isString('contractName', contractName); - assert.isETHAddressHex('address', address); - if (deployedBytecode !== undefined && deployedBytecode !== '') { - // `deployedBytecode` might contain references to - // unlinked libraries and, hence, would not be a hex string. We'll just - // leave `_deployedBytecodeIfExists` empty if this is the case. - // TODO(dorothy-zbornak): We should link the `deployedBytecode` - // beforehand in the generated wrappers. - try { - assert.isHexString('deployedBytecode', deployedBytecode); - this._deployedBytecodeIfExists = Buffer.from(deployedBytecode.substr(2), 'hex'); - } catch (err) { - // Do nothing. - } - } - const provider = providerUtils.standardizeOrThrow(supportedProvider); - if (callAndTxnDefaults !== undefined) { - assert.doesConformToSchema('callAndTxnDefaults', callAndTxnDefaults, schemas.callDataSchema, [ - schemas.addressSchema, - schemas.numberSchema, - schemas.jsNumber, - ]); - } - this.contractName = contractName; - this._web3Wrapper = new Web3Wrapper(provider, callAndTxnDefaults); - this.abi = abi; - this.address = address; - const methodAbis = this.abi.filter( - (abiDefinition: AbiDefinition) => abiDefinition.type === AbiType.Function, - ) as MethodAbi[]; - this._abiEncoderByFunctionSignature = {}; - methodAbis.forEach(methodAbi => { - const abiEncoder = new AbiEncoder.Method(methodAbi); - const functionSignature = abiEncoder.getSignature(); - this._abiEncoderByFunctionSignature[functionSignature] = abiEncoder; - this._web3Wrapper.abiDecoder.addABI(abi, contractName); - }); - if (logDecodeDependencies) { - Object.entries(logDecodeDependencies).forEach(([dependencyName, dependencyAbi]) => - this._web3Wrapper.abiDecoder.addABI(dependencyAbi, dependencyName), - ); - } - } -} diff --git a/packages/base-contract/src/subscription_manager.ts b/packages/base-contract/src/subscription_manager.ts deleted file mode 100644 index 1bbad65356..0000000000 --- a/packages/base-contract/src/subscription_manager.ts +++ /dev/null @@ -1,196 +0,0 @@ -import { AbiDecoder, intervalUtils, logUtils } from '@0x/utils'; -import { marshaller, Web3Wrapper } from '@0x/web3-wrapper'; -import { - BlockParamLiteral, - BlockRange, - ContractAbi, - FilterObject, - LogEntry, - LogWithDecodedArgs, - RawLog, - RawLogEntry, -} from 'ethereum-types'; -import { Block, BlockAndLogStreamer, Log } from 'ethereumjs-blockstream'; - -import { EventCallback, IndexedFilterValues } from '@0x/types'; - -import { SubscriptionErrors } from './types'; -import { filterUtils } from './utils/filter_utils'; - -const DEFAULT_BLOCK_POLLING_INTERVAL = 1000; - -export class SubscriptionManager { - public abi: ContractAbi; - private _blockAndLogStreamerIfExists: BlockAndLogStreamer | undefined; - private _blockAndLogStreamIntervalIfExists?: NodeJS.Timer; - private readonly _web3Wrapper: Web3Wrapper; - private readonly _filters: { [filterToken: string]: FilterObject }; - private readonly _filterCallbacks: { - [filterToken: string]: EventCallback; - }; - private _onLogAddedSubscriptionToken: string | undefined; - private _onLogRemovedSubscriptionToken: string | undefined; - private static _onBlockAndLogStreamerError(isVerbose: boolean, err: Error): void { - // Since Blockstream errors are all recoverable, we simply log them if the verbose - // config is passed in. - if (isVerbose) { - logUtils.warn(err); - } - } - constructor(abi: ContractAbi, web3Wrapper: Web3Wrapper) { - this.abi = abi; - this._web3Wrapper = web3Wrapper; - this._filters = {}; - this._filterCallbacks = {}; - this._blockAndLogStreamerIfExists = undefined; - this._onLogAddedSubscriptionToken = undefined; - this._onLogRemovedSubscriptionToken = undefined; - } - public unsubscribeAll(): void { - const filterTokens = Object.keys(this._filterCallbacks); - filterTokens.forEach(filterToken => this.unsubscribe(filterToken)); - } - public unsubscribe(filterToken: string, err?: Error): void { - if (this._filters[filterToken] === undefined) { - throw new Error(SubscriptionErrors.SubscriptionNotFound); - } - if (err !== undefined) { - const callback = this._filterCallbacks[filterToken]; - callback(err, undefined); - } - delete this._filters[filterToken]; - delete this._filterCallbacks[filterToken]; - if (Object.keys(this._filters).length === 0) { - this._stopBlockAndLogStream(); - } - } - public subscribe( - address: string, - eventName: ContractEvents, - indexFilterValues: IndexedFilterValues, - abi: ContractAbi, - callback: EventCallback, - isVerbose: boolean = false, - blockPollingIntervalMs?: number, - ): string { - const filter = filterUtils.getFilter(address, eventName, indexFilterValues, abi); - if (this._blockAndLogStreamerIfExists === undefined) { - this._startBlockAndLogStream(isVerbose, blockPollingIntervalMs); - } - const filterToken = filterUtils.generateUUID(); - this._filters[filterToken] = filter; - this._filterCallbacks[filterToken] = callback as EventCallback; // tslint:disable-line:no-unnecessary-type-assertion - return filterToken; - } - public async getLogsAsync( - address: string, - eventName: ContractEvents, - blockRange: BlockRange, - indexFilterValues: IndexedFilterValues, - abi: ContractAbi, - ): Promise>> { - const filter = filterUtils.getFilter(address, eventName, indexFilterValues, abi, blockRange); - const logs = await this._web3Wrapper.getLogsAsync(filter); - const logsWithDecodedArguments = logs.map(this._tryToDecodeLogOrNoop.bind(this)) as any[]; - return logsWithDecodedArguments; - } - protected _tryToDecodeLogOrNoop( - log: LogEntry, - ): LogWithDecodedArgs | RawLog { - const abiDecoder = new AbiDecoder([this.abi]); - const logWithDecodedArgs = abiDecoder.tryToDecodeLogOrNoop(log); - return logWithDecodedArgs; - } - private _onLogStateChanged( - isRemoved: boolean, - blockHash: string, - rawLogs: RawLogEntry[], - ): void { - const logs: LogEntry[] = rawLogs.map(rawLog => marshaller.unmarshalLog(rawLog)); - logs.forEach(log => { - Object.entries(this._filters).forEach(([filterToken, filter]) => { - if (filterUtils.matchesFilter(log, filter)) { - const decodedLog = this._tryToDecodeLogOrNoop(log) as LogWithDecodedArgs; - const logEvent = { - log: decodedLog, - isRemoved, - }; - this._filterCallbacks[filterToken](null, logEvent); - } - }); - }); - } - private _startBlockAndLogStream(isVerbose: boolean, blockPollingIntervalMs?: number): void { - if (this._blockAndLogStreamerIfExists !== undefined) { - throw new Error(SubscriptionErrors.SubscriptionAlreadyPresent); - } - this._blockAndLogStreamerIfExists = new BlockAndLogStreamer( - this._blockstreamGetBlockOrNullAsync.bind(this), - this._blockstreamGetLogsAsync.bind(this), - SubscriptionManager._onBlockAndLogStreamerError.bind(this, isVerbose), - ); - const catchAllLogFilter = {}; - this._blockAndLogStreamerIfExists.addLogFilter(catchAllLogFilter); - const _blockPollingIntervalMs = - blockPollingIntervalMs === undefined ? DEFAULT_BLOCK_POLLING_INTERVAL : blockPollingIntervalMs; - this._blockAndLogStreamIntervalIfExists = intervalUtils.setAsyncExcludingInterval( - this._reconcileBlockAsync.bind(this), - _blockPollingIntervalMs, - SubscriptionManager._onBlockAndLogStreamerError.bind(this, isVerbose), - ); - let isRemoved = false; - this._onLogAddedSubscriptionToken = this._blockAndLogStreamerIfExists.subscribeToOnLogsAdded( - this._onLogStateChanged.bind(this, isRemoved), - ); - isRemoved = true; - this._onLogRemovedSubscriptionToken = this._blockAndLogStreamerIfExists.subscribeToOnLogsRemoved( - this._onLogStateChanged.bind(this, isRemoved), - ); - } - // This method only exists in order to comply with the expected interface of Blockstream's constructor - private async _blockstreamGetBlockOrNullAsync(hash: string): Promise { - const shouldIncludeTransactionData = false; - const blockOrNull = await this._web3Wrapper.sendRawPayloadAsync({ - method: 'eth_getBlockByHash', - params: [hash, shouldIncludeTransactionData], - }); - return blockOrNull; - } - // This method only exists in order to comply with the expected interface of Blockstream's constructor - private async _blockstreamGetLatestBlockOrNullAsync(): Promise { - const shouldIncludeTransactionData = false; - const blockOrNull = await this._web3Wrapper.sendRawPayloadAsync({ - method: 'eth_getBlockByNumber', - params: [BlockParamLiteral.Latest, shouldIncludeTransactionData], - }); - return blockOrNull; - } - // This method only exists in order to comply with the expected interface of Blockstream's constructor - private async _blockstreamGetLogsAsync(filterOptions: FilterObject): Promise { - const logs = await this._web3Wrapper.sendRawPayloadAsync({ - method: 'eth_getLogs', - params: [filterOptions], - }); - return logs as RawLogEntry[]; - } - private _stopBlockAndLogStream(): void { - if (this._blockAndLogStreamerIfExists === undefined) { - throw new Error(SubscriptionErrors.SubscriptionNotFound); - } - this._blockAndLogStreamerIfExists.unsubscribeFromOnLogsAdded(this._onLogAddedSubscriptionToken as string); - this._blockAndLogStreamerIfExists.unsubscribeFromOnLogsRemoved(this._onLogRemovedSubscriptionToken as string); - intervalUtils.clearAsyncExcludingInterval(this._blockAndLogStreamIntervalIfExists as NodeJS.Timer); - delete this._blockAndLogStreamerIfExists; - } - private async _reconcileBlockAsync(): Promise { - const latestBlockOrNull = await this._blockstreamGetLatestBlockOrNullAsync(); - if (latestBlockOrNull === null) { - return; // noop - } - // We need to coerce to Block type cause Web3.Block includes types for mempool blocks - if (this._blockAndLogStreamerIfExists !== undefined) { - // If we clear the interval while fetching the block - this._blockAndLogStreamer will be undefined - await this._blockAndLogStreamerIfExists.reconcileNewBlock(latestBlockOrNull); - } - } -} diff --git a/packages/base-contract/src/types.ts b/packages/base-contract/src/types.ts deleted file mode 100644 index e834668e46..0000000000 --- a/packages/base-contract/src/types.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { BlockParam, CallData, LogEntryEvent, TransactionReceiptWithDecodedLogs, TxData } from 'ethereum-types'; - -import { PromiseWithTransactionHash } from './index'; - -export type LogEvent = LogEntryEvent; - -export interface ContractEvent { - logIndex: number; - transactionIndex: number; - transactionHash: string; - blockHash: string; - blockNumber: number; - address: string; - type: string; - event: string; - args: ContractEventArgs; -} - -export enum SubscriptionErrors { - SubscriptionNotFound = 'SUBSCRIPTION_NOT_FOUND', - SubscriptionAlreadyPresent = 'SUBSCRIPTION_ALREADY_PRESENT', -} - -/** - * Used with `sendTransactionAsync` - * * shouldValidate: Flag indicating whether the library should make attempts to validate a transaction before - * broadcasting it. For example, order has a valid signature, maker has sufficient funds, etc. Default=true. - */ -export interface SendTransactionOpts { - shouldValidate?: boolean; -} - -/** - * Used with `awaitTransactionSuccessAsync` - * * pollingIntervalMs: Determine polling intervals in milliseconds - * * timeoutMs: Determines timeout in milliseconds - */ -export interface AwaitTransactionSuccessOpts extends SendTransactionOpts { - pollingIntervalMs?: number; - timeoutMs?: number; -} - -export interface ContractFunctionObj { - callAsync(callData?: Partial, defaultBlock?: BlockParam): Promise; - getABIEncodedTransactionData(): string; -} - -export interface ContractTxFunctionObj extends ContractFunctionObj { - sendTransactionAsync(txData?: Partial, opts?: SendTransactionOpts): Promise; - awaitTransactionSuccessAsync( - txData?: Partial, - opts?: AwaitTransactionSuccessOpts, - ): PromiseWithTransactionHash; - estimateGasAsync(txData?: Partial): Promise; -} diff --git a/packages/base-contract/src/utils.ts b/packages/base-contract/src/utils.ts deleted file mode 100644 index 0f6bda3246..0000000000 --- a/packages/base-contract/src/utils.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { AbiEncoder } from '@0x/utils'; -import { ContractArtifact, DataItem, MethodAbi } from 'ethereum-types'; - -// tslint:disable-next-line:completed-docs -export function formatABIDataItem(abi: DataItem, value: any, formatter: (type: string, value: any) => any): any { - const trailingArrayRegex = /\[\d*\]$/; - if (abi.type.match(trailingArrayRegex)) { - const arrayItemType = abi.type.replace(trailingArrayRegex, ''); - return value.map((val: any) => { - const arrayItemAbi = { - ...abi, - type: arrayItemType, - }; - return formatABIDataItem(arrayItemAbi, val, formatter); - }); - } else if (abi.type === 'tuple') { - const formattedTuple: { [componentName: string]: DataItem } = {}; - if (abi.components) { - abi.components.forEach(componentABI => { - formattedTuple[componentABI.name] = formatABIDataItem( - componentABI, - value[componentABI.name], - formatter, - ); - }); - } - return formattedTuple; - } else { - return formatter(abi.type, value); - } -} - -/** - * Takes a MethodAbi and returns a function signature for ABI encoding/decoding - * @return a function signature as a string, e.g. 'functionName(uint256, bytes[])' - */ -export function methodAbiToFunctionSignature(methodAbi: MethodAbi): string { - const method = AbiEncoder.createMethod(methodAbi.name, methodAbi.inputs); - return method.getSignature(); -} - -/** - * Replaces unliked library references in the bytecode of a contract artifact - * with real addresses and returns the bytecode. - */ -export function linkLibrariesInBytecode( - artifact: ContractArtifact, - libraryAddresses: { [libraryName: string]: string }, -): string { - const bytecodeArtifact = artifact.compilerOutput.evm.bytecode; - let bytecode = bytecodeArtifact.object.substr(2); - for (const link of Object.values(bytecodeArtifact.linkReferences)) { - for (const [libraryName, libraryRefs] of Object.entries(link)) { - const libraryAddress = libraryAddresses[libraryName]; - if (!libraryAddress) { - throw new Error( - `${ - artifact.contractName - } has an unlinked reference library ${libraryName} but no addresses was provided'.`, - ); - } - for (const ref of libraryRefs) { - bytecode = [ - bytecode.substring(0, ref.start * 2), - libraryAddress.toLowerCase().substr(2), - bytecode.substring((ref.start + ref.length) * 2), - ].join(''); - } - } - } - return `0x${bytecode}`; -} diff --git a/packages/base-contract/src/utils/filter_utils.ts b/packages/base-contract/src/utils/filter_utils.ts deleted file mode 100644 index e914c94066..0000000000 --- a/packages/base-contract/src/utils/filter_utils.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { IndexedFilterValues } from '@0x/types'; -import { BigNumber } from '@0x/utils'; -import { BlockRange, ContractAbi, EventAbi, FilterObject, LogEntry } from 'ethereum-types'; -import * as ethUtil from 'ethereumjs-util'; -import * as jsSHA3 from 'js-sha3'; -import * as uuid from 'uuid/v4'; - -const TOPIC_LENGTH = 32; - -export const filterUtils = { - generateUUID(): string { - return uuid(); - }, - getFilter( - address: string, - eventName: ContractEvents, - indexFilterValues: IndexedFilterValues, - abi: ContractAbi, - blockRange?: BlockRange, - ): FilterObject { - // tslint:disable:next-line no-unnecessary-type-assertion - const eventAbi = abi.find(abiDefinition => (abiDefinition as EventAbi).name === eventName) as EventAbi; - const eventSignature = filterUtils.getEventSignatureFromAbiByName(eventAbi); - const topicForEventSignature = ethUtil.addHexPrefix(jsSHA3.keccak256(eventSignature)); - const topicsForIndexedArgs = filterUtils.getTopicsForIndexedArgs(eventAbi, indexFilterValues); - const topics = [topicForEventSignature, ...topicsForIndexedArgs]; - let filter: FilterObject = { - address, - topics, - }; - if (blockRange !== undefined) { - filter = { - ...blockRange, - ...filter, - }; - } - return filter; - }, - getEventSignatureFromAbiByName(eventAbi: EventAbi): string { - const types = eventAbi.inputs.map(i => i.type); - const signature = `${eventAbi.name}(${types.join(',')})`; - return signature; - }, - getTopicsForIndexedArgs(abi: EventAbi, indexFilterValues: IndexedFilterValues): Array { - const topics: Array = []; - for (const eventInput of abi.inputs) { - if (!eventInput.indexed) { - continue; - } - if (indexFilterValues[eventInput.name] === undefined) { - // Null is a wildcard topic in a JSON-RPC call - topics.push(null); - } else { - // tslint:disable: no-unnecessary-type-assertion - let value = indexFilterValues[eventInput.name] as any; - if (BigNumber.isBigNumber(value)) { - // tslint:disable-next-line custom-no-magic-numbers - value = ethUtil.fromSigned(value.toString(10) as any); - } - // tslint:enable: no-unnecessary-type-assertion - const buffer = ethUtil.toBuffer(value); - const paddedBuffer = ethUtil.setLengthLeft(buffer, TOPIC_LENGTH); - const topic = ethUtil.bufferToHex(paddedBuffer); - topics.push(topic); - } - } - return topics; - }, - matchesFilter(log: LogEntry, filter: FilterObject): boolean { - if (filter.address !== undefined && log.address !== filter.address) { - return false; - } - if (filter.topics !== undefined) { - return filterUtils.doesMatchTopics(log.topics, filter.topics); - } - return true; - }, - doesMatchTopics(logTopics: string[], filterTopics: Array): boolean { - const matchesTopic = logTopics.map((logTopic, i) => filterUtils.matchesTopic(logTopic, filterTopics[i])); - const doesMatchTopics = matchesTopic.every(m => m); - return doesMatchTopics; - }, - matchesTopic(logTopic: string, filterTopic: string[] | string | null): boolean { - if (Array.isArray(filterTopic)) { - return filterTopic.includes(logTopic); - } - if (typeof filterTopic === 'string') { - return filterTopic === logTopic; - } - // null topic is a wildcard - return true; - }, -}; diff --git a/packages/base-contract/test/base_contract_test.ts b/packages/base-contract/test/base_contract_test.ts deleted file mode 100644 index 2c31d1f119..0000000000 --- a/packages/base-contract/test/base_contract_test.ts +++ /dev/null @@ -1,114 +0,0 @@ -import * as chai from 'chai'; -import 'mocha'; - -import { BaseContract } from '../src'; - -const { expect } = chai; - -describe('BaseContract', () => { - describe('strictArgumentEncodingCheck', () => { - it('works for simple types', () => { - BaseContract.strictArgumentEncodingCheck( - [{ name: 'to', type: 'address' }], - ['0xe834ec434daba538cd1b9fe1582052b880bd7e63'], - ); - }); - it('works for array types', () => { - const inputAbi = [ - { - name: 'takerAssetFillAmounts', - type: 'uint256[]', - }, - ]; - const args = [ - ['9000000000000000000', '79000000000000000000', '979000000000000000000', '7979000000000000000000'], - ]; - BaseContract.strictArgumentEncodingCheck(inputAbi, args); - }); - it('works for tuple/struct types', () => { - const inputAbi = [ - { - components: [ - { - name: 'makerAddress', - type: 'address', - }, - { - name: 'takerAddress', - type: 'address', - }, - { - name: 'feeRecipientAddress', - type: 'address', - }, - { - name: 'senderAddress', - type: 'address', - }, - { - name: 'makerAssetAmount', - type: 'uint256', - }, - { - name: 'takerAssetAmount', - type: 'uint256', - }, - { - name: 'makerFee', - type: 'uint256', - }, - { - name: 'takerFee', - type: 'uint256', - }, - { - name: 'expirationTimeSeconds', - type: 'uint256', - }, - { - name: 'salt', - type: 'uint256', - }, - { - name: 'makerAssetData', - type: 'bytes', - }, - { - name: 'takerAssetData', - type: 'bytes', - }, - ], - name: 'order', - type: 'tuple', - }, - ]; - const args = [ - { - makerAddress: '0x6ecbe1db9ef729cbe972c83fb886247691fb6beb', - takerAddress: '0x0000000000000000000000000000000000000000', - feeRecipientAddress: '0xe834ec434daba538cd1b9fe1582052b880bd7e63', - senderAddress: '0x0000000000000000000000000000000000000000', - makerAssetAmount: '0', - takerAssetAmount: '200000000000000000000', - makerFee: '1000000000000000000', - takerFee: '1000000000000000000', - expirationTimeSeconds: '1532563026', - salt: '59342956082154660870994022243365949771115859664887449740907298019908621891376', - makerAssetData: '0xf47261b00000000000000000000000001dc4c1cefef38a777b15aa20260a54e584b16c48', - takerAssetData: '0xf47261b00000000000000000000000001d7022f5b17d2f8b695918fb48fa1089c9f85401', - }, - ]; - BaseContract.strictArgumentEncodingCheck(inputAbi, args); - }); - it('throws for integer overflows', () => { - expect(() => - BaseContract.strictArgumentEncodingCheck([{ name: 'amount', type: 'uint8' }], ['256']), - ).to.throw(); - }); - it('throws for fixed byte array overflows', () => { - expect(() => - BaseContract.strictArgumentEncodingCheck([{ name: 'hash', type: 'bytes8' }], ['0x001122334455667788']), - ).to.throw(); - }); - }); -}); diff --git a/packages/base-contract/test/utils_test.ts b/packages/base-contract/test/utils_test.ts deleted file mode 100644 index 0608b72a25..0000000000 --- a/packages/base-contract/test/utils_test.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { BigNumber } from '@0x/utils'; -import * as chai from 'chai'; -import 'mocha'; - -import { formatABIDataItem } from '../src/utils'; - -const { expect } = chai; - -describe('Utils tests', () => { - describe('#formatABIDataItem', () => { - it('correctly handles arrays', () => { - const calls: Array<{ type: string; value: any }> = []; - const abi = { - name: 'values', - type: 'uint256[]', - }; - const val = [1, 2, 3]; - const formatted = formatABIDataItem(abi, val, (type: string, value: any) => { - calls.push({ type, value }); - return value; // no-op - }); - expect(formatted).to.be.deep.equal(val); - expect(calls).to.be.deep.equal([ - { type: 'uint256', value: 1 }, - { type: 'uint256', value: 2 }, - { type: 'uint256', value: 3 }, - ]); - }); - it('correctly handles tuples', () => { - const calls: Array<{ type: string; value: any }> = []; - const abi = { - components: [ - { - name: 'to', - type: 'address', - }, - { - name: 'amount', - type: 'uint256', - }, - ], - name: 'data', - type: 'tuple', - }; - const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'; - const val = { to: ZERO_ADDRESS, amount: new BigNumber(1) }; - const formatted = formatABIDataItem(abi, val, (type: string, value: any) => { - calls.push({ type, value }); - return value; // no-op - }); - expect(formatted).to.be.deep.equal(val); - expect(calls).to.be.deep.equal([ - { - type: 'address', - value: val.to, - }, - { - type: 'uint256', - value: val.amount, - }, - ]); - }); - it('correctly handles nested arrays of tuples', () => { - const calls: Array<{ type: string; value: any }> = []; - const abi = { - components: [ - { - name: 'to', - type: 'address', - }, - { - name: 'amount', - type: 'uint256', - }, - ], - name: 'data', - type: 'tuple[2][]', - }; - const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'; - const val = [ - [{ to: ZERO_ADDRESS, amount: new BigNumber(1) }, { to: ZERO_ADDRESS, amount: new BigNumber(2) }], - ]; - const formatted = formatABIDataItem(abi, val, (type: string, value: any) => { - calls.push({ type, value }); - return value; // no-op - }); - expect(formatted).to.be.deep.equal(val); - expect(calls).to.be.deep.equal([ - { - type: 'address', - value: val[0][0].to, - }, - { - type: 'uint256', - value: val[0][0].amount, - }, - { - type: 'address', - value: val[0][1].to, - }, - { - type: 'uint256', - value: val[0][1].amount, - }, - ]); - }); - }); -}); diff --git a/packages/base-contract/tsconfig.json b/packages/base-contract/tsconfig.json deleted file mode 100644 index bf70fcb4cd..0000000000 --- a/packages/base-contract/tsconfig.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "extends": "../../tsconfig", - "compilerOptions": { - "outDir": "lib", - "rootDir": "." - }, - "typeRoots": ["node_modules/@0x/typescript-typings/types", "node_modules/@types"], - "include": ["src/**/*", "test/**/*"] -} diff --git a/packages/base-contract/tslint.json b/packages/base-contract/tslint.json deleted file mode 100644 index dd9053357e..0000000000 --- a/packages/base-contract/tslint.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": ["@0x/tslint-config"] -} diff --git a/packages/connect/.npmignore b/packages/connect/.npmignore deleted file mode 100644 index ea588d4859..0000000000 --- a/packages/connect/.npmignore +++ /dev/null @@ -1,9 +0,0 @@ -# Blacklist all files -.* -* -# Whitelist lib -!lib/**/* -# Blacklist tests and publish scripts -/lib/test/* -/lib/monorepo_scripts/ -# Package specific ignore diff --git a/packages/connect/CHANGELOG.json b/packages/connect/CHANGELOG.json deleted file mode 100644 index d7bf5b0dc1..0000000000 --- a/packages/connect/CHANGELOG.json +++ /dev/null @@ -1,818 +0,0 @@ -[ - { - "timestamp": 1594788383, - "version": "6.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1592969527, - "version": "6.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1582623685, - "version": "6.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1581204851, - "version": "6.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1580988106, - "version": "6.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1579682890, - "version": "6.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1578272714, - "version": "6.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1576540892, - "version": "6.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1575931811, - "version": "6.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "6.0.0", - "changes": [ - { - "note": "Removed dependency on @0x/order-utils", - "pr": 2321 - }, - { - "note": "All references to network ID have been removed, and references to chain ID have been introduced instead", - "pr": 2313 - } - ], - "timestamp": 1575296764 - }, - { - "version": "5.1.0-beta.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1575290197 - }, - { - "version": "5.1.0-beta.2", - "changes": [ - { - "note": "Removed dependency on @0x/order-utils", - "pr": 2321 - } - ], - "timestamp": 1574030254 - }, - { - "version": "5.1.0-beta.1", - "changes": [ - { - "note": "All references to network ID have been removed, and references to chain ID have been introduced instead", - "pr": 2313 - } - ], - "timestamp": 1573159180 - }, - { - "version": "5.1.0-beta.0", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1570135330 - }, - { - "timestamp": 1568744790, - "version": "5.0.19", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1567521715, - "version": "5.0.18", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1566446343, - "version": "5.0.17", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1565296576, - "version": "5.0.16", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1564604963, - "version": "5.0.15", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563957393, - "version": "5.0.14", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563193019, - "version": "5.0.13", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563047529, - "version": "5.0.12", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563006338, - "version": "5.0.11", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1558712885, - "version": "5.0.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1557961111, - "version": "5.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "5.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1557799313 - }, - { - "timestamp": 1557507213, - "version": "5.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "5.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1554997931 - }, - { - "timestamp": 1553183790, - "version": "5.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "5.0.3", - "changes": [ - { - "note": "Update websocket@^1.0.25 -> websocket@^1.0.26", - "pr": 1685 - } - ], - "timestamp": 1553091633 - }, - { - "timestamp": 1551479279, - "version": "5.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551220833, - "version": "5.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "5.0.0", - "changes": [ - { - "note": "Add support for EIP1193 providers & Web3.js providers >= 1.0-beta.38", - "pr": 1627 - }, - { - "note": "Update provider params to type SupportedProvider which outlines all supported providers", - "pr": 1627 - } - ], - "timestamp": 1551130135 - }, - { - "timestamp": 1549733923, - "version": "4.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "4.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1549547375 - }, - { - "timestamp": 1549504360, - "version": "4.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1549452781, - "version": "4.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "4.0.0", - "changes": [ - { - "note": "Upgrade the bignumber.js to v8.0.2", - "pr": 1517 - } - ], - "timestamp": 1549373905 - }, - { - "timestamp": 1547561734, - "version": "3.0.13", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547225310, - "version": "3.0.12", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547040760, - "version": "3.0.11", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.0.10", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544739608 - }, - { - "version": "3.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544570656 - }, - { - "timestamp": 1543401373, - "version": "3.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542821676, - "version": "3.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542208198, - "version": "3.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542134075, - "version": "3.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542028948, - "version": "3.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1541740904 - }, - { - "timestamp": 1539871071, - "version": "3.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1538693146 - }, - { - "version": "3.0.0", - "changes": [ - { - "note": "Change /order_config request to a POST instead of GET", - "pr": 1091 - } - ], - "timestamp": 1538157789 - }, - { - "timestamp": 1537907159, - "version": "2.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.3", - "changes": [ - { - "note": "Import SRA-related types from @0xproject/types", - "pr": 1085 - } - ], - "timestamp": 1537875740 - }, - { - "timestamp": 1537541580, - "version": "2.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537369748, - "version": "2.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.0", - "changes": [ - { - "note": "Change `OrderConfigRequest` to use BigNumber instead of string for relevant fields.", - "pr": 1058 - } - ], - "timestamp": 1536142250 - }, - { - "version": "2.0.0-rc.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1535377027 - }, - { - "version": "2.0.0-rc.1", - "changes": [ - { - "note": "Updated for SRA v2", - "pr": 974 - }, - { - "note": "Stopped exporting `Order` type", - "pr": 924 - } - ], - "timestamp": 1535133899 - }, - { - "timestamp": 1534210131, - "version": "1.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532619515, - "version": "1.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532614997, - "version": "1.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532605697, - "version": "1.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532357734, - "version": "1.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532043000, - "version": "1.0.0", - "changes": [ - { - "note": "Remove `WebSocketOrderbookChannel` from the public interface and replace with `orderbookChannelFactory`" - } - ] - }, - { - "timestamp": 1531919263, - "version": "0.6.17", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1531149657, - "version": "0.6.16", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1529397769, - "version": "0.6.15", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1527616612, - "version": "0.6.14", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1527008270, - "version": "0.6.13", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1525477860, - "version": "0.6.12", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1525428773, - "version": "0.6.11", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1524044013, - "version": "0.6.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1523462196, - "version": "0.6.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1522673609, - "version": "0.6.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1522658513, - "version": "0.6.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.6.4", - "changes": [ - { - "note": "Consolidate `Order`, `SignedOrder`, and `ECSignature` into the `@0xproject/types` package", - "pr": 456 - } - ], - "timestamp": 1521298800 - }, - { - "version": "0.6.2", - "changes": [ - { - "note": "Fix JSON parse empty response", - "pr": 407 - } - ], - "timestamp": 1518706800 - }, - { - "version": "0.6.0", - "changes": [ - { - "note": "Add pagination options to HttpClient methods", - "pr": 393 - }, - { - "note": "Add heartbeat configuration to WebSocketOrderbookChannel constructor", - "pr": 406 - } - ], - "timestamp": 1518706800 - }, - { - "version": "0.5.7", - "changes": [ - { - "note": "Fix publishing issue where .npmignore was not properly excluding undesired content", - "pr": 389 - } - ], - "timestamp": 1518102000 - }, - { - "version": "0.5.0", - "changes": [ - { - "note": "Sanitize api endpoint url and remove trailing slashes", - "pr": 318 - }, - { - "note": "Improve error message text in HttpClient", - "pr": 318 - }, - { - "note": "Stop appending '/v0' to api endpoint url in HttpClient", - "pr": 318 - } - ], - "timestamp": 1516114800 - }, - { - "version": "0.4.0", - "changes": [ - { - "note": "Prevent getFeesAsync method on HttpClient from mutating input", - "pr": 296 - } - ], - "timestamp": 1515596400 - }, - { - "version": "0.3.0", - "changes": [ - { - "note": "Expose WebSocketOrderbookChannel and associated types to public interface", - "pr": 251 - }, - { - "note": "Remove tokenA and tokenB fields from OrdersRequest", - "pr": 256 - } - ], - "timestamp": 1512658800 - }, - { - "version": "0.2.0", - "changes": [ - { - "note": "Add SignedOrder and TokenTradeInfo to the public interface" - }, - { - "note": "Add ECSignature and Order to the public interface" - }, - { - "note": "Remove dependency on 0x.js" - } - ], - "timestamp": 1511881200 - }, - { - "version": "0.1.0", - "changes": [ - { - "note": "Provide a HttpClient class for interacting with standard relayer api compliant HTTP urls" - } - ], - "timestamp": 1511276400 - } -] diff --git a/packages/connect/CHANGELOG.md b/packages/connect/CHANGELOG.md deleted file mode 100644 index 0135227301..0000000000 --- a/packages/connect/CHANGELOG.md +++ /dev/null @@ -1,355 +0,0 @@ - - -CHANGELOG - -## v6.0.9 - _July 15, 2020_ - - * Dependencies updated - -## v6.0.8 - _June 24, 2020_ - - * Dependencies updated - -## v6.0.7 - _February 25, 2020_ - - * Dependencies updated - -## v6.0.6 - _February 8, 2020_ - - * Dependencies updated - -## v6.0.5 - _February 6, 2020_ - - * Dependencies updated - -## v6.0.4 - _January 22, 2020_ - - * Dependencies updated - -## v6.0.3 - _January 6, 2020_ - - * Dependencies updated - -## v6.0.2 - _December 17, 2019_ - - * Dependencies updated - -## v6.0.1 - _December 9, 2019_ - - * Dependencies updated - -## v6.0.0 - _December 2, 2019_ - - * Removed dependency on @0x/order-utils (#2321) - * All references to network ID have been removed, and references to chain ID have been introduced instead (#2313) - -## v5.1.0-beta.3 - _December 2, 2019_ - - * Dependencies updated - -## v5.1.0-beta.2 - _November 17, 2019_ - - * Removed dependency on @0x/order-utils (#2321) - -## v5.1.0-beta.1 - _November 7, 2019_ - - * All references to network ID have been removed, and references to chain ID have been introduced instead (#2313) - -## v5.1.0-beta.0 - _October 3, 2019_ - - * Dependencies updated - -## v5.0.19 - _September 17, 2019_ - - * Dependencies updated - -## v5.0.18 - _September 3, 2019_ - - * Dependencies updated - -## v5.0.17 - _August 22, 2019_ - - * Dependencies updated - -## v5.0.16 - _August 8, 2019_ - - * Dependencies updated - -## v5.0.15 - _July 31, 2019_ - - * Dependencies updated - -## v5.0.14 - _July 24, 2019_ - - * Dependencies updated - -## v5.0.13 - _July 15, 2019_ - - * Dependencies updated - -## v5.0.12 - _July 13, 2019_ - - * Dependencies updated - -## v5.0.11 - _July 13, 2019_ - - * Dependencies updated - -## v5.0.10 - _May 24, 2019_ - - * Dependencies updated - -## v5.0.9 - _May 15, 2019_ - - * Dependencies updated - -## v5.0.8 - _May 14, 2019_ - - * Dependencies updated - -## v5.0.6 - _May 10, 2019_ - - * Dependencies updated - -## v5.0.5 - _April 11, 2019_ - - * Dependencies updated - -## v5.0.4 - _March 21, 2019_ - - * Dependencies updated - -## v5.0.3 - _March 20, 2019_ - - * Update websocket@^1.0.25 -> websocket@^1.0.26 (#1685) - -## v5.0.2 - _March 1, 2019_ - - * Dependencies updated - -## v5.0.1 - _February 26, 2019_ - - * Dependencies updated - -## v5.0.0 - _February 25, 2019_ - - * Add support for EIP1193 providers & Web3.js providers >= 1.0-beta.38 (#1627) - * Update provider params to type SupportedProvider which outlines all supported providers (#1627) - -## v4.0.4 - _February 9, 2019_ - - * Dependencies updated - -## v4.0.3 - _February 7, 2019_ - - * Dependencies updated - -## v4.0.2 - _February 7, 2019_ - - * Dependencies updated - -## v4.0.1 - _February 6, 2019_ - - * Dependencies updated - -## v4.0.0 - _February 5, 2019_ - - * Upgrade the bignumber.js to v8.0.2 (#1517) - -## v3.0.13 - _January 15, 2019_ - - * Dependencies updated - -## v3.0.12 - _January 11, 2019_ - - * Dependencies updated - -## v3.0.11 - _January 9, 2019_ - - * Dependencies updated - -## v3.0.10 - _December 13, 2018_ - - * Dependencies updated - -## v3.0.9 - _December 11, 2018_ - - * Dependencies updated - -## v3.0.8 - _November 28, 2018_ - - * Dependencies updated - -## v3.0.7 - _November 21, 2018_ - - * Dependencies updated - -## v3.0.6 - _November 14, 2018_ - - * Dependencies updated - -## v3.0.5 - _November 13, 2018_ - - * Dependencies updated - -## v3.0.4 - _November 12, 2018_ - - * Dependencies updated - -## v3.0.3 - _November 9, 2018_ - - * Dependencies updated - -## v3.0.2 - _October 18, 2018_ - - * Dependencies updated - -## v3.0.1 - _October 4, 2018_ - - * Dependencies updated - -## v3.0.0 - _September 28, 2018_ - - * Change /order_config request to a POST instead of GET (#1091) - -## v2.0.4 - _September 25, 2018_ - - * Dependencies updated - -## v2.0.3 - _September 25, 2018_ - - * Import SRA-related types from @0xproject/types (#1085) - -## v2.0.2 - _September 21, 2018_ - - * Dependencies updated - -## v2.0.1 - _September 19, 2018_ - - * Dependencies updated - -## v2.0.0 - _September 5, 2018_ - - * Change `OrderConfigRequest` to use BigNumber instead of string for relevant fields. (#1058) - -## v2.0.0-rc.2 - _August 27, 2018_ - - * Dependencies updated - -## v2.0.0-rc.1 - _August 24, 2018_ - - * Updated for SRA v2 (#974) - * Stopped exporting `Order` type (#924) - -## v1.0.5 - _August 14, 2018_ - - * Dependencies updated - -## v1.0.4 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.3 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.2 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.1 - _July 23, 2018_ - - * Dependencies updated - -## v1.0.0 - _July 19, 2018_ - - * Remove `WebSocketOrderbookChannel` from the public interface and replace with `orderbookChannelFactory` - -## v0.6.17 - _July 18, 2018_ - - * Dependencies updated - -## v0.6.16 - _July 9, 2018_ - - * Dependencies updated - -## v0.6.15 - _June 19, 2018_ - - * Dependencies updated - -## v0.6.14 - _May 29, 2018_ - - * Dependencies updated - -## v0.6.13 - _May 22, 2018_ - - * Dependencies updated - -## v0.6.12 - _May 4, 2018_ - - * Dependencies updated - -## v0.6.11 - _May 4, 2018_ - - * Dependencies updated - -## v0.6.10 - _April 18, 2018_ - - * Dependencies updated - -## v0.6.9 - _April 11, 2018_ - - * Dependencies updated - -## v0.6.8 - _April 2, 2018_ - - * Dependencies updated - -## v0.6.7 - _April 2, 2018_ - - * Dependencies updated - -## v0.6.4 - _March 17, 2018_ - - * Consolidate `Order`, `SignedOrder`, and `ECSignature` into the `@0xproject/types` package (#456) - -## v0.6.2 - _February 15, 2018_ - - * Fix JSON parse empty response (#407) - -## v0.6.0 - _February 15, 2018_ - - * Add pagination options to HttpClient methods (#393) - * Add heartbeat configuration to WebSocketOrderbookChannel constructor (#406) - -## v0.5.7 - _February 8, 2018_ - - * Fix publishing issue where .npmignore was not properly excluding undesired content (#389) - -## v0.5.0 - _January 16, 2018_ - - * Sanitize api endpoint url and remove trailing slashes (#318) - * Improve error message text in HttpClient (#318) - * Stop appending '/v0' to api endpoint url in HttpClient (#318) - -## v0.4.0 - _January 10, 2018_ - - * Prevent getFeesAsync method on HttpClient from mutating input (#296) - -## v0.3.0 - _December 7, 2017_ - - * Expose WebSocketOrderbookChannel and associated types to public interface (#251) - * Remove tokenA and tokenB fields from OrdersRequest (#256) - -## v0.2.0 - _November 28, 2017_ - - * Add SignedOrder and TokenTradeInfo to the public interface - * Add ECSignature and Order to the public interface - * Remove dependency on 0x.js - -## v0.1.0 - _November 21, 2017_ - - * Provide a HttpClient class for interacting with standard relayer api compliant HTTP urls diff --git a/packages/connect/README.md b/packages/connect/README.md deleted file mode 100644 index 08afa78944..0000000000 --- a/packages/connect/README.md +++ /dev/null @@ -1,74 +0,0 @@ -## @0x/connect - -This repository contains a Javascript library that makes it easy to interact with Relayers that conform to the [Standard Relayer API](https://github.com/0xProject/standard-relayer-api) - -## Installation - -```bash -yarn add @0x/connect -``` - -If your project is in [TypeScript](https://www.typescriptlang.org/), add the following to your `tsconfig.json`: - -```json -"compilerOptions": { - "typeRoots": ["node_modules/@0x/typescript-typings/types", "node_modules/@types"], -} -``` - -## Usage - -- [Docs](https://0x.org/docs/tools/connect) -- [Tutorials](https://0x.org/docs/guides/using-the-standard-relayer-api) - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install dependencies - -If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: - -```bash -yarn config set workspaces-experimental true -``` - -Then install dependencies - -```bash -yarn install -``` - -### Build - -To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory: - -```bash -PKG=@0x/connect yarn build -``` - -Or continuously rebuild on change: - -```bash -PKG=@0x/connect yarn watch -``` - -### Clean - -```bash -yarn clean -``` - -### Lint - -```bash -yarn lint -``` - -### Run Tests - -```bash -yarn test -``` diff --git a/packages/connect/coverage/.gitkeep b/packages/connect/coverage/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/connect/docs/reference.mdx b/packages/connect/docs/reference.mdx deleted file mode 100644 index 13a1d2c188..0000000000 --- a/packages/connect/docs/reference.mdx +++ /dev/null @@ -1,684 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -## Type aliases - - - - - -### AssetPairsResponse - -Ƭ **AssetPairsResponse**: *[PaginatedCollection](#interface-paginatedcollection)‹*[AssetPairsItem](#interface-assetpairsitem)*›* - -*Defined in [types/src/index.ts:416](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L416)* - -___ - - - - - - - -### FeeRecipientsResponse - -Ƭ **FeeRecipientsResponse**: *[PaginatedCollection](#interface-paginatedcollection)‹*string*›* - -*Defined in [types/src/index.ts:484](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L484)* - -___ - - - - - -### OrdersResponse - -Ƭ **OrdersResponse**: *[PaginatedCollection](#interface-paginatedcollection)‹*[APIOrder](#interface-apiorder)*›* - -*Defined in [types/src/index.ts:404](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L404)* - -___ - - - - - - - - - -# Interface: APIOrder - - -## Properties - -### metaData - -• **metaData**: *object* - -*Defined in [types/src/index.ts:408](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L408)* - -___ - -### order - -• **order**: *[SignedOrder](#class-signedorder)* - -*Defined in [types/src/index.ts:407](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L407)* - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# Class: HttpClient - -This class includes all the functionality related to interacting with a set of HTTP endpoints -that implement the standard relayer API v2 - - -## Constructors - - - -\+ **new HttpClient**(`url`: string): *[HttpClient](#class-httpclient)* - -*Defined in [connect/src/http_client.ts:43](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/connect/src/http_client.ts#L43)* - -Instantiates a new HttpClient instance - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`url` | string | The relayer API base HTTP url you would like to interact with | - -**Returns:** *[HttpClient](#class-httpclient)* - -An instance of HttpClient - -## Methods - -### getAssetPairsAsync - -▸ **getAssetPairsAsync**(`requestOpts?`: `AssetPairsRequestOpts` & `PagedRequestOpts`): *`Promise`* - -*Defined in [connect/src/http_client.ts:58](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/connect/src/http_client.ts#L58)* - -Retrieve assetData pair info from the API - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`requestOpts?` | `AssetPairsRequestOpts` & `PagedRequestOpts` | Options specifying assetData information to retrieve, page information. | - -**Returns:** *`Promise`* - -The resulting AssetPairsResponse that match the request - -___ - -### getFeeRecipientsAsync - -▸ **getFeeRecipientsAsync**(`requestOpts?`: [PagedRequestOpts](#interface-pagedrequestopts)): *`Promise`* - -*Defined in [connect/src/http_client.ts:140](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/connect/src/http_client.ts#L140)* - -Retrieve the list of fee recipient addresses used by the relayer. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`requestOpts?` | [PagedRequestOpts](#interface-pagedrequestopts) | Options specifying page information. | - -**Returns:** *`Promise`* - -The resulting FeeRecipientsResponse - -___ - -### getOrderAsync - -▸ **getOrderAsync**(`orderHash`: string): *`Promise`* - -*Defined in [connect/src/http_client.ts:94](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/connect/src/http_client.ts#L94)* - -Retrieve a specific order from the API - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`orderHash` | string | An orderHash generated from the desired order | - -**Returns:** *`Promise`* - -The APIOrder that matches the supplied orderHash - -___ - -### getOrderConfigAsync - -▸ **getOrderConfigAsync**(`request`: `OrderConfigRequest`): *`Promise`* - -*Defined in [connect/src/http_client.ts:126](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/connect/src/http_client.ts#L126)* - -Retrieve fee information from the API - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`request` | `OrderConfigRequest` | A OrderConfigRequest instance describing the specific fees to retrieve | - -**Returns:** *`Promise`* - -The resulting OrderConfigResponse that matches the request - -___ - -### getOrderbookAsync - -▸ **getOrderbookAsync**(`request`: `OrderbookRequest`, `requestOpts?`: [PagedRequestOpts](#interface-pagedrequestopts)): *`Promise`* - -*Defined in [connect/src/http_client.ts:106](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/connect/src/http_client.ts#L106)* - -Retrieve an orderbook from the API - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`request` | `OrderbookRequest` | An OrderbookRequest instance describing the specific orderbook to retrieve | -`requestOpts?` | [PagedRequestOpts](#interface-pagedrequestopts) | Options specifying page information. | - -**Returns:** *`Promise`* - -The resulting OrderbookResponse that matches the request - -___ - -### getOrdersAsync - -▸ **getOrdersAsync**(`requestOpts?`: `OrdersRequestOpts` & `PagedRequestOpts`): *`Promise`* - -*Defined in [connect/src/http_client.ts:77](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/connect/src/http_client.ts#L77)* - -Retrieve orders from the API - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`requestOpts?` | `OrdersRequestOpts` & `PagedRequestOpts` | Options specifying orders to retrieve and page information, page information. | - -**Returns:** *`Promise`* - -The resulting OrdersResponse that match the request - -___ - -### submitOrderAsync - -▸ **submitOrderAsync**(`signedOrder`: `SignedOrder`): *`Promise`* - -*Defined in [connect/src/http_client.ts:155](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/connect/src/http_client.ts#L155)* - -Submit a signed order to the API - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`signedOrder` | `SignedOrder` | A SignedOrder instance to submit | - -**Returns:** *`Promise`* - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# Interface: PagedRequestOpts - - -## Properties - -### `Optional` page - -• **page**? : *undefined | number* - -*Defined in [types/src/index.ts:491](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L491)* - -___ - -### `Optional` perPage - -• **perPage**? : *undefined | number* - -*Defined in [types/src/index.ts:492](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L492)* - -
- -# Interface: PaginatedCollection <**T**> - -## Type parameters - -▪ **T** - - -## Properties - -### page - -• **page**: *number* - -*Defined in [types/src/index.ts:459](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L459)* - -___ - -### perPage - -• **perPage**: *number* - -*Defined in [types/src/index.ts:460](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L460)* - -___ - -### records - -• **records**: *`T`[]* - -*Defined in [types/src/index.ts:461](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L461)* - -___ - -### total - -• **total**: *number* - -*Defined in [types/src/index.ts:458](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L458)* - -
- - - - - - - - - -# Interface: SignedOrder - - -## Properties - -### chainId - -• **chainId**: *number* - -*Inherited from [Order](#interface-order).[chainId](#chainid)* - -*Defined in [types/src/index.ts:14](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L14)* - -___ - -### exchangeAddress - -• **exchangeAddress**: *string* - -*Inherited from [Order](#interface-order).[exchangeAddress](#exchangeaddress)* - -*Defined in [types/src/index.ts:15](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L15)* - -___ - -### expirationTimeSeconds - -• **expirationTimeSeconds**: *`BigNumber`* - -*Inherited from [Order](#interface-order).[expirationTimeSeconds](#expirationtimeseconds)* - -*Defined in [types/src/index.ts:24](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L24)* - -___ - -### feeRecipientAddress - -• **feeRecipientAddress**: *string* - -*Inherited from [Order](#interface-order).[feeRecipientAddress](#feerecipientaddress)* - -*Defined in [types/src/index.ts:18](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L18)* - -___ - -### makerAddress - -• **makerAddress**: *string* - -*Inherited from [Order](#interface-order).[makerAddress](#makeraddress)* - -*Defined in [types/src/index.ts:16](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L16)* - -___ - -### makerAssetAmount - -• **makerAssetAmount**: *`BigNumber`* - -*Inherited from [Order](#interface-order).[makerAssetAmount](#makerassetamount)* - -*Defined in [types/src/index.ts:20](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L20)* - -___ - -### makerAssetData - -• **makerAssetData**: *string* - -*Inherited from [Order](#interface-order).[makerAssetData](#makerassetdata)* - -*Defined in [types/src/index.ts:26](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L26)* - -___ - -### makerFee - -• **makerFee**: *`BigNumber`* - -*Inherited from [Order](#interface-order).[makerFee](#makerfee)* - -*Defined in [types/src/index.ts:22](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L22)* - -___ - -### makerFeeAssetData - -• **makerFeeAssetData**: *string* - -*Inherited from [Order](#interface-order).[makerFeeAssetData](#makerfeeassetdata)* - -*Defined in [types/src/index.ts:28](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L28)* - -___ - -### salt - -• **salt**: *`BigNumber`* - -*Inherited from [Order](#interface-order).[salt](#salt)* - -*Defined in [types/src/index.ts:25](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L25)* - -___ - -### senderAddress - -• **senderAddress**: *string* - -*Inherited from [Order](#interface-order).[senderAddress](#senderaddress)* - -*Defined in [types/src/index.ts:19](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L19)* - -___ - -### signature - -• **signature**: *string* - -*Defined in [types/src/index.ts:33](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L33)* - -___ - -### takerAddress - -• **takerAddress**: *string* - -*Inherited from [Order](#interface-order).[takerAddress](#takeraddress)* - -*Defined in [types/src/index.ts:17](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L17)* - -___ - -### takerAssetAmount - -• **takerAssetAmount**: *`BigNumber`* - -*Inherited from [Order](#interface-order).[takerAssetAmount](#takerassetamount)* - -*Defined in [types/src/index.ts:21](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L21)* - -___ - -### takerAssetData - -• **takerAssetData**: *string* - -*Inherited from [Order](#interface-order).[takerAssetData](#takerassetdata)* - -*Defined in [types/src/index.ts:27](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L27)* - -___ - -### takerFee - -• **takerFee**: *`BigNumber`* - -*Inherited from [Order](#interface-order).[takerFee](#takerfee)* - -*Defined in [types/src/index.ts:23](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L23)* - -___ - -### takerFeeAssetData - -• **takerFeeAssetData**: *string* - -*Inherited from [Order](#interface-order).[takerFeeAssetData](#takerfeeassetdata)* - -*Defined in [types/src/index.ts:29](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L29)* - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - -
- - - - -## Object literals - -### `Const` ordersChannelFactory - -#### ▪ **ordersChannelFactory**: *object* - -*Defined in [connect/src/orders_channel_factory.ts:7](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/connect/src/orders_channel_factory.ts#L7)* - -#### createWebSocketOrdersChannelAsync - -▸ **createWebSocketOrdersChannelAsync**(`url`: string, `handler`: [OrdersChannelHandler](#interface-orderschannelhandler)): *`Promise`* - -*Defined in [connect/src/orders_channel_factory.ts:15](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/connect/src/orders_channel_factory.ts#L15)* - -Instantiates a new WebSocketOrdersChannel instance - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`url` | string | The relayer API base WS url you would like to interact with | -`handler` | [OrdersChannelHandler](#interface-orderschannelhandler) | An OrdersChannelHandler instance that responds to various channel updates | - -**Returns:** *`Promise`* - -An OrdersChannel Promise - -
- diff --git a/packages/connect/package.json b/packages/connect/package.json deleted file mode 100644 index 49571783e7..0000000000 --- a/packages/connect/package.json +++ /dev/null @@ -1,91 +0,0 @@ -{ - "name": "@0x/connect", - "version": "6.0.9", - "engines": { - "node": ">=6.12" - }, - "description": "A javascript library for interacting with the standard relayer api", - "keywords": [ - "connect", - "0xproject", - "ethereum", - "tokens", - "exchange" - ], - "main": "lib/src/index.js", - "types": "lib/src/index.d.ts", - "scripts": { - "build": "tsc -b", - "build:ci": "yarn build", - "clean": "shx rm -rf lib test_temp generated_docs", - "copy_test_fixtures": "copyfiles -u 2 './test/fixtures/**/*.json' ./lib/test/fixtures", - "lint": "tslint --format stylish --project .", - "fix": "tslint --fix --format stylish --project .", - "run_mocha": "mocha --require source-map-support/register --require make-promises-safe lib/test/**/*_test.js --exit", - "test": "run-s copy_test_fixtures 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", - "diff_docs": "git diff --exit-code ./docs", - "s3:sync_md_docs": "aws s3 sync ./docs s3://docs-markdown/${npm_package_name}/v${npm_package_version} --profile 0xproject --region us-east-1 --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers", - "docs:md": "ts-doc-gen --sourceDir='$PROJECT_FILES' --output=$MD_FILE_DIR --fileExtension=mdx --tsconfig=./typedoc-tsconfig.json", - "docs:json": "typedoc --excludePrivate --excludeExternals --excludeProtected --ignoreCompilerErrors --target ES5 --tsconfig typedoc-tsconfig.json --json $JSON_FILE_PATH $PROJECT_FILES" - }, - "config": { - "postpublish": { - "assets": [] - } - }, - "repository": { - "type": "git", - "url": "https://github.com/0xProject/0x-monorepo.git" - }, - "author": "Brandon Millman", - "license": "Apache-2.0", - "bugs": { - "url": "https://github.com/0xProject/0x-monorepo/issues" - }, - "homepage": "https://github.com/0xProject/0x-monorepo/packages/connect/README.md", - "dependencies": { - "@0x/assert": "^3.0.9", - "@0x/json-schemas": "^5.1.0", - "@0x/types": "^3.2.0", - "@0x/typescript-typings": "^5.1.1", - "@0x/utils": "^5.5.1", - "lodash": "^4.17.11", - "query-string": "^6.0.0", - "sinon": "^4.0.0", - "uuid": "^3.3.2", - "websocket": "^1.0.26" - }, - "devDependencies": { - "@0x/ts-doc-gen": "^0.0.22", - "@0x/tslint-config": "^4.1.0", - "@types/fetch-mock": "^6.0.3", - "@types/lodash": "4.14.104", - "@types/mocha": "^5.2.7", - "@types/query-string": "^5.1.0", - "@types/sinon": "^2.2.2", - "@types/uuid": "^3.4.3", - "@types/websocket": "^0.0.39", - "async-child-process": "^1.1.1", - "chai": "^4.0.1", - "chai-as-promised": "^7.1.0", - "copyfiles": "^2.0.0", - "dirty-chai": "^2.0.1", - "fetch-mock": "^5.13.1", - "make-promises-safe": "^1.1.0", - "mocha": "^6.2.0", - "npm-run-all": "^4.1.2", - "nyc": "^11.0.1", - "shx": "^0.2.2", - "tslint": "5.11.0", - "typedoc": "^0.15.0", - "typescript": "3.0.1" - }, - "publishConfig": { - "access": "public" - }, - "gitHead": "4f91bfd907996b2f4dd383778b50c479c2602b56" -} diff --git a/packages/connect/src/globals.d.ts b/packages/connect/src/globals.d.ts deleted file mode 100644 index 783b92913c..0000000000 --- a/packages/connect/src/globals.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -declare module '*.json' { - const value: any; - export default value; -} diff --git a/packages/connect/src/http_client.ts b/packages/connect/src/http_client.ts deleted file mode 100644 index c050a374bd..0000000000 --- a/packages/connect/src/http_client.ts +++ /dev/null @@ -1,187 +0,0 @@ -import { assert } from '@0x/assert'; -import { schemas } from '@0x/json-schemas'; -import { - APIOrder, - AssetPairsRequestOpts, - AssetPairsResponse, - FeeRecipientsResponse, - OrderbookRequest, - OrderbookResponse, - OrderConfigRequest, - OrderConfigResponse, - OrdersRequestOpts, - OrdersResponse, - PagedRequestOpts, - SignedOrder, -} from '@0x/types'; -import { fetchAsync } from '@0x/utils'; -import * as _ from 'lodash'; -import * as queryString from 'query-string'; - -import { HttpRequestOptions, HttpRequestType } from './types'; -import { relayerResponseJsonParsers } from './utils/relayer_response_json_parsers'; - -const TRAILING_SLASHES_REGEX = /\/+$/; - -/** - * This class includes all the functionality related to interacting with a set of HTTP endpoints - * that implement the standard relayer API v2 - */ -export class HttpClient { - private readonly _apiEndpointUrl: string; - /** - * Format parameters to be appended to http requests into query string form - */ - private static _buildQueryStringFromHttpParams(params?: object): string { - // if params are undefined or empty, return an empty string - if (params === undefined || _.isEmpty(params)) { - return ''; - } - // stringify the formatted object - const stringifiedParams = queryString.stringify(params); - return `?${stringifiedParams}`; - } - /** - * Instantiates a new HttpClient instance - * @param url The relayer API base HTTP url you would like to interact with - * @return An instance of HttpClient - */ - constructor(url: string) { - assert.isWebUri('url', url); - this._apiEndpointUrl = url.replace(TRAILING_SLASHES_REGEX, ''); // remove trailing slashes - } - /** - * Retrieve assetData pair info from the API - * @param requestOpts Options specifying assetData information to retrieve, page information. - * @return The resulting AssetPairsResponse that match the request - */ - public async getAssetPairsAsync( - requestOpts?: AssetPairsRequestOpts & PagedRequestOpts, - ): Promise { - if (requestOpts !== undefined) { - assert.doesConformToSchema('requestOpts', requestOpts, schemas.assetPairsRequestOptsSchema); - assert.doesConformToSchema('requestOpts', requestOpts, schemas.pagedRequestOptsSchema); - } - const httpRequestOpts = { - params: requestOpts, - }; - const responseJson = await this._requestAsync('/asset_pairs', HttpRequestType.Get, httpRequestOpts); - const assetDataPairs = relayerResponseJsonParsers.parseAssetDataPairsJson(responseJson); - return assetDataPairs; - } - /** - * Retrieve orders from the API - * @param requestOpts Options specifying orders to retrieve and page information, page information. - * @return The resulting OrdersResponse that match the request - */ - public async getOrdersAsync(requestOpts?: OrdersRequestOpts & PagedRequestOpts): Promise { - if (requestOpts !== undefined) { - assert.doesConformToSchema('requestOpts', requestOpts, schemas.ordersRequestOptsSchema); - assert.doesConformToSchema('requestOpts', requestOpts, schemas.pagedRequestOptsSchema); - } - const httpRequestOpts = { - params: requestOpts, - }; - const responseJson = await this._requestAsync(`/orders`, HttpRequestType.Get, httpRequestOpts); - const orders = relayerResponseJsonParsers.parseOrdersJson(responseJson); - return orders; - } - /** - * Retrieve a specific order from the API - * @param orderHash An orderHash generated from the desired order - * @return The APIOrder that matches the supplied orderHash - */ - public async getOrderAsync(orderHash: string): Promise { - assert.doesConformToSchema('orderHash', orderHash, schemas.orderHashSchema); - const responseJson = await this._requestAsync(`/order/${orderHash}`, HttpRequestType.Get); - const order = relayerResponseJsonParsers.parseAPIOrderJson(responseJson); - return order; - } - /** - * Retrieve an orderbook from the API - * @param request An OrderbookRequest instance describing the specific orderbook to retrieve - * @param requestOpts Options specifying page information. - * @return The resulting OrderbookResponse that matches the request - */ - public async getOrderbookAsync( - request: OrderbookRequest, - requestOpts?: PagedRequestOpts, - ): Promise { - assert.doesConformToSchema('request', request, schemas.orderBookRequestSchema); - if (requestOpts !== undefined) { - assert.doesConformToSchema('requestOpts', requestOpts, schemas.pagedRequestOptsSchema); - } - const httpRequestOpts = { - params: _.defaults({}, request, requestOpts), - }; - const responseJson = await this._requestAsync('/orderbook', HttpRequestType.Get, httpRequestOpts); - const orderbook = relayerResponseJsonParsers.parseOrderbookResponseJson(responseJson); - return orderbook; - } - /** - * Retrieve fee information from the API - * @param request A OrderConfigRequest instance describing the specific fees to retrieve - * @return The resulting OrderConfigResponse that matches the request - */ - public async getOrderConfigAsync(request: OrderConfigRequest): Promise { - assert.doesConformToSchema('request', request, schemas.orderConfigRequestSchema); - const httpRequestOpts = { - payload: request, - }; - const responseJson = await this._requestAsync('/order_config', HttpRequestType.Post, httpRequestOpts); - const fees = relayerResponseJsonParsers.parseOrderConfigResponseJson(responseJson); - return fees; - } - /** - * Retrieve the list of fee recipient addresses used by the relayer. - * @param requestOpts Options specifying page information. - * @return The resulting FeeRecipientsResponse - */ - public async getFeeRecipientsAsync(requestOpts?: PagedRequestOpts): Promise { - if (requestOpts !== undefined) { - assert.doesConformToSchema('requestOpts', requestOpts, schemas.pagedRequestOptsSchema); - } - const httpRequestOpts = { - params: requestOpts, - }; - const feeRecipients = await this._requestAsync('/fee_recipients', HttpRequestType.Get, httpRequestOpts); - assert.doesConformToSchema('feeRecipients', feeRecipients, schemas.relayerApiFeeRecipientsResponseSchema); - return feeRecipients; - } - /** - * Submit a signed order to the API - * @param signedOrder A SignedOrder instance to submit - */ - public async submitOrderAsync(signedOrder: SignedOrder): Promise { - assert.doesConformToSchema('signedOrder', signedOrder, schemas.signedOrderSchema); - const httpRequestOpts = { - payload: signedOrder, - }; - await this._requestAsync('/order', HttpRequestType.Post, httpRequestOpts); - } - private async _requestAsync( - path: string, - requestType: HttpRequestType, - requestOptions?: HttpRequestOptions, - ): Promise { - const params = _.get(requestOptions, 'params'); - const payload = _.get(requestOptions, 'payload'); - const query = HttpClient._buildQueryStringFromHttpParams(params); - const url = `${this._apiEndpointUrl}${path}${query}`; - const headers = new Headers({ - 'content-type': 'application/json', - }); - const response = await fetchAsync(url, { - method: requestType, - body: JSON.stringify(payload), - headers, - }); - const text = await response.text(); - if (!response.ok) { - const errorString = `${response.status} - ${response.statusText}\n${requestType} ${url}\n${text}`; - throw Error(errorString); - } - const result = !_.isEmpty(text) ? JSON.parse(text) : undefined; - return result; - } -} diff --git a/packages/connect/src/index.ts b/packages/connect/src/index.ts deleted file mode 100644 index 0849c9a633..0000000000 --- a/packages/connect/src/index.ts +++ /dev/null @@ -1,19 +0,0 @@ -export { HttpClient } from './http_client'; -export { ordersChannelFactory } from './orders_channel_factory'; -export { OrdersChannel, OrdersChannelHandler } from './types'; -export { - APIOrder, - AssetPairsRequestOpts, - AssetPairsResponse, - FeeRecipientsResponse, - OrderbookRequest, - OrderbookResponse, - OrderConfigRequest, - OrderConfigResponse, - OrdersChannelSubscriptionOpts, - OrdersRequestOpts, - OrdersResponse, - PagedRequestOpts, - PaginatedCollection, - SignedOrder, -} from '@0x/types'; diff --git a/packages/connect/src/orders_channel_factory.ts b/packages/connect/src/orders_channel_factory.ts deleted file mode 100644 index 5986d2a772..0000000000 --- a/packages/connect/src/orders_channel_factory.ts +++ /dev/null @@ -1,29 +0,0 @@ -import * as WebSocket from 'websocket'; - -import { OrdersChannel, OrdersChannelHandler } from './types'; -import { assert } from './utils/assert'; -import { WebSocketOrdersChannel } from './ws_orders_channel'; - -export const ordersChannelFactory = { - /** - * Instantiates a new WebSocketOrdersChannel instance - * @param url The relayer API base WS url you would like to interact with - * @param handler An OrdersChannelHandler instance that responds to various - * channel updates - * @return An OrdersChannel Promise - */ - async createWebSocketOrdersChannelAsync(url: string, handler: OrdersChannelHandler): Promise { - assert.isUri('url', url); - assert.isOrdersChannelHandler('handler', handler); - return new Promise((resolve, reject) => { - const client = new WebSocket.w3cwebsocket(url); - client.onopen = () => { - const ordersChannel = new WebSocketOrdersChannel(client, handler); - resolve(ordersChannel); - }; - client.onerror = err => { - reject(err); - }; - }); - }, -}; diff --git a/packages/connect/src/types.ts b/packages/connect/src/types.ts deleted file mode 100644 index 5e990de9e7..0000000000 --- a/packages/connect/src/types.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { APIOrder, OrdersChannelSubscriptionOpts } from '@0x/types'; - -export interface OrdersChannel { - subscribe: (subscriptionOpts: OrdersChannelSubscriptionOpts) => void; - close: () => void; -} - -export interface OrdersChannelHandler { - onUpdate: (channel: OrdersChannel, subscriptionOpts: OrdersChannelSubscriptionOpts, orders: APIOrder[]) => void; - onError: (channel: OrdersChannel, err: Error, subscriptionOpts?: OrdersChannelSubscriptionOpts) => void; - onClose: (channel: OrdersChannel) => void; -} - -export interface HttpRequestOptions { - params?: object; - payload?: object; -} - -export enum HttpRequestType { - Get = 'GET', - Post = 'POST', -} diff --git a/packages/connect/src/utils/assert.ts b/packages/connect/src/utils/assert.ts deleted file mode 100644 index de7536ffe5..0000000000 --- a/packages/connect/src/utils/assert.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { assert as sharedAssert } from '@0x/assert'; -// HACK: We need those two unused imports because they're actually used by sharedAssert which gets injected here -// tslint:disable-next-line:no-unused-variable -import { Schema, schemas } from '@0x/json-schemas'; -// tslint:disable-next-line:no-unused-variable -import { ECSignature } from '@0x/types'; -// tslint:disable-next-line:no-unused-variable -import { BigNumber } from '@0x/utils'; -import * as _ from 'lodash'; - -export const assert = { - ...sharedAssert, - isOrdersChannelSubscriptionOpts(variableName: string, subscriptionOpts: any): void { - sharedAssert.doesConformToSchema( - variableName, - subscriptionOpts, - schemas.relayerApiOrdersChannelSubscribePayloadSchema, - ); - }, - isOrdersChannelHandler(variableName: string, handler: any): void { - sharedAssert.isFunction(`${variableName}.onUpdate`, _.get(handler, 'onUpdate')); - sharedAssert.isFunction(`${variableName}.onError`, _.get(handler, 'onError')); - sharedAssert.isFunction(`${variableName}.onClose`, _.get(handler, 'onClose')); - }, -}; diff --git a/packages/connect/src/utils/order_parsing_utils.ts b/packages/connect/src/utils/order_parsing_utils.ts deleted file mode 100644 index 4659467404..0000000000 --- a/packages/connect/src/utils/order_parsing_utils.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { BigNumber } from '@0x/utils'; -import * as _ from 'lodash'; - -export const orderParsingUtils = { - convertStringsFieldsToBigNumbers(obj: any, fields: string[]): any { - const result = _.assign({}, obj); - _.each(fields, field => { - _.update(result, field, (value: string) => { - if (value === undefined) { - throw new Error(`Could not find field '${field}' while converting string fields to BigNumber.`); - } - return new BigNumber(value); - }); - }); - return result; - }, - convertOrderStringFieldsToBigNumber(order: any): any { - return orderParsingUtils.convertStringsFieldsToBigNumbers(order, [ - 'makerAssetAmount', - 'takerAssetAmount', - 'makerFee', - 'takerFee', - 'expirationTimeSeconds', - 'salt', - ]); - }, -}; diff --git a/packages/connect/src/utils/orders_channel_message_parser.ts b/packages/connect/src/utils/orders_channel_message_parser.ts deleted file mode 100644 index 9d66f7e728..0000000000 --- a/packages/connect/src/utils/orders_channel_message_parser.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { assert } from '@0x/assert'; -import { schemas } from '@0x/json-schemas'; -import * as _ from 'lodash'; - -import { OrdersChannelMessage, OrdersChannelMessageTypes } from '@0x/types'; - -import { relayerResponseJsonParsers } from './relayer_response_json_parsers'; - -export const ordersChannelMessageParser = { - parse(utf8Data: string): OrdersChannelMessage { - // parse the message - const messageObj = JSON.parse(utf8Data); - // ensure we have a type parameter to switch on - const type: string = _.get(messageObj, 'type'); - assert.assert(type !== undefined, `Message is missing a type parameter: ${utf8Data}`); - assert.isString('type', type); - // ensure we have a request id for the resulting message - const requestId: string = _.get(messageObj, 'requestId'); - assert.assert(requestId !== undefined, `Message is missing a requestId parameter: ${utf8Data}`); - assert.isString('requestId', requestId); - switch (type) { - case OrdersChannelMessageTypes.Update: { - assert.doesConformToSchema('message', messageObj, schemas.relayerApiOrdersChannelUpdateSchema); - const ordersJson = messageObj.payload; - const orders = relayerResponseJsonParsers.parseAPIOrdersJson(ordersJson); - return _.assign(messageObj, { payload: orders }); - } - default: { - return { - type: OrdersChannelMessageTypes.Unknown, - requestId, - payload: undefined, - }; - } - } - }, -}; diff --git a/packages/connect/src/utils/relayer_response_json_parsers.ts b/packages/connect/src/utils/relayer_response_json_parsers.ts deleted file mode 100644 index 6f416b55de..0000000000 --- a/packages/connect/src/utils/relayer_response_json_parsers.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { assert } from '@0x/assert'; -import { schemas } from '@0x/json-schemas'; -import { - APIOrder, - AssetPairsItem, - AssetPairsResponse, - OrderbookResponse, - OrderConfigResponse, - OrdersResponse, -} from '@0x/types'; - -import { orderParsingUtils } from './order_parsing_utils'; -import { typeConverters } from './type_converters'; - -export const relayerResponseJsonParsers = { - parseAssetDataPairsJson(json: any): AssetPairsResponse { - assert.doesConformToSchema('assetDataPairsResponse', json, schemas.relayerApiAssetDataPairsResponseSchema); - return { ...json, records: relayerResponseJsonParsers.parseAssetPairsItemsJson(json.records) }; - }, - parseAssetPairsItemsJson(json: any): AssetPairsItem[] { - return json.map((assetDataPair: any) => { - return orderParsingUtils.convertStringsFieldsToBigNumbers(assetDataPair, [ - 'assetDataA.minAmount', - 'assetDataA.maxAmount', - 'assetDataB.minAmount', - 'assetDataB.maxAmount', - ]); - }); - }, - parseOrdersJson(json: any): OrdersResponse { - assert.doesConformToSchema('relayerApiOrdersResponse', json, schemas.relayerApiOrdersResponseSchema); - return { ...json, records: relayerResponseJsonParsers.parseAPIOrdersJson(json.records) }; - }, - parseAPIOrdersJson(json: any): APIOrder[] { - return json.map(relayerResponseJsonParsers.parseAPIOrderJson.bind(relayerResponseJsonParsers)); - }, - parseAPIOrderJson(json: any): APIOrder { - assert.doesConformToSchema('relayerApiOrder', json, schemas.relayerApiOrderSchema); - return typeConverters.convertAPIOrderStringFieldsToBigNumber(json); - }, - parseOrderbookResponseJson(json: any): OrderbookResponse { - assert.doesConformToSchema('orderBookResponse', json, schemas.relayerApiOrderbookResponseSchema); - return typeConverters.convertOrderbookStringFieldsToBigNumber(json); - }, - parseOrderConfigResponseJson(json: any): OrderConfigResponse { - assert.doesConformToSchema('orderConfigResponse', json, schemas.relayerApiOrderConfigResponseSchema); - return orderParsingUtils.convertStringsFieldsToBigNumbers(json, ['makerFee', 'takerFee']); - }, -}; diff --git a/packages/connect/src/utils/type_converters.ts b/packages/connect/src/utils/type_converters.ts deleted file mode 100644 index 1be06a6ecc..0000000000 --- a/packages/connect/src/utils/type_converters.ts +++ /dev/null @@ -1,27 +0,0 @@ -import * as _ from 'lodash'; - -import { APIOrder } from '@0x/types'; - -import { orderParsingUtils } from './order_parsing_utils'; - -export const typeConverters = { - convertOrderbookStringFieldsToBigNumber(orderbook: any): any { - const bids = _.get(orderbook, 'bids', []); - const asks = _.get(orderbook, 'asks', []); - const convertedBids = { - ...bids, - records: bids.records.map((order: any) => typeConverters.convertAPIOrderStringFieldsToBigNumber(order)), - }; - const convertedAsks = { - ...asks, - records: asks.records.map((order: any) => typeConverters.convertAPIOrderStringFieldsToBigNumber(order)), - }; - return { - bids: convertedBids, - asks: convertedAsks, - }; - }, - convertAPIOrderStringFieldsToBigNumber(apiOrder: any): APIOrder { - return { ...apiOrder, order: orderParsingUtils.convertOrderStringFieldsToBigNumber(apiOrder.order) }; - }, -}; diff --git a/packages/connect/src/ws_orders_channel.ts b/packages/connect/src/ws_orders_channel.ts deleted file mode 100644 index 10e546d701..0000000000 --- a/packages/connect/src/ws_orders_channel.ts +++ /dev/null @@ -1,102 +0,0 @@ -import { OrdersChannelMessageTypes, OrdersChannelSubscriptionOpts } from '@0x/types'; -import * as _ from 'lodash'; -import { v4 as uuid } from 'uuid'; -import * as WebSocket from 'websocket'; - -import { OrdersChannel, OrdersChannelHandler } from './types'; -import { assert } from './utils/assert'; -import { ordersChannelMessageParser } from './utils/orders_channel_message_parser'; - -export interface OrdersChannelSubscriptionOptsMap { - [key: string]: OrdersChannelSubscriptionOpts; -} - -/** - * This class includes all the functionality related to interacting with a websocket endpoint - * that implements the standard relayer API v0 - */ -export class WebSocketOrdersChannel implements OrdersChannel { - private readonly _client: WebSocket.w3cwebsocket; - private readonly _handler: OrdersChannelHandler; - private readonly _subscriptionOptsMap: OrdersChannelSubscriptionOptsMap = {}; - /** - * Instantiates a new WebSocketOrdersChannel instance - * @param client A WebSocket client - * @param handler An OrdersChannelHandler instance that responds to various - * channel updates - * @return An instance of WebSocketOrdersChannel - */ - constructor(client: WebSocket.w3cwebsocket, handler: OrdersChannelHandler) { - assert.isOrdersChannelHandler('handler', handler); - // set private members - this._client = client; - this._handler = handler; - // attach client callbacks - this._client.onerror = err => { - this._handler.onError(this, err); - }; - this._client.onclose = () => { - this._handler.onClose(this); - }; - this._client.onmessage = message => { - this._handleWebSocketMessage(message); - }; - } - /** - * Subscribe to orderbook snapshots and updates from the websocket - * @param subscriptionOpts An OrdersChannelSubscriptionOpts instance describing which - * assetData pair to subscribe to - */ - public subscribe(subscriptionOpts: OrdersChannelSubscriptionOpts): void { - assert.isOrdersChannelSubscriptionOpts('subscriptionOpts', subscriptionOpts); - assert.assert(this._client.readyState === WebSocket.w3cwebsocket.OPEN, 'WebSocket connection is closed'); - const requestId = uuid(); - this._subscriptionOptsMap[requestId] = subscriptionOpts; - const subscribeMessage = { - type: 'subscribe', - channel: 'orders', - requestId, - payload: subscriptionOpts, - }; - this._client.send(JSON.stringify(subscribeMessage)); - } - /** - * Close the websocket and stop receiving updates - */ - public close(): void { - this._client.close(); - } - private _handleWebSocketMessage(message: any): void { - if (message.data === undefined) { - this._handler.onError(this, new Error(`Message does not contain data. Url: ${this._client.url}`)); - return; - } - try { - const data = message.data; - const parserResult = ordersChannelMessageParser.parse(data); - const subscriptionOpts = this._subscriptionOptsMap[parserResult.requestId]; - if (subscriptionOpts === undefined) { - this._handler.onError( - this, - new Error(`Message has unknown requestId. Url: ${this._client.url} Message: ${data}`), - ); - return; - } - switch (parserResult.type) { - case OrdersChannelMessageTypes.Update: { - this._handler.onUpdate(this, subscriptionOpts, parserResult.payload); - break; - } - default: { - this._handler.onError( - this, - new Error(`Message has unknown type parameter. Url: ${this._client.url} Message: ${data}`), - subscriptionOpts, - ); - } - } - } catch (error) { - this._handler.onError(this, error); - } - } -} diff --git a/packages/connect/test/fixtures/standard_relayer_api/asset_pairs.json b/packages/connect/test/fixtures/standard_relayer_api/asset_pairs.json deleted file mode 100644 index 603e9f67e0..0000000000 --- a/packages/connect/test/fixtures/standard_relayer_api/asset_pairs.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "total": 43, - "page": 1, - "perPage": 100, - "records": [ - { - "assetDataA": { - "minAmount": "0", - "maxAmount": "10000000000000000000", - "precision": 5, - "assetData": "0xf47261b04c32345ced77393b3530b1eed0f346429d" - }, - "assetDataB": { - "minAmount": "0", - "maxAmount": "50000000000000000000", - "precision": 5, - "assetData": "0x0257179264389b814a946f3e92105513705ca6b990" - } - } - ] -} diff --git a/packages/connect/test/fixtures/standard_relayer_api/asset_pairs.ts b/packages/connect/test/fixtures/standard_relayer_api/asset_pairs.ts deleted file mode 100644 index 3ceeffdc86..0000000000 --- a/packages/connect/test/fixtures/standard_relayer_api/asset_pairs.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { BigNumber } from '@0x/utils'; - -import { AssetPairsResponse } from '@0x/types'; - -export const assetDataPairsResponse: AssetPairsResponse = { - total: 43, - page: 1, - perPage: 100, - records: [ - { - assetDataA: { - minAmount: new BigNumber('0'), - maxAmount: new BigNumber('10000000000000000000'), - precision: 5, - assetData: '0xf47261b04c32345ced77393b3530b1eed0f346429d', - }, - assetDataB: { - minAmount: new BigNumber('0'), - maxAmount: new BigNumber('50000000000000000000'), - precision: 5, - assetData: '0x0257179264389b814a946f3e92105513705ca6b990', - }, - }, - ], -}; diff --git a/packages/connect/test/fixtures/standard_relayer_api/fee_recipients.json b/packages/connect/test/fixtures/standard_relayer_api/fee_recipients.json deleted file mode 100644 index b1d570b03e..0000000000 --- a/packages/connect/test/fixtures/standard_relayer_api/fee_recipients.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "total": 3, - "page": 1, - "perPage": 10, - "records": [ - "0x6ec92694ea172ebc430c30fa31de87620967a082", - "0x9e56625509c2f60af937f23b7b532600390e8c8b", - "0xa2b31dacf30a9c50ca473337c01d8a201ae33e32" - ] -} diff --git a/packages/connect/test/fixtures/standard_relayer_api/fee_recipients.ts b/packages/connect/test/fixtures/standard_relayer_api/fee_recipients.ts deleted file mode 100644 index 694433128f..0000000000 --- a/packages/connect/test/fixtures/standard_relayer_api/fee_recipients.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { FeeRecipientsResponse } from '@0x/types'; - -export const feeRecipientsResponse: FeeRecipientsResponse = { - total: 3, - page: 1, - perPage: 10, - records: [ - '0x6ec92694ea172ebc430c30fa31de87620967a082', - '0x9e56625509c2f60af937f23b7b532600390e8c8b', - '0xa2b31dacf30a9c50ca473337c01d8a201ae33e32', - ], -}; diff --git a/packages/connect/test/fixtures/standard_relayer_api/order/0xabc67323774bdbd24d94f977fa9ac94a50f016026fd13f42990861238897721f.json b/packages/connect/test/fixtures/standard_relayer_api/order/0xabc67323774bdbd24d94f977fa9ac94a50f016026fd13f42990861238897721f.json deleted file mode 100644 index d973347f60..0000000000 --- a/packages/connect/test/fixtures/standard_relayer_api/order/0xabc67323774bdbd24d94f977fa9ac94a50f016026fd13f42990861238897721f.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "order": { - "makerAddress": "0x9e56625509c2f60af937f23b7b532600390e8c8b", - "takerAddress": "0xa2b31dacf30a9c50ca473337c01d8a201ae33e32", - "feeRecipientAddress": "0xb046140686d052fff581f63f8136cce132e857da", - "senderAddress": "0xa2b31dacf30a9c50ca473337c01d8a201ae33e32", - "makerAssetAmount": "10000000000000000", - "takerAssetAmount": "20000000000000000", - "makerFee": "100000000000000", - "takerFee": "200000000000000", - "expirationTimeSeconds": "1532560590", - "salt": "1532559225", - "makerAssetData": "0xf47261b04c32345ced77393b3530b1eed0f346429d", - "takerAssetData": "0x0257179264389b814a946f3e92105513705ca6b990", - "makerFeeAssetData": "0xf47261b04c32345ced77393b3530b1eed0f346429d", - "takerFeeAssetData": "0x0257179264389b814a946f3e92105513705ca6b990", - "exchangeAddress": "0x12459c951127e0c374ff9105dda097662a027093", - "signature": "0x012761a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351bc33", - "chainId": 1 - }, - "metaData": {} -} diff --git a/packages/connect/test/fixtures/standard_relayer_api/order/0xabc67323774bdbd24d94f977fa9ac94a50f016026fd13f42990861238897721f.ts b/packages/connect/test/fixtures/standard_relayer_api/order/0xabc67323774bdbd24d94f977fa9ac94a50f016026fd13f42990861238897721f.ts deleted file mode 100644 index 4a4db13055..0000000000 --- a/packages/connect/test/fixtures/standard_relayer_api/order/0xabc67323774bdbd24d94f977fa9ac94a50f016026fd13f42990861238897721f.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { BigNumber } from '@0x/utils'; - -export const orderResponse = { - order: { - makerAddress: '0x9e56625509c2f60af937f23b7b532600390e8c8b', - takerAddress: '0xa2b31dacf30a9c50ca473337c01d8a201ae33e32', - feeRecipientAddress: '0xb046140686d052fff581f63f8136cce132e857da', - senderAddress: '0xa2b31dacf30a9c50ca473337c01d8a201ae33e32', - makerAssetAmount: new BigNumber('10000000000000000'), - takerAssetAmount: new BigNumber('20000000000000000'), - makerFee: new BigNumber('100000000000000'), - takerFee: new BigNumber('200000000000000'), - expirationTimeSeconds: new BigNumber('1532560590'), - salt: new BigNumber('1532559225'), - makerAssetData: '0xf47261b04c32345ced77393b3530b1eed0f346429d', - takerAssetData: '0x0257179264389b814a946f3e92105513705ca6b990', - makerFeeAssetData: '0xf47261b04c32345ced77393b3530b1eed0f346429d', - takerFeeAssetData: '0x0257179264389b814a946f3e92105513705ca6b990', - exchangeAddress: '0x12459c951127e0c374ff9105dda097662a027093', - signature: '0x012761a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351bc33', - chainId: 1, - }, - metaData: {}, -}; diff --git a/packages/connect/test/fixtures/standard_relayer_api/order_config.json b/packages/connect/test/fixtures/standard_relayer_api/order_config.json deleted file mode 100644 index ad2c2cd827..0000000000 --- a/packages/connect/test/fixtures/standard_relayer_api/order_config.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "senderAddress": "0xa2b31dacf30a9c50ca473337c01d8a201ae33e32", - "feeRecipientAddress": "0xb046140686d052fff581f63f8136cce132e857da", - "makerFee": "100000000000000", - "takerFee": "200000000000000", - "makerFeeAssetData": "0xf47261b04c32345ced77393b3530b1eed0f346429d", - "takerFeeAssetData": "0xf47261b04c32345ced77393b3530b1eed0f346429d" -} diff --git a/packages/connect/test/fixtures/standard_relayer_api/order_config.ts b/packages/connect/test/fixtures/standard_relayer_api/order_config.ts deleted file mode 100644 index 94dcde71f8..0000000000 --- a/packages/connect/test/fixtures/standard_relayer_api/order_config.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { BigNumber } from '@0x/utils'; - -import { OrderConfigResponse } from '@0x/types'; - -export const orderConfigResponse: OrderConfigResponse = { - senderAddress: '0xa2b31dacf30a9c50ca473337c01d8a201ae33e32', - feeRecipientAddress: '0xb046140686d052fff581f63f8136cce132e857da', - makerFee: new BigNumber('100000000000000'), - takerFee: new BigNumber('200000000000000'), - makerFeeAssetData: '0xf47261b04c32345ced77393b3530b1eed0f346429d', - takerFeeAssetData: '0xf47261b04c32345ced77393b3530b1eed0f346429d', -}; diff --git a/packages/connect/test/fixtures/standard_relayer_api/orderbook.json b/packages/connect/test/fixtures/standard_relayer_api/orderbook.json deleted file mode 100644 index 6a69b708f0..0000000000 --- a/packages/connect/test/fixtures/standard_relayer_api/orderbook.json +++ /dev/null @@ -1,60 +0,0 @@ -{ - "bids": { - "total": 325, - "page": 2, - "perPage": 100, - "records": [ - { - "order": { - "makerAddress": "0x9e56625509c2f60af937f23b7b532600390e8c8b", - "takerAddress": "0xa2b31dacf30a9c50ca473337c01d8a201ae33e32", - "feeRecipientAddress": "0xb046140686d052fff581f63f8136cce132e857da", - "senderAddress": "0xa2b31dacf30a9c50ca473337c01d8a201ae33e32", - "makerAssetAmount": "10000000000000000", - "takerAssetAmount": "20000000000000000", - "makerFee": "100000000000000", - "takerFee": "200000000000000", - "expirationTimeSeconds": "1532560590", - "salt": "1532559225", - "makerAssetData": "0xf47261b04c32345ced77393b3530b1eed0f346429d", - "takerAssetData": "0x0257179264389b814a946f3e92105513705ca6b990", - "makerFeeAssetData": "0xf47261b04c32345ced77393b3530b1eed0f346429d", - "takerFeeAssetData": "0x0257179264389b814a946f3e92105513705ca6b990", - "exchangeAddress": "0x12459c951127e0c374ff9105dda097662a027093", - "signature": "0x012761a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351bc33", - "chainId": 1 - }, - "metaData": {} - } - ] - }, - "asks": { - "total": 500, - "page": 2, - "perPage": 100, - "records": [ - { - "order": { - "makerAddress": "0xa2b31dacf30a9c50ca473337c01d8a201ae33e32", - "takerAddress": "0x9e56625509c2f60af937f23b7b532600390e8c8b", - "feeRecipientAddress": "0xb046140686d052fff581f63f8136cce132e857da", - "senderAddress": "0xa2b31dacf30a9c50ca473337c01d8a201ae33e32", - "makerAssetAmount": "20000000000000000", - "takerAssetAmount": "10000000000000000", - "makerFee": "200000000000000", - "takerFee": "100000000000000", - "expirationTimeSeconds": "1532560590", - "salt": "1532559225", - "makerAssetData": "0x0257179264389b814a946f3e92105513705ca6b990", - "takerAssetData": "0xf47261b04c32345ced77393b3530b1eed0f346429d", - "makerFeeAssetData": "0x0257179264389b814a946f3e92105513705ca6b990", - "takerFeeAssetData": "0xf47261b04c32345ced77393b3530b1eed0f346429d", - "exchangeAddress": "0x12459c951127e0c374ff9105dda097662a027093", - "signature": "0x013842a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b3518891", - "chainId": 1 - }, - "metaData": {} - } - ] - } -} diff --git a/packages/connect/test/fixtures/standard_relayer_api/orderbook.ts b/packages/connect/test/fixtures/standard_relayer_api/orderbook.ts deleted file mode 100644 index fa639d38fe..0000000000 --- a/packages/connect/test/fixtures/standard_relayer_api/orderbook.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { BigNumber } from '@0x/utils'; - -import { OrderbookResponse } from '@0x/types'; - -export const orderbookResponse: OrderbookResponse = { - bids: { - total: 325, - page: 2, - perPage: 100, - records: [ - { - order: { - makerAddress: '0x9e56625509c2f60af937f23b7b532600390e8c8b', - takerAddress: '0xa2b31dacf30a9c50ca473337c01d8a201ae33e32', - feeRecipientAddress: '0xb046140686d052fff581f63f8136cce132e857da', - senderAddress: '0xa2b31dacf30a9c50ca473337c01d8a201ae33e32', - makerAssetAmount: new BigNumber('10000000000000000'), - takerAssetAmount: new BigNumber('20000000000000000'), - makerFee: new BigNumber('100000000000000'), - takerFee: new BigNumber('200000000000000'), - expirationTimeSeconds: new BigNumber('1532560590'), - salt: new BigNumber('1532559225'), - makerAssetData: '0xf47261b04c32345ced77393b3530b1eed0f346429d', - takerAssetData: '0x0257179264389b814a946f3e92105513705ca6b990', - makerFeeAssetData: '0xf47261b04c32345ced77393b3530b1eed0f346429d', - takerFeeAssetData: '0x0257179264389b814a946f3e92105513705ca6b990', - signature: '0x012761a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351bc33', - chainId: 1, - exchangeAddress: '0x12459c951127e0c374ff9105dda097662a027093', - }, - metaData: {}, - }, - ], - }, - asks: { - total: 500, - page: 2, - perPage: 100, - records: [ - { - order: { - makerAddress: '0xa2b31dacf30a9c50ca473337c01d8a201ae33e32', - takerAddress: '0x9e56625509c2f60af937f23b7b532600390e8c8b', - feeRecipientAddress: '0xb046140686d052fff581f63f8136cce132e857da', - senderAddress: '0xa2b31dacf30a9c50ca473337c01d8a201ae33e32', - makerAssetAmount: new BigNumber('20000000000000000'), - takerAssetAmount: new BigNumber('10000000000000000'), - makerFee: new BigNumber('200000000000000'), - takerFee: new BigNumber('100000000000000'), - expirationTimeSeconds: new BigNumber('1532560590'), - salt: new BigNumber('1532559225'), - makerAssetData: '0x0257179264389b814a946f3e92105513705ca6b990', - takerAssetData: '0xf47261b04c32345ced77393b3530b1eed0f346429d', - makerFeeAssetData: '0x0257179264389b814a946f3e92105513705ca6b990', - takerFeeAssetData: '0xf47261b04c32345ced77393b3530b1eed0f346429d', - signature: '0x013842a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b3518891', - chainId: 1, - exchangeAddress: '0x12459c951127e0c374ff9105dda097662a027093', - }, - metaData: {}, - }, - ], - }, -}; diff --git a/packages/connect/test/fixtures/standard_relayer_api/orders.json b/packages/connect/test/fixtures/standard_relayer_api/orders.json deleted file mode 100644 index 755e2a1d5f..0000000000 --- a/packages/connect/test/fixtures/standard_relayer_api/orders.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "total": 984, - "page": 1, - "perPage": 100, - "records": [ - { - "order": { - "makerAddress": "0x9e56625509c2f60af937f23b7b532600390e8c8b", - "takerAddress": "0xa2b31dacf30a9c50ca473337c01d8a201ae33e32", - "feeRecipientAddress": "0xb046140686d052fff581f63f8136cce132e857da", - "senderAddress": "0xa2b31dacf30a9c50ca473337c01d8a201ae33e32", - "makerAssetAmount": "10000000000000000", - "takerAssetAmount": "20000000000000000", - "makerFee": "100000000000000", - "takerFee": "200000000000000", - "expirationTimeSeconds": "1532560590", - "salt": "1532559225", - "makerAssetData": "0xf47261b04c32345ced77393b3530b1eed0f346429d", - "takerAssetData": "0x0257179264389b814a946f3e92105513705ca6b990", - "makerFeeAssetData": "0xf47261b04c32345ced77393b3530b1eed0f346429d", - "takerFeeAssetData": "0x0257179264389b814a946f3e92105513705ca6b990", - "exchangeAddress": "0x12459c951127e0c374ff9105dda097662a027093", - "signature": "0x012761a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351bc33", - "chainId": 1 - }, - "metaData": {} - } - ] -} diff --git a/packages/connect/test/fixtures/standard_relayer_api/orders.ts b/packages/connect/test/fixtures/standard_relayer_api/orders.ts deleted file mode 100644 index 018b0851f0..0000000000 --- a/packages/connect/test/fixtures/standard_relayer_api/orders.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { BigNumber } from '@0x/utils'; - -import { OrdersResponse } from '@0x/types'; - -export const ordersResponse: OrdersResponse = { - total: 984, - page: 1, - perPage: 100, - records: [ - { - order: { - makerAddress: '0x9e56625509c2f60af937f23b7b532600390e8c8b', - takerAddress: '0xa2b31dacf30a9c50ca473337c01d8a201ae33e32', - feeRecipientAddress: '0xb046140686d052fff581f63f8136cce132e857da', - senderAddress: '0xa2b31dacf30a9c50ca473337c01d8a201ae33e32', - makerAssetAmount: new BigNumber('10000000000000000'), - takerAssetAmount: new BigNumber('20000000000000000'), - makerFee: new BigNumber('100000000000000'), - takerFee: new BigNumber('200000000000000'), - expirationTimeSeconds: new BigNumber('1532560590'), - salt: new BigNumber('1532559225'), - makerAssetData: '0xf47261b04c32345ced77393b3530b1eed0f346429d', - takerAssetData: '0x0257179264389b814a946f3e92105513705ca6b990', - makerFeeAssetData: '0xf47261b04c32345ced77393b3530b1eed0f346429d', - takerFeeAssetData: '0x0257179264389b814a946f3e92105513705ca6b990', - signature: '0x012761a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351bc33', - chainId: 1, - exchangeAddress: '0x12459c951127e0c374ff9105dda097662a027093', - }, - metaData: {}, - }, - ], -}; diff --git a/packages/connect/test/fixtures/standard_relayer_api/unknown_orders_channel_message.ts b/packages/connect/test/fixtures/standard_relayer_api/unknown_orders_channel_message.ts deleted file mode 100644 index b6c0cd50c5..0000000000 --- a/packages/connect/test/fixtures/standard_relayer_api/unknown_orders_channel_message.ts +++ /dev/null @@ -1,10 +0,0 @@ -import * as orderResponseJSON from './order/0xabc67323774bdbd24d94f977fa9ac94a50f016026fd13f42990861238897721f.json'; - -const orderJSONString = JSON.stringify(orderResponseJSON); - -export const unknownOrdersChannelMessage = `{ - "type": "superGoodUpdate", - "channel": "orderbook", - "requestId": "6ce8c5a6-5c46-4027-a44a-51831c77b8a1", - "payload": [${orderJSONString}] -}`; diff --git a/packages/connect/test/fixtures/standard_relayer_api/update_orders_channel_message.ts b/packages/connect/test/fixtures/standard_relayer_api/update_orders_channel_message.ts deleted file mode 100644 index c18a2c7895..0000000000 --- a/packages/connect/test/fixtures/standard_relayer_api/update_orders_channel_message.ts +++ /dev/null @@ -1,17 +0,0 @@ -import * as apiOrderJSON from './order/0xabc67323774bdbd24d94f977fa9ac94a50f016026fd13f42990861238897721f.json'; - -const apiOrderJSONString = JSON.stringify(apiOrderJSON); - -export const updateOrdersChannelMessage = `{ - "type": "update", - "channel": "orders", - "requestId": "5a1ce3a2-22b9-41e6-a615-68077512e9e2", - "payload": [${apiOrderJSONString}] -}`; - -export const malformedUpdateOrdersChannelMessage = `{ - "type": "update", - "channel": "orders", - "requestId": "4d8efcee-adde-4475-9601-f0b30962ca2b", - "payload": {} -}`; diff --git a/packages/connect/test/http_client_test.ts b/packages/connect/test/http_client_test.ts deleted file mode 100644 index 48d767d020..0000000000 --- a/packages/connect/test/http_client_test.ts +++ /dev/null @@ -1,189 +0,0 @@ -import { BigNumber } from '@0x/utils'; -import * as chai from 'chai'; -import * as chaiAsPromised from 'chai-as-promised'; -import * as dirtyChai from 'dirty-chai'; -import * as fetchMock from 'fetch-mock'; -import 'mocha'; - -import { HttpClient } from '../src/index'; - -import { assetDataPairsResponse } from './fixtures/standard_relayer_api/asset_pairs'; -import * as assetDataPairsResponseJSON from './fixtures/standard_relayer_api/asset_pairs.json'; -import { feeRecipientsResponse } from './fixtures/standard_relayer_api/fee_recipients'; -import * as feeRecipientsResponseJSON from './fixtures/standard_relayer_api/fee_recipients.json'; -import { orderResponse } from './fixtures/standard_relayer_api/order/0xabc67323774bdbd24d94f977fa9ac94a50f016026fd13f42990861238897721f'; -import * as orderResponseJSON from './fixtures/standard_relayer_api/order/0xabc67323774bdbd24d94f977fa9ac94a50f016026fd13f42990861238897721f.json'; -import { orderConfigResponse } from './fixtures/standard_relayer_api/order_config'; -import * as orderConfigResponseJSON from './fixtures/standard_relayer_api/order_config.json'; -import { orderbookResponse } from './fixtures/standard_relayer_api/orderbook'; -import * as orderbookJSON from './fixtures/standard_relayer_api/orderbook.json'; -import { ordersResponse } from './fixtures/standard_relayer_api/orders'; -import * as ordersResponseJSON from './fixtures/standard_relayer_api/orders.json'; - -chai.config.includeStack = true; -chai.use(dirtyChai); -chai.use(chaiAsPromised); -const expect = chai.expect; - -describe('HttpClient', () => { - const relayUrl = 'https://example.com'; - const relayerClient = new HttpClient(relayUrl); - beforeEach(() => { - fetchMock.restore(); - }); - describe('#constructor', () => { - it('should remove trailing slashes from api url', async () => { - const urlWithTrailingSlash = 'https://slash.com/'; - const urlWithoutTrailingSlash = 'https://slash.com'; - const client = new HttpClient(urlWithTrailingSlash); - const sanitizedUrl = (client as any)._apiEndpointUrl; - expect(sanitizedUrl).to.be.deep.equal(urlWithoutTrailingSlash); - }); - }); - describe('#getAssetPairsAsync', () => { - const url = `${relayUrl}/asset_pairs`; - it('gets assetData pairs with default options when none are provided', async () => { - fetchMock.get(url, assetDataPairsResponseJSON); - const assetDataPairs = await relayerClient.getAssetPairsAsync(); - expect(assetDataPairs).to.be.deep.equal(assetDataPairsResponse); - }); - it('gets assetData pairs with specified request options', async () => { - const assetData = '0xf47261b04c32345ced77393b3530b1eed0f346429d'; - const assetPairsRequestOpts = { - assetDataA: assetData, - page: 3, - perPage: 50, - }; - const urlWithQuery = `${url}?assetDataA=${assetData}&page=3&perPage=50`; - fetchMock.get(urlWithQuery, assetDataPairsResponseJSON); - const assetDataPairs = await relayerClient.getAssetPairsAsync(assetPairsRequestOpts); - expect(assetDataPairs).to.be.deep.equal(assetDataPairsResponse); - }); - it('throws an error for invalid JSON response', async () => { - fetchMock.get(url, { test: 'dummy' }); - expect(relayerClient.getAssetPairsAsync()).to.be.rejected(); - }); - }); - describe('#getOrdersAsync', () => { - const url = `${relayUrl}/orders`; - it('gets orders with default options when none are provided', async () => { - fetchMock.get(url, ordersResponseJSON); - const orders = await relayerClient.getOrdersAsync(); - expect(orders).to.be.deep.equal(ordersResponse); - }); - it('gets orders with specified request options', async () => { - const assetDataAddress = '0x323b5d4c32345ced77393b3530b1eed0f346429d'; - const ordersRequest = { - assetDataAddress, - page: 3, - perPage: 50, - }; - const urlWithQuery = `${url}?assetDataAddress=${assetDataAddress}&page=3&perPage=50`; - fetchMock.get(urlWithQuery, ordersResponseJSON); - const orders = await relayerClient.getOrdersAsync(ordersRequest); - expect(orders).to.be.deep.equal(ordersResponse); - }); - it('throws an error for invalid JSON response', async () => { - fetchMock.get(url, { test: 'dummy' }); - expect(relayerClient.getOrdersAsync()).to.be.rejected(); - }); - }); - describe('#getOrderAsync', () => { - const orderHash = '0xabc67323774bdbd24d94f977fa9ac94a50f016026fd13f42990861238897721f'; - const url = `${relayUrl}/order/${orderHash}`; - it('gets order', async () => { - fetchMock.get(url, orderResponseJSON); - const order = await relayerClient.getOrderAsync(orderHash); - expect(order).to.be.deep.equal(orderResponse); - }); - it('throws an error for invalid JSON response', async () => { - fetchMock.get(url, { test: 'dummy' }); - expect(relayerClient.getOrderAsync(orderHash)).to.be.rejected(); - }); - }); - describe('#getOrderBookAsync', () => { - const request = { - baseAssetData: '0x323b5d4c32345ced77393b3530b1eed0f346429d', - quoteAssetData: '0xa2b31dacf30a9c50ca473337c01d8a201ae33e32', - }; - const url = `${relayUrl}/orderbook`; - it('gets orderbook with default page options when none are provided', async () => { - const urlWithQuery = `${url}?baseAssetData=${request.baseAssetData}"eAssetData=${ - request.quoteAssetData - }`; - fetchMock.get(urlWithQuery, orderbookJSON); - const orderbook = await relayerClient.getOrderbookAsync(request); - expect(orderbook).to.be.deep.equal(orderbookResponse); - }); - it('gets orderbook with specified page options', async () => { - const urlWithQuery = `${url}?baseAssetData=${request.baseAssetData}&page=3&perPage=50"eAssetData=${ - request.quoteAssetData - }`; - fetchMock.get(urlWithQuery, orderbookJSON); - const pagedRequestOptions = { - page: 3, - perPage: 50, - }; - const orderbook = await relayerClient.getOrderbookAsync(request, pagedRequestOptions); - expect(orderbook).to.be.deep.equal(orderbookResponse); - }); - it('throws an error for invalid JSON response', async () => { - fetchMock.get(url, { test: 'dummy' }); - expect(relayerClient.getOrderbookAsync(request)).to.be.rejected(); - }); - }); - describe('#getOrderConfigAsync', () => { - const request = { - makerAddress: '0x9e56625509c2f60af937f23b7b532600390e8c8b', - takerAddress: '0xa2b31dacf30a9c50ca473337c01d8a201ae33e32', - makerAssetAmount: new BigNumber('10000000000000000'), - takerAssetAmount: new BigNumber('20000000000000000'), - expirationTimeSeconds: new BigNumber('1532560590'), - makerAssetData: '0xf47261b04c32345ced77393b3530b1eed0f346429d', - takerAssetData: '0x0257179264389b814a946f3e92105513705ca6b990', - exchangeAddress: '0x12459c951127e0c374ff9105dda097662a027093', - }; - const url = `${relayUrl}/order_config`; - it('gets order config', async () => { - fetchMock.post(url, orderConfigResponseJSON); - const fees = await relayerClient.getOrderConfigAsync(request); - expect(fees).to.be.deep.equal(orderConfigResponse); - }); - it('does not mutate input', async () => { - fetchMock.post(url, orderConfigResponseJSON); - const makerAssetAmountBefore = request.makerAssetAmount; - const takerAssetAmountBefore = request.takerAssetAmount; - const expirationTimeSecondsBefore = request.expirationTimeSeconds; - await relayerClient.getOrderConfigAsync(request); - expect(makerAssetAmountBefore).to.be.deep.equal(request.makerAssetAmount); - expect(takerAssetAmountBefore).to.be.deep.equal(request.takerAssetAmount); - expect(expirationTimeSecondsBefore).to.be.deep.equal(request.expirationTimeSeconds); - }); - it('throws an error for invalid JSON response', async () => { - fetchMock.post(url, { test: 'dummy' }); - expect(relayerClient.getOrderConfigAsync(request)).to.be.rejected(); - }); - }); - describe('#getFeeRecipientsAsync', () => { - const url = `${relayUrl}/fee_recipients`; - it('gets fee recipients with default page options when none are provided', async () => { - fetchMock.get(url, feeRecipientsResponseJSON); - const feeRecipients = await relayerClient.getFeeRecipientsAsync(); - expect(feeRecipients).to.be.deep.equal(feeRecipientsResponse); - }); - it('gets fee recipient with specified page options', async () => { - const urlWithQuery = `${url}?page=3&perPage=50`; - fetchMock.get(urlWithQuery, feeRecipientsResponseJSON); - const pagedRequestOptions = { - page: 3, - perPage: 50, - }; - const feeRecipients = await relayerClient.getFeeRecipientsAsync(pagedRequestOptions); - expect(feeRecipients).to.be.deep.equal(feeRecipientsResponse); - }); - it('throws an error for invalid JSON response', async () => { - fetchMock.get(url, { test: 'dummy' }); - expect(relayerClient.getFeeRecipientsAsync()).to.be.rejected(); - }); - }); -}); diff --git a/packages/connect/test/orders_channel_factory_test.ts b/packages/connect/test/orders_channel_factory_test.ts deleted file mode 100644 index 29aa87c65d..0000000000 --- a/packages/connect/test/orders_channel_factory_test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import * as chai from 'chai'; -import * as dirtyChai from 'dirty-chai'; -import * as _ from 'lodash'; - -import 'mocha'; - -import { ordersChannelFactory } from '../src/orders_channel_factory'; - -chai.config.includeStack = true; -chai.use(dirtyChai); -const expect = chai.expect; -const emptyOrdersChannelHandler = { - onUpdate: _.noop.bind(_), - onError: _.noop.bind(_), - onClose: _.noop.bind(_), -}; - -describe('ordersChannelFactory', () => { - const websocketUrl = 'ws://localhost:8080'; - describe('#createWebSocketOrdersChannelAsync', () => { - it('throws when input is not a url', () => { - const badUrlInput = 54; - expect( - ordersChannelFactory.createWebSocketOrdersChannelAsync(badUrlInput as any, emptyOrdersChannelHandler), - ).to.be.rejected(); - }); - it('throws when handler has the incorrect members', () => { - const badHandlerInput = {}; - expect( - ordersChannelFactory.createWebSocketOrdersChannelAsync(websocketUrl, badHandlerInput as any), - ).to.be.rejected(); - }); - }); -}); diff --git a/packages/connect/test/orders_channel_message_parsers_test.ts b/packages/connect/test/orders_channel_message_parsers_test.ts deleted file mode 100644 index 4d4a2d23fb..0000000000 --- a/packages/connect/test/orders_channel_message_parsers_test.ts +++ /dev/null @@ -1,59 +0,0 @@ -import * as chai from 'chai'; -import * as dirtyChai from 'dirty-chai'; -import 'mocha'; - -import { ordersChannelMessageParser } from '../src/utils/orders_channel_message_parser'; - -import { orderResponse } from './fixtures/standard_relayer_api/order/0xabc67323774bdbd24d94f977fa9ac94a50f016026fd13f42990861238897721f'; -import { unknownOrdersChannelMessage } from './fixtures/standard_relayer_api/unknown_orders_channel_message'; -import { - malformedUpdateOrdersChannelMessage, - updateOrdersChannelMessage, -} from './fixtures/standard_relayer_api/update_orders_channel_message'; - -chai.config.includeStack = true; -chai.use(dirtyChai); -const expect = chai.expect; - -describe('ordersChannelMessageParser', () => { - describe('#parser', () => { - it('parses update messages', () => { - const updateMessage = ordersChannelMessageParser.parse(updateOrdersChannelMessage); - expect(updateMessage.type).to.be.equal('update'); - expect(updateMessage.payload).to.be.deep.equal([orderResponse]); - }); - it('returns unknown message for messages with unsupported types', () => { - const unknownMessage = ordersChannelMessageParser.parse(unknownOrdersChannelMessage); - expect(unknownMessage.type).to.be.equal('unknown'); - expect(unknownMessage.payload).to.be.undefined(); - }); - it('throws when message does not include a type', () => { - const typelessMessage = `{ - "channel": "orders", - "requestId": "4d8efcee-adde-4475-9601-f0b30962ca2b", - "payload": [] - }`; - const badCall = () => ordersChannelMessageParser.parse(typelessMessage); - expect(badCall).throws(`Message is missing a type parameter: ${typelessMessage}`); - }); - it('throws when type is not a string', () => { - const messageWithBadType = `{ - "type": 1, - "channel": "orders", - "requestId": "4d8efcee-adde-4475-9601-f0b30962ca2b", - "payload": [] - }`; - const badCall = () => ordersChannelMessageParser.parse(messageWithBadType); - expect(badCall).throws('Expected type to be of type string, encountered: 1'); - }); - it('throws when update message has malformed payload', () => { - const badCall = () => ordersChannelMessageParser.parse(malformedUpdateOrdersChannelMessage); - expect(badCall).throws(/^Expected message to conform to schema/); - }); - it('throws when input message is not valid JSON', () => { - const nonJsonString = 'h93b{sdfs9fsd f'; - const badCall = () => ordersChannelMessageParser.parse(nonJsonString); - expect(badCall).throws('Unexpected token h in JSON at position 0'); - }); - }); -}); diff --git a/packages/connect/test/ws_orders_channel_test.ts b/packages/connect/test/ws_orders_channel_test.ts deleted file mode 100644 index df30bc41d0..0000000000 --- a/packages/connect/test/ws_orders_channel_test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import * as chai from 'chai'; -import * as dirtyChai from 'dirty-chai'; -import * as _ from 'lodash'; -import 'mocha'; -import * as Sinon from 'sinon'; -import * as WebSocket from 'websocket'; - -import { WebSocketOrdersChannel } from '../src/ws_orders_channel'; - -chai.config.includeStack = true; -chai.use(dirtyChai); -const expect = chai.expect; -const emptyOrdersChannelHandler = { - onUpdate: _.noop.bind(_), - onError: _.noop.bind(_), - onClose: _.noop.bind(_), -}; - -describe('WebSocketOrdersChannel', () => { - const websocketUrl = 'ws://localhost:8080'; - const openClient = new WebSocket.w3cwebsocket(websocketUrl); - Sinon.stub(openClient, 'readyState').get(() => WebSocket.w3cwebsocket.OPEN); - Sinon.stub(openClient, 'send').callsFake(_.noop.bind(_)); - const openOrdersChannel = new WebSocketOrdersChannel(openClient, emptyOrdersChannelHandler); - const subscriptionOpts = { - baseAssetData: '0x323b5d4c32345ced77393b3530b1eed0f346429d', - quoteAssetData: '0xef7fff64389b814a946f3e92105513705ca6b990', - limit: 100, - }; - describe('#subscribe', () => { - it('throws when subscriptionOpts does not conform to schema', () => { - const badSubscribeCall = openOrdersChannel.subscribe.bind(openOrdersChannel, { - makerAssetData: 5, - }); - expect(badSubscribeCall).throws(); - }); - it('does not throw when inputs are of correct types', () => { - const goodSubscribeCall = openOrdersChannel.subscribe.bind(openOrdersChannel, subscriptionOpts); - expect(goodSubscribeCall).to.not.throw(); - }); - it('throws when client is closed', () => { - const closedClient = new WebSocket.w3cwebsocket(websocketUrl); - Sinon.stub(closedClient, 'readyState').get(() => WebSocket.w3cwebsocket.CLOSED); - const closedOrdersChannel = new WebSocketOrdersChannel(closedClient, emptyOrdersChannelHandler); - const badSubscribeCall = closedOrdersChannel.subscribe.bind(closedOrdersChannel, subscriptionOpts); - expect(badSubscribeCall).throws('WebSocket connection is closed'); - }); - }); -}); diff --git a/packages/connect/tsconfig.json b/packages/connect/tsconfig.json deleted file mode 100644 index 2ee711adcc..0000000000 --- a/packages/connect/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../tsconfig", - "compilerOptions": { - "outDir": "lib", - "rootDir": "." - }, - "include": ["./src/**/*", "./test/**/*"] -} diff --git a/packages/connect/tslint.json b/packages/connect/tslint.json deleted file mode 100644 index dd9053357e..0000000000 --- a/packages/connect/tslint.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": ["@0x/tslint-config"] -} diff --git a/packages/connect/typedoc-tsconfig.json b/packages/connect/typedoc-tsconfig.json deleted file mode 100644 index c9b0af1ae6..0000000000 --- a/packages/connect/typedoc-tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "../../typedoc-tsconfig", - "compilerOptions": { - "outDir": "lib" - }, - "include": ["./src/**/*", "./test/**/*"] -} diff --git a/packages/contracts-gen/.npmignore b/packages/contracts-gen/.npmignore deleted file mode 100644 index 8053fd5d11..0000000000 --- a/packages/contracts-gen/.npmignore +++ /dev/null @@ -1,10 +0,0 @@ -# Blacklist all files -.* -* -# Whitelist lib -!lib/**/* -# Blacklist tests and publish scripts -/lib/test/* -/lib/monorepo_scripts/ -# Package specific ignore -!bin/**/* diff --git a/packages/contracts-gen/CHANGELOG.json b/packages/contracts-gen/CHANGELOG.json deleted file mode 100644 index c693c285a8..0000000000 --- a/packages/contracts-gen/CHANGELOG.json +++ /dev/null @@ -1,291 +0,0 @@ -[ - { - "timestamp": 1594788383, - "version": "2.0.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1592969527, - "version": "2.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1582623685, - "version": "2.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1581204851, - "version": "2.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1580988106, - "version": "2.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1580811564, - "version": "2.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1579682890, - "version": "2.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1578272714, - "version": "2.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1576540892, - "version": "2.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1575931811, - "version": "2.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.0", - "changes": [ - { - "note": "Generate boilerplate for all contracts if none are specified or if all contracts identifier is used", - "pr": 2055 - }, - { - "note": "Fixed sorting in artifact generation", - "pr": 1910 - } - ], - "timestamp": 1575296764 - }, - { - "version": "1.1.0-beta.4", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1575290197 - }, - { - "version": "1.1.0-beta.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1574238768 - }, - { - "version": "1.1.0-beta.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1574030254 - }, - { - "version": "1.1.0-beta.1", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1573159180 - }, - { - "version": "1.1.0-beta.0", - "changes": [ - { - "note": "Generate boilerplate for all contracts if none are specified or if all contracts identifier is used", - "pr": 2055 - }, - { - "note": "Fixed sorting in artifact generation", - "pr": 1910 - } - ], - "timestamp": 1570135330 - }, - { - "timestamp": 1568744790, - "version": "1.0.15", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1567521715, - "version": "1.0.14", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1565296576, - "version": "1.0.13", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1564604963, - "version": "1.0.12", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563957393, - "version": "1.0.11", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563006338, - "version": "1.0.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1557507213, - "version": "1.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1554997931 - }, - { - "timestamp": 1553183790, - "version": "1.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1553091633, - "version": "1.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551479279, - "version": "1.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551220833, - "version": "1.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551130135, - "version": "1.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1549733923, - "version": "1.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1549547375 - } -] diff --git a/packages/contracts-gen/CHANGELOG.md b/packages/contracts-gen/CHANGELOG.md deleted file mode 100644 index 590654272c..0000000000 --- a/packages/contracts-gen/CHANGELOG.md +++ /dev/null @@ -1,132 +0,0 @@ - - -CHANGELOG - -## v2.0.10 - _July 15, 2020_ - - * Dependencies updated - -## v2.0.9 - _June 24, 2020_ - - * Dependencies updated - -## v2.0.8 - _February 25, 2020_ - - * Dependencies updated - -## v2.0.7 - _February 8, 2020_ - - * Dependencies updated - -## v2.0.6 - _February 6, 2020_ - - * Dependencies updated - -## v2.0.5 - _February 4, 2020_ - - * Dependencies updated - -## v2.0.4 - _January 22, 2020_ - - * Dependencies updated - -## v2.0.3 - _January 6, 2020_ - - * Dependencies updated - -## v2.0.2 - _December 17, 2019_ - - * Dependencies updated - -## v2.0.1 - _December 9, 2019_ - - * Dependencies updated - -## v2.0.0 - _December 2, 2019_ - - * Generate boilerplate for all contracts if none are specified or if all contracts identifier is used (#2055) - * Fixed sorting in artifact generation (#1910) - -## v1.1.0-beta.4 - _December 2, 2019_ - - * Dependencies updated - -## v1.1.0-beta.3 - _November 20, 2019_ - - * Dependencies updated - -## v1.1.0-beta.2 - _November 17, 2019_ - - * Dependencies updated - -## v1.1.0-beta.1 - _November 7, 2019_ - - * Dependencies updated - -## v1.1.0-beta.0 - _October 3, 2019_ - - * Generate boilerplate for all contracts if none are specified or if all contracts identifier is used (#2055) - * Fixed sorting in artifact generation (#1910) - -## v1.0.15 - _September 17, 2019_ - - * Dependencies updated - -## v1.0.14 - _September 3, 2019_ - - * Dependencies updated - -## v1.0.13 - _August 8, 2019_ - - * Dependencies updated - -## v1.0.12 - _July 31, 2019_ - - * Dependencies updated - -## v1.0.11 - _July 24, 2019_ - - * Dependencies updated - -## v1.0.10 - _July 13, 2019_ - - * Dependencies updated - -## v1.0.9 - _May 10, 2019_ - - * Dependencies updated - -## v1.0.8 - _April 11, 2019_ - - * Dependencies updated - -## v1.0.7 - _March 21, 2019_ - - * Dependencies updated - -## v1.0.6 - _March 20, 2019_ - - * Dependencies updated - -## v1.0.5 - _March 1, 2019_ - - * Dependencies updated - -## v1.0.4 - _February 26, 2019_ - - * Dependencies updated - -## v1.0.3 - _February 25, 2019_ - - * Dependencies updated - -## v1.0.2 - _February 9, 2019_ - - * Dependencies updated - -## v1.0.1 - _February 7, 2019_ - - * Dependencies updated diff --git a/packages/contracts-gen/README.md b/packages/contracts-gen/README.md deleted file mode 100644 index feaf9e65f7..0000000000 --- a/packages/contracts-gen/README.md +++ /dev/null @@ -1,76 +0,0 @@ -# Contracts Gen - -This package allows you to generate boilerplate TypeScript code and configs for smart contracts packages. - -## Installation - -`yarn add -g @0x/contracts-gen` - -## Usage - -Run it from within your smart contracts packages. - -```bash -contracts-gen -``` - -You should run this tool after each time you move your contracts around to regenerate boilerplate code and configs. - -## What can it generate - -This tool does the following: - -- Reads your `compiler.json`. Specifically the list of smart contracts. -- Creates `wrapper.ts` file which exports all contract wrappers. -- Creates `artifacts.ts` file which exports all contract artifacts. -- Generates list of JSON artifact files in `tsconfig.json` -- Generates a glob for abi-gen in `package.json` - -On top of that - if your `compiler.json` has contracts referenced just by name - it will resolve the name to relative path and put it there. -It also sorts all the lists in it's output leading to smaller and cleaner diffs. - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install dependencies - -If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: - -```bash -yarn config set workspaces-experimental true -``` - -Then install dependencies - -```bash -yarn install -``` - -### Build - -To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory: - -```bash -PKG=@0x/contracts-gen yarn build -``` - -Or continuously rebuild on change: - -```bash -PKG=@0x/contracts-gen yarn watch -``` - -### Clean - -```bash -yarn clean -``` - -### Lint - -```bash -yarn lint -``` diff --git a/packages/contracts-gen/bin/contracts-gen.js b/packages/contracts-gen/bin/contracts-gen.js deleted file mode 100755 index ec6ab4db6e..0000000000 --- a/packages/contracts-gen/bin/contracts-gen.js +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/env node -require('../lib/src/contracts-gen.js'); diff --git a/packages/contracts-gen/package.json b/packages/contracts-gen/package.json deleted file mode 100644 index 4cb72a740a..0000000000 --- a/packages/contracts-gen/package.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@0x/contracts-gen", - "version": "2.0.10", - "engines": { - "node": ">=6.12" - }, - "description": "Generates boilerplate code for smart contracts packages", - "main": "lib/src/index.js", - "types": "lib/src/index.d.ts", - "scripts": { - "lint": "tslint --format stylish --project .", - "fix": "tslint --fix --format stylish --project .", - "clean": "shx rm -rf lib", - "build": "tsc -b", - "build:ci": "yarn build" - }, - "bin": { - "contracts-gen": "bin/contracts-gen.js" - }, - "repository": { - "type": "git", - "url": "https://github.com/0xProject/0x-monorepo.git" - }, - "license": "Apache-2.0", - "bugs": { - "url": "https://github.com/0xProject/0x-monorepo/issues" - }, - "homepage": "https://github.com/0xProject/0x-monorepo/packages/contracts-gen/README.md", - "dependencies": { - "@0x/sol-compiler": "^4.1.1", - "@0x/sol-resolver": "^3.1.0", - "@0x/types": "^3.2.0", - "@0x/typescript-typings": "^5.1.1", - "@0x/utils": "^5.5.1", - "ethereum-types": "^3.2.0", - "lodash": "^4.17.11", - "mkdirp": "^0.5.1", - "prettier": "^1.16.3", - "to-snake-case": "^1.0.0" - }, - "devDependencies": { - "@0x/tslint-config": "^4.1.0", - "@types/mkdirp": "^0.5.2", - "@types/node": "12.12.54", - "@types/prettier": "^1.15.2", - "shx": "^0.2.2", - "tslint": "5.11.0", - "typescript": "3.0.1" - }, - "publishConfig": { - "access": "public" - }, - "gitHead": "4f91bfd907996b2f4dd383778b50c479c2602b56" -} diff --git a/packages/contracts-gen/src/contracts-gen.ts b/packages/contracts-gen/src/contracts-gen.ts deleted file mode 100644 index 3b73662dfc..0000000000 --- a/packages/contracts-gen/src/contracts-gen.ts +++ /dev/null @@ -1,298 +0,0 @@ -#!/usr/bin/env node - -import { Compiler } from '@0x/sol-compiler'; -import { NameResolver } from '@0x/sol-resolver'; -import { PackageJSON } from '@0x/types'; -import { logUtils } from '@0x/utils'; -import { CompilerOptions } from 'ethereum-types'; -import * as fs from 'fs'; -import * as _ from 'lodash'; -import * as mkdirp from 'mkdirp'; -import * as path from 'path'; -import * as prettier from 'prettier'; -import toSnakeCase = require('to-snake-case'); - -const SOLIDITY_EXTENSION = '.sol'; -const DEFAULT_ARTIFACTS_DIR = 'test/artifacts'; -const DEFAULT_CONTRACTS_DIR = 'contracts'; -const DEFAULT_WRAPPERS_DIR = 'test/generated-wrappers'; -const SRC_ARTIFACTS_TS_FILE_PATH = 'src/artifacts.ts'; -const TEST_ARTIFACTS_TS_FILE_PATH = 'test/artifacts.ts'; -const SRC_WRAPPERS_TS_FILE_PATH = 'src/wrappers.ts'; -const TEST_WRAPPERS_TS_FILE_PATH = 'test/wrappers.ts'; -const AUTO_GENERATED_BANNER = `/* -* ----------------------------------------------------------------------------- -* Warning: This file is auto-generated by contracts-gen. Don't edit manually. -* ----------------------------------------------------------------------------- -*/`; -const AUTO_GENERATED_BANNER_FOR_LISTS = `This list is auto-generated by contracts-gen. Don't edit manually.`; -const ALL_CONTRACTS_IDENTIFIER = '*'; -const GENERATE = 'generate'; -const COPY = 'copy'; - -(async () => { - const command = process.argv.pop(); - if (command !== GENERATE && command !== COPY) { - throw new Error(`Unknown command found: ${command}`); - } - - const compilerJSON = readJSONFile('compiler.json'); - const compiler = new Compiler(compilerJSON); - const testContracts = compiler.getContractNamesToCompile(); - if (!_.isArray(testContracts)) { - throw new Error('Unable to run the generator bacause contracts key in compiler.json is not of type array'); - } - let srcContracts = testContracts; - const packageJSON = readJSONFile('package.json'); - if (packageJSON.config !== undefined && (packageJSON.config as any).publicInterfaceContracts !== undefined) { - srcContracts = (packageJSON.config as any).publicInterfaceContracts.split(','); - } - if (!_.isArray(testContracts)) { - throw new Error('Unable to run the generator bacause contracts key in compiler.json is not of type array'); - } - const testArtifactsDir = compilerJSON.artifactsDir || DEFAULT_ARTIFACTS_DIR; - const srcArtifactsDir = convertToTopLevelDir('testArtifactsDir', testArtifactsDir); - const testWrappersDir = DEFAULT_WRAPPERS_DIR; - const srcWrappersDir = convertToTopLevelDir('testWrappersDir', testWrappersDir); - - // Make sure all dirs exist, if not, create them - mkdirp.sync(testArtifactsDir); - mkdirp.sync(srcArtifactsDir); - mkdirp.sync(testWrappersDir); - mkdirp.sync(srcWrappersDir); - - if (command === GENERATE) { - await regenerateContractPackageAsync( - testContracts, - srcContracts, - testArtifactsDir, - srcArtifactsDir, - testWrappersDir, - srcWrappersDir, - ); - } else if (command === COPY) { - copyOverTestArtifactsAndWrappersToSrc( - srcContracts, - testArtifactsDir, - srcArtifactsDir, - testWrappersDir, - srcWrappersDir, - ); - } - process.exit(0); -})().catch(err => { - logUtils.log(err); - process.exit(1); -}); - -function copyOverTestArtifactsAndWrappersToSrc( - srcContracts: string[], - testArtifactsDir: string, - srcArtifactsDir: string, - testWrappersDir: string, - srcWrappersDir: string, -): void { - // Copy over artifacts - srcContracts.forEach(contract => { - const srcPath = `${srcArtifactsDir}/${contract}.json`; - mkdirp.sync(srcArtifactsDir); - fs.copyFileSync(`${testArtifactsDir}/${contract}.json`, srcPath); - }); - - // Copy over wrappers - srcContracts.forEach(contract => { - const wrapperFileName = makeOutputFileName(contract); - const srcPath = `${srcWrappersDir}/${wrapperFileName}.ts`; - mkdirp.sync(srcWrappersDir); - fs.copyFileSync(`${testWrappersDir}/${wrapperFileName}.ts`, srcPath); - }); -} - -async function regenerateContractPackageAsync( - testContracts: string[], - srcContracts: string[], - testArtifactsDir: string, - srcArtifactsDir: string, - testWrappersDir: string, - srcWrappersDir: string, -): Promise { - const compilerJSON = readJSONFile('compiler.json'); - - const packageDir = process.cwd(); - const testContractsDir = compilerJSON.contractsDir || DEFAULT_CONTRACTS_DIR; - const prettierConfig = await prettier.resolveConfig(packageDir); - generateCompilerJSONContractsList(testContracts, testContractsDir, prettierConfig); - generateArtifactsTs(testContracts, testArtifactsDir, TEST_ARTIFACTS_TS_FILE_PATH, prettierConfig); - generateArtifactsTs(srcContracts, srcArtifactsDir, SRC_ARTIFACTS_TS_FILE_PATH, prettierConfig); - generateWrappersTs(testContracts, testWrappersDir, TEST_WRAPPERS_TS_FILE_PATH, prettierConfig); - generateWrappersTs(srcContracts, srcWrappersDir, SRC_WRAPPERS_TS_FILE_PATH, prettierConfig); - generateTsConfigJSONFilesList(testContracts, testArtifactsDir, srcContracts, srcArtifactsDir, prettierConfig); - generatePackageJSONABIConfig(testContracts, 'abis', testArtifactsDir, prettierConfig); -} - -function convertToTopLevelDir(name: string, aPath: string): string { - let finalPath = aPath; - const hasDotPrefix = aPath.startsWith('./'); - if (hasDotPrefix) { - finalPath = aPath.substr(2); - } - const segments = finalPath.split('/'); - if (segments.length === 0) { - throw new Error(`Cannot have empty path for ${name}`); - } - if (segments.length === 1) { - return aPath; - } - segments.shift(); - return `${hasDotPrefix ? './' : ''}${segments.join('/')}`; -} - -function generateCompilerJSONContractsList( - contracts: string[], - contractsDir: string, - prettierConfig: prettier.Options | null, -): void { - const COMPILER_JSON_FILE_PATH = 'compiler.json'; - const compilerJSON = readJSONFile(COMPILER_JSON_FILE_PATH); - if (compilerJSON.contracts !== undefined && compilerJSON.contracts !== ALL_CONTRACTS_IDENTIFIER) { - compilerJSON.contracts = _.map(contracts, contract => { - if (contract.endsWith(SOLIDITY_EXTENSION)) { - // If it's already a relative path - NO-OP. - return contract; - } else { - // If it's just a contract name - resolve it and rewrite. - return new NameResolver(contractsDir).resolve(contract).path; - } - }); - compilerJSON.contracts = _.sortBy(compilerJSON.contracts); - } - const compilerJSONString = JSON.stringify(compilerJSON); - const formattedCompilerJSON = prettier.format(compilerJSONString, { - ...prettierConfig, - filepath: COMPILER_JSON_FILE_PATH, - }); - fs.writeFileSync(COMPILER_JSON_FILE_PATH, formattedCompilerJSON); -} - -function generateArtifactsTs( - contracts: string[], - artifactsDir: string, - artifactsTsFilePath: string, - prettierConfig: prettier.Options | null, -): void { - const imports = _.map(contracts, contract => { - const contractName = path.basename(contract, SOLIDITY_EXTENSION); - const importPath = path.join('..', artifactsDir, `${contractName}.json`); - return `import * as ${contractName} from '${importPath}';`; - }); - const sortedImports = _.sortBy(imports, _import => _import.toLowerCase()); - const artifacts = _.map(contracts, contract => { - const contractName = path.basename(contract, SOLIDITY_EXTENSION); - if (contractName === 'ZRXToken') { - // HACK(albrow): "as any" hack still required here because ZRXToken does not - // conform to the v2 artifact type. - return `${contractName}: (${contractName} as any) as ContractArtifact,`; - } else { - return `${contractName}: ${contractName} as ContractArtifact,`; - } - }); - const artifactsTs = ` - ${AUTO_GENERATED_BANNER} - import { ContractArtifact } from 'ethereum-types'; - - ${sortedImports.join('\n')} - export const artifacts = {${artifacts.join('\n')}}; - `; - const formattedArtifactsTs = prettier.format(artifactsTs, { ...prettierConfig, filepath: artifactsTsFilePath }); - fs.writeFileSync(artifactsTsFilePath, formattedArtifactsTs); -} - -function generateWrappersTs( - contracts: string[], - wrappersDir: string, - wrappersTsFilePath: string, - prettierConfig: prettier.Options | null, -): void { - const imports = _.map(contracts, contract => { - const contractName = path.basename(contract, SOLIDITY_EXTENSION); - const outputFileName = makeOutputFileName(contractName); - const exportPath = path.join('..', wrappersDir, outputFileName); - return `export * from '${exportPath}';`; - }); - const sortedImports = _.sortBy(imports); - const wrappersTs = ` - ${AUTO_GENERATED_BANNER} - ${sortedImports.join('\n')} - `; - const formattedArtifactsTs = prettier.format(wrappersTs, { ...prettierConfig, filepath: wrappersTsFilePath }); - fs.writeFileSync(wrappersTsFilePath, formattedArtifactsTs); -} - -function generateTsConfigJSONFilesList( - testContracts: string[], - testArtifactsDir: string, - srcContracts: string[], - srcArtifactsDir: string, - prettierConfig: prettier.Options | null, -): void { - const TS_CONFIG_FILE_PATH = 'tsconfig.json'; - const tsConfig = readJSONFile(TS_CONFIG_FILE_PATH); - const testFiles = _.map(testContracts, contract => { - const contractName = path.basename(contract, SOLIDITY_EXTENSION); - const artifactPath = path.join(testArtifactsDir, `${contractName}.json`); - return artifactPath; - }); - const srcFiles = _.map(srcContracts, contract => { - const contractName = path.basename(contract, SOLIDITY_EXTENSION); - const artifactPath = path.join(srcArtifactsDir, `${contractName}.json`); - return artifactPath; - }); - tsConfig.files = [...testFiles, ...srcFiles]; - tsConfig.files = _.sortBy(tsConfig.files); - const tsConfigString = JSON.stringify(tsConfig); - const formattedTsConfig = prettier.format(tsConfigString, { ...prettierConfig, filepath: TS_CONFIG_FILE_PATH }); - fs.writeFileSync(TS_CONFIG_FILE_PATH, formattedTsConfig); -} - -function generatePackageJSONABIConfig( - contracts: string[], - configName: string, - artifactsDir: string, - prettierConfig: prettier.Options | null, -): void { - let packageJSON = readJSONFile('package.json'); - const contractNames = _.map(contracts, contract => { - const contractName = path.basename(contract, SOLIDITY_EXTENSION); - return contractName; - }); - const sortedContractNames = _.sortBy(contractNames); - packageJSON = { - ...packageJSON, - config: { - ...packageJSON.config, - [`${configName}:comment`]: AUTO_GENERATED_BANNER_FOR_LISTS, - [configName]: `${artifactsDir}/@(${sortedContractNames.join('|')}).json`, - }, - }; - const PACKAGE_JSON_FILE_PATH = 'package.json'; - const packageJSONString = JSON.stringify(packageJSON); - const formattedPackageJSON = prettier.format(packageJSONString, { - ...prettierConfig, - filepath: PACKAGE_JSON_FILE_PATH, - }); - fs.writeFileSync(PACKAGE_JSON_FILE_PATH, formattedPackageJSON); -} - -function makeOutputFileName(name: string): string { - let fileName = toSnakeCase(name); - // HACK: Snake case doesn't make a lot of sense for abbreviated names but we can't reliably detect abbreviations - // so we special-case the abbreviations we use. - fileName = fileName.replace('z_r_x', 'zrx').replace('e_r_c', 'erc'); - return fileName; -} - -function readJSONFile(filePath: string): T { - const JSONString = fs.readFileSync(filePath, 'utf8'); - const parsed: T = JSON.parse(JSONString); - return parsed; -} diff --git a/packages/contracts-gen/src/index.ts b/packages/contracts-gen/src/index.ts deleted file mode 100644 index c5f4b01f1e..0000000000 --- a/packages/contracts-gen/src/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * This module is a CLI tool. As soon as you run it - it starts doing stuff. - * At the same time - our installation tests assume that you can import package without causing side effects. - * That's why our main entry point it empty. No side effects. But our secondary entry point - contracts-gen.ts is a CLI tool and starts running as soon as you import/run it. - */ -export {}; diff --git a/packages/contracts-gen/tsconfig.json b/packages/contracts-gen/tsconfig.json deleted file mode 100644 index 233008d61c..0000000000 --- a/packages/contracts-gen/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../tsconfig", - "compilerOptions": { - "outDir": "lib", - "rootDir": "." - }, - "include": ["./src/**/*"] -} diff --git a/packages/contracts-gen/tslint.json b/packages/contracts-gen/tslint.json deleted file mode 100644 index dd9053357e..0000000000 --- a/packages/contracts-gen/tslint.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": ["@0x/tslint-config"] -} diff --git a/packages/dev-utils/.npmignore b/packages/dev-utils/.npmignore deleted file mode 100644 index ea588d4859..0000000000 --- a/packages/dev-utils/.npmignore +++ /dev/null @@ -1,9 +0,0 @@ -# Blacklist all files -.* -* -# Whitelist lib -!lib/**/* -# Blacklist tests and publish scripts -/lib/test/* -/lib/monorepo_scripts/ -# Package specific ignore diff --git a/packages/dev-utils/CHANGELOG.json b/packages/dev-utils/CHANGELOG.json deleted file mode 100644 index 0655236b88..0000000000 --- a/packages/dev-utils/CHANGELOG.json +++ /dev/null @@ -1,764 +0,0 @@ -[ - { - "version": "3.3.0", - "changes": [ - { - "note": "Export `GethCallOverrides` type", - "pr": 2620 - } - ], - "timestamp": 1594788383 - }, - { - "timestamp": 1592969527, - "version": "3.2.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1582623685, - "version": "3.2.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.2.0", - "changes": [ - { - "note": "Refactor into public libraries.", - "pr": 2464 - } - ], - "timestamp": 1581204851 - }, - { - "timestamp": 1580988106, - "version": "3.1.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1580811564, - "version": "3.1.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.1.1", - "changes": [ - { - "note": "Set default `hardfork` option for ganache provider to `\"istanbul\"`", - "pr": 2432 - } - ], - "timestamp": 1579682890 - }, - { - "version": "3.1.0", - "changes": [ - { - "note": "Add `locked` `Web3Config` option.", - "pr": 2407 - } - ], - "timestamp": 1578272714 - }, - { - "timestamp": 1576540892, - "version": "3.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1575931811, - "version": "3.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.0.0", - "changes": [ - { - "note": "`revertWith` mocha extensions now accept Promise-like objects instead of just Promises", - "pr": 2031 - }, - { - "note": "Add `shouldAllowUnlimitedContractSize` to `Web3Config`.", - "pr": 2075 - }, - { - "note": "Add `UNLIMITED_CONTRACT_SIZE` to `EnvVars`.", - "pr": 2075 - }, - { - "note": "Add `total_accounts` option to `Web3Config`.", - "pr": 2109 - }, - { - "note": "Add `chaiSetup` function with `RevertError` testing support", - "pr": 1761 - }, - { - "note": "Refactor out `Error` coercion code into the `utils` package", - "pr": 1819 - } - ], - "timestamp": 1575296764 - }, - { - "version": "2.4.0-beta.4", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1575290197 - }, - { - "version": "2.4.0-beta.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1574238768 - }, - { - "version": "2.4.0-beta.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1574030254 - }, - { - "version": "2.4.0-beta.1", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1573159180 - }, - { - "version": "2.4.0-beta.0", - "changes": [ - { - "note": "`revertWith` mocha extensions now accept Promise-like objects instead of just Promises", - "pr": 2031 - }, - { - "note": "Add `shouldAllowUnlimitedContractSize` to `Web3Config`.", - "pr": 2075 - }, - { - "note": "Add `UNLIMITED_CONTRACT_SIZE` to `EnvVars`.", - "pr": 2075 - }, - { - "note": "Add `total_accounts` option to `Web3Config`.", - "pr": 2109 - }, - { - "note": "Add `chaiSetup` function with `RevertError` testing support", - "pr": 1761 - }, - { - "note": "Refactor out `Error` coercion code into the `utils` package", - "pr": 1819 - } - ], - "timestamp": 1570135330 - }, - { - "timestamp": 1568744790, - "version": "2.3.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1567521715, - "version": "2.3.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1566446343, - "version": "2.3.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.3.0", - "changes": [ - { - "note": "Move `tokenUtils` here from `@0x/contract-wrappers`", - "pr": 2037 - } - ], - "timestamp": 1565296576 - }, - { - "timestamp": 1564604963, - "version": "2.2.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563957393, - "version": "2.2.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563006338, - "version": "2.2.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1558712885, - "version": "2.2.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1557507213, - "version": "2.2.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.2.1", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1554997931 - }, - { - "version": "2.2.0", - "changes": [ - { - "note": "Added `startProviderEngine` to `providerUtils`. Preventing excess block polling", - "pr": 1695 - } - ], - "timestamp": 1553183790 - }, - { - "timestamp": 1553091633, - "version": "2.1.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551479279, - "version": "2.1.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551220833, - "version": "2.1.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551130135, - "version": "2.1.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.1.0", - "changes": [ - { - "note": "Allow using the Web3Factory in-process Ganache provider with existing DB snapshot", - "pr": 1602 - } - ], - "timestamp": 1549733923 - }, - { - "version": "2.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1549547375 - }, - { - "timestamp": 1549452781, - "version": "2.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.0", - "changes": [ - { - "note": "Upgrade the bignumber.js to v8.0.2", - "pr": 1517 - } - ], - "timestamp": 1549373905 - }, - { - "timestamp": 1547561734, - "version": "1.0.24", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547225310, - "version": "1.0.23", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547040760, - "version": "1.0.22", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.21", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544739608 - }, - { - "version": "1.0.20", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544570656 - }, - { - "timestamp": 1543401373, - "version": "1.0.19", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542821676, - "version": "1.0.18", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542208198, - "version": "1.0.17", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542134075, - "version": "1.0.16", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542028948, - "version": "1.0.15", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.14", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1541740904 - }, - { - "version": "1.0.13", - "changes": [ - { - "note": "Make web3-provider-engine types a 'dependency' so it's available to users of the library", - "pr": 1105 - } - ], - "timestamp": 1539871071 - }, - { - "version": "1.0.12", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1538693146 - }, - { - "timestamp": 1538157789, - "version": "1.0.11", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537907159, - "version": "1.0.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537875740, - "version": "1.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537541580, - "version": "1.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1536142250, - "version": "1.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1535377027, - "version": "1.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1535133899, - "version": "1.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1534210131, - "version": "1.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1532619515 - }, - { - "timestamp": 1532605697, - "version": "1.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532357734, - "version": "1.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532043000, - "version": "1.0.0", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1531919263, - "version": "0.4.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1531149657, - "version": "0.4.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1529397769, - "version": "0.4.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.4.3", - "changes": [ - { - "note": "Add optional parameter shouldUseFakeGasEstimate to Web3Config", - "pr": 622 - }, - { - "note": "Add SolidityProfiler to EnvVars", - "pr": 675 - } - ], - "timestamp": 1527008544 - }, - { - "version": "0.4.2", - "changes": [ - { - "note": "Pass SolCompilerArtifactAdapter to CoverageSubprovider", - "pr": 589 - }, - { - "note": "Move callbackErrorReporter over from 0x.js", - "pr": 579 - } - ], - "timestamp": 1527008544 - }, - { - "timestamp": 1525477860, - "version": "0.4.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.4.0", - "changes": [ - { - "note": "Update web3 provider engine to 14.0.4", - "pr": 555 - } - ], - "timestamp": 1525428773 - }, - { - "version": "0.3.6", - "changes": [ - { - "note": "Allow an rpcURL to be set in Web3Config (for testnet RPC endpoints)", - "pr": 524 - } - ], - "timestamp": 1524044013 - }, - { - "timestamp": 1523462196, - "version": "0.3.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1522673609, - "version": "0.3.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1522658513, - "version": "0.3.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.3.1", - "changes": [ - { - "note": "Reduce npm package size by adding an `.npmignore` file." - }, - { - "note": "Move `@0xproject/web3-wrapper` to dependencies from devDependencies." - } - ], - "timestamp": 1521298800 - }, - { - "version": "0.3.0", - "changes": [ - { - "note": "Add coverage subprovider if SOLIDITY_COVERAGE env variable is true", - "pr": 426 - }, - { - "note": "Refactor `BlockchainLifecycle` to work with in-process ganache", - "pr": 426 - }, - { - "note": "Remove `RPC` class and move it's logic to `Web3Wrapper`", - "pr": 426 - } - ], - "timestamp": 1521298800 - }, - { - "version": "0.2.0", - "changes": [ - { - "note": "Remove subproviders", - "pr": 392 - } - ], - "timestamp": 1518706800 - }, - { - "version": "0.0.12", - "changes": [ - { - "note": "Fix publishing issue where .npmignore was not properly excluding undesired content", - "pr": 389 - } - ], - "timestamp": 1518102000 - }, - { - "version": "0.0.11", - "changes": [ - { - "note": "Updated `types-ethereumjs-util` dev dependency", - "pr": 352 - } - ], - "timestamp": 1517929200 - } -] diff --git a/packages/dev-utils/CHANGELOG.md b/packages/dev-utils/CHANGELOG.md deleted file mode 100644 index e13b05d3e8..0000000000 --- a/packages/dev-utils/CHANGELOG.md +++ /dev/null @@ -1,325 +0,0 @@ - - -CHANGELOG - -## v3.3.0 - _July 15, 2020_ - - * Export `GethCallOverrides` type (#2620) - -## v3.2.2 - _June 24, 2020_ - - * Dependencies updated - -## v3.2.1 - _February 25, 2020_ - - * Dependencies updated - -## v3.2.0 - _February 8, 2020_ - - * Refactor into public libraries. (#2464) - -## v3.1.3 - _February 6, 2020_ - - * Dependencies updated - -## v3.1.2 - _February 4, 2020_ - - * Dependencies updated - -## v3.1.1 - _January 22, 2020_ - - * Set default `hardfork` option for ganache provider to `"istanbul"` (#2432) - -## v3.1.0 - _January 6, 2020_ - - * Add `locked` `Web3Config` option. (#2407) - -## v3.0.2 - _December 17, 2019_ - - * Dependencies updated - -## v3.0.1 - _December 9, 2019_ - - * Dependencies updated - -## v3.0.0 - _December 2, 2019_ - - * `revertWith` mocha extensions now accept Promise-like objects instead of just Promises (#2031) - * Add `shouldAllowUnlimitedContractSize` to `Web3Config`. (#2075) - * Add `UNLIMITED_CONTRACT_SIZE` to `EnvVars`. (#2075) - * Add `total_accounts` option to `Web3Config`. (#2109) - * Add `chaiSetup` function with `RevertError` testing support (#1761) - * Refactor out `Error` coercion code into the `utils` package (#1819) - -## v2.4.0-beta.4 - _December 2, 2019_ - - * Dependencies updated - -## v2.4.0-beta.3 - _November 20, 2019_ - - * Dependencies updated - -## v2.4.0-beta.2 - _November 17, 2019_ - - * Dependencies updated - -## v2.4.0-beta.1 - _November 7, 2019_ - - * Dependencies updated - -## v2.4.0-beta.0 - _October 3, 2019_ - - * `revertWith` mocha extensions now accept Promise-like objects instead of just Promises (#2031) - * Add `shouldAllowUnlimitedContractSize` to `Web3Config`. (#2075) - * Add `UNLIMITED_CONTRACT_SIZE` to `EnvVars`. (#2075) - * Add `total_accounts` option to `Web3Config`. (#2109) - * Add `chaiSetup` function with `RevertError` testing support (#1761) - * Refactor out `Error` coercion code into the `utils` package (#1819) - -## v2.3.3 - _September 17, 2019_ - - * Dependencies updated - -## v2.3.2 - _September 3, 2019_ - - * Dependencies updated - -## v2.3.1 - _August 22, 2019_ - - * Dependencies updated - -## v2.3.0 - _August 8, 2019_ - - * Move `tokenUtils` here from `@0x/contract-wrappers` (#2037) - -## v2.2.6 - _July 31, 2019_ - - * Dependencies updated - -## v2.2.5 - _July 24, 2019_ - - * Dependencies updated - -## v2.2.4 - _July 13, 2019_ - - * Dependencies updated - -## v2.2.3 - _May 24, 2019_ - - * Dependencies updated - -## v2.2.2 - _May 10, 2019_ - - * Dependencies updated - -## v2.2.1 - _April 11, 2019_ - - * Dependencies updated - -## v2.2.0 - _March 21, 2019_ - - * Added `startProviderEngine` to `providerUtils`. Preventing excess block polling (#1695) - -## v2.1.4 - _March 20, 2019_ - - * Dependencies updated - -## v2.1.3 - _March 1, 2019_ - - * Dependencies updated - -## v2.1.2 - _February 26, 2019_ - - * Dependencies updated - -## v2.1.1 - _February 25, 2019_ - - * Dependencies updated - -## v2.1.0 - _February 9, 2019_ - - * Allow using the Web3Factory in-process Ganache provider with existing DB snapshot (#1602) - -## v2.0.2 - _February 7, 2019_ - - * Dependencies updated - -## v2.0.1 - _February 6, 2019_ - - * Dependencies updated - -## v2.0.0 - _February 5, 2019_ - - * Upgrade the bignumber.js to v8.0.2 (#1517) - -## v1.0.24 - _January 15, 2019_ - - * Dependencies updated - -## v1.0.23 - _January 11, 2019_ - - * Dependencies updated - -## v1.0.22 - _January 9, 2019_ - - * Dependencies updated - -## v1.0.21 - _December 13, 2018_ - - * Dependencies updated - -## v1.0.20 - _December 11, 2018_ - - * Dependencies updated - -## v1.0.19 - _November 28, 2018_ - - * Dependencies updated - -## v1.0.18 - _November 21, 2018_ - - * Dependencies updated - -## v1.0.17 - _November 14, 2018_ - - * Dependencies updated - -## v1.0.16 - _November 13, 2018_ - - * Dependencies updated - -## v1.0.15 - _November 12, 2018_ - - * Dependencies updated - -## v1.0.14 - _November 9, 2018_ - - * Dependencies updated - -## v1.0.13 - _October 18, 2018_ - - * Make web3-provider-engine types a 'dependency' so it's available to users of the library (#1105) - -## v1.0.12 - _October 4, 2018_ - - * Dependencies updated - -## v1.0.11 - _September 28, 2018_ - - * Dependencies updated - -## v1.0.10 - _September 25, 2018_ - - * Dependencies updated - -## v1.0.9 - _September 25, 2018_ - - * Dependencies updated - -## v1.0.8 - _September 21, 2018_ - - * Dependencies updated - -## v1.0.7 - _September 5, 2018_ - - * Dependencies updated - -## v1.0.6 - _August 27, 2018_ - - * Dependencies updated - -## v1.0.5 - _August 24, 2018_ - - * Dependencies updated - -## v1.0.4 - _August 14, 2018_ - - * Dependencies updated - -## v1.0.3 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.2 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.1 - _July 23, 2018_ - - * Dependencies updated - -## v1.0.0 - _July 19, 2018_ - - * Dependencies updated - -## v0.4.6 - _July 18, 2018_ - - * Dependencies updated - -## v0.4.5 - _July 9, 2018_ - - * Dependencies updated - -## v0.4.4 - _June 19, 2018_ - - * Dependencies updated - -## v0.4.3 - _May 22, 2018_ - - * Add optional parameter shouldUseFakeGasEstimate to Web3Config (#622) - * Add SolidityProfiler to EnvVars (#675) - -## v0.4.2 - _May 22, 2018_ - - * Pass SolCompilerArtifactAdapter to CoverageSubprovider (#589) - * Move callbackErrorReporter over from 0x.js (#579) - -## v0.4.1 - _May 4, 2018_ - - * Dependencies updated - -## v0.4.0 - _May 4, 2018_ - - * Update web3 provider engine to 14.0.4 (#555) - -## v0.3.6 - _April 18, 2018_ - - * Allow an rpcURL to be set in Web3Config (for testnet RPC endpoints) (#524) - -## v0.3.5 - _April 11, 2018_ - - * Dependencies updated - -## v0.3.4 - _April 2, 2018_ - - * Dependencies updated - -## v0.3.3 - _April 2, 2018_ - - * Dependencies updated - -## v0.3.1 - _March 17, 2018_ - - * Reduce npm package size by adding an `.npmignore` file. - * Move `@0xproject/web3-wrapper` to dependencies from devDependencies. - -## v0.3.0 - _March 17, 2018_ - - * Add coverage subprovider if SOLIDITY_COVERAGE env variable is true (#426) - * Refactor `BlockchainLifecycle` to work with in-process ganache (#426) - * Remove `RPC` class and move it's logic to `Web3Wrapper` (#426) - -## v0.2.0 - _February 15, 2018_ - - * Remove subproviders (#392) - -## v0.0.12 - _February 8, 2018_ - - * Fix publishing issue where .npmignore was not properly excluding undesired content (#389) - -## v0.0.11 - _February 6, 2018_ - - * Updated `types-ethereumjs-util` dev dependency (#352) diff --git a/packages/dev-utils/README.md b/packages/dev-utils/README.md deleted file mode 100644 index b85159dd83..0000000000 --- a/packages/dev-utils/README.md +++ /dev/null @@ -1,95 +0,0 @@ -## Dev utils - -Dev utils to be shared across 0x projects and packages - -## Configuration - -Some env variables might be set to change the behaviour of created web3 providers/instances. - -``` -VERBOSE_GANACHE: boolean. Enables verbose Ganache logging. Every request/response payload. Slightly slower, but useful for testing. -SOLIDITY_COVERAGE: boolean. If set - adds coverage subprovider which intercepts all calls/transactions and can be later used to compute code coverage. -``` - -Boolean env variables should be either `true` or `false`. Defaults to `false` if not set. - -## Install - -```bash -yarn add @0x/dev-utils -``` - -If your project is in [TypeScript](https://www.typescriptlang.org/), add the following to your `tsconfig.json`: - -```json -"compilerOptions": { - "typeRoots": ["node_modules/@0x/typescript-typings/types", "node_modules/@types"], -} -``` - -## Troubleshooting - -If you are still seeing TS type errors complaining about missing DOM types such as `Response`: - -``` -error TS2304: Cannot find name 'Response'. -``` - -Then you need to explicitly add the `dom` lib to your compiler options in `tsconfig.json`. The `dom` library is included by default, but customizing the `lib` option can cause it to be dropped. - -``` -"compilerOptions": { - "lib": [..., "dom"], -``` - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install dependencies - -If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: - -```bash -yarn config set workspaces-experimental true -``` - -Then install dependencies - -```bash -yarn install -``` - -### Build - -To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory: - -```bash -PKG=@0x/dev-utils yarn build -``` - -Or continuously rebuild on change: - -```bash -PKG=@0x/dev-utils yarn watch -``` - -### Clean - -```bash -yarn clean -``` - -### Lint - -```bash -yarn lint -``` - -### Run Tests - -```bash -yarn test -``` diff --git a/packages/dev-utils/coverage/.gitkeep b/packages/dev-utils/coverage/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/dev-utils/package.json b/packages/dev-utils/package.json deleted file mode 100644 index 66346f282e..0000000000 --- a/packages/dev-utils/package.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "name": "@0x/dev-utils", - "version": "3.3.0", - "engines": { - "node": ">=6.12" - }, - "description": "0x dev TS utils", - "main": "lib/src/index.js", - "types": "lib/src/index.d.ts", - "scripts": { - "build": "tsc -b", - "build:ci": "yarn build", - "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", - "lint": "tslint --format stylish --project .", - "fix": "tslint --format stylish --fix --project .", - "docs:md": "ts-doc-gen --sourceDir='$PROJECT_FILES' --output=$MD_FILE_DIR --fileExtension=mdx --tsconfig=./typedoc-tsconfig.json", - "docs:json": "typedoc --excludePrivate --excludeExternals --excludeProtected --ignoreCompilerErrors --target ES5 --tsconfig typedoc-tsconfig.json --json $JSON_FILE_PATH $PROJECT_FILES" - }, - "license": "Apache-2.0", - "repository": { - "type": "git", - "url": "https://github.com/0xProject/0x-monorepo.git" - }, - "bugs": { - "url": "https://github.com/0xProject/0x-monorepo/issues" - }, - "homepage": "https://github.com/0xProject/0x-monorepo/packages/dev-utils/README.md", - "devDependencies": { - "@0x/ts-doc-gen": "^0.0.22", - "@0x/tslint-config": "^4.1.0", - "@types/lodash": "4.14.104", - "@types/mocha": "^5.2.7", - "make-promises-safe": "^1.1.0", - "mocha": "^6.2.0", - "npm-run-all": "^4.1.2", - "nyc": "^11.0.1", - "shx": "^0.2.2", - "tslint": "5.11.0", - "typedoc": "^0.15.0", - "typescript": "3.0.1" - }, - "dependencies": { - "@0x/subproviders": "^6.1.1", - "@0x/types": "^3.2.0", - "@0x/typescript-typings": "^5.1.1", - "@0x/utils": "^5.5.1", - "@0x/web3-wrapper": "^7.2.0", - "@types/web3-provider-engine": "^14.0.0", - "chai": "^4.0.1", - "chai-as-promised": "^7.1.0", - "chai-bignumber": "^3.0.0", - "dirty-chai": "^2.0.1", - "ethereum-types": "^3.2.0", - "lodash": "^4.17.11", - "web3-provider-engine": "14.0.6" - }, - "publishConfig": { - "access": "public" - }, - "gitHead": "4f91bfd907996b2f4dd383778b50c479c2602b56" -} diff --git a/packages/dev-utils/src/blockchain_lifecycle.ts b/packages/dev-utils/src/blockchain_lifecycle.ts deleted file mode 100644 index 600f8b36bc..0000000000 --- a/packages/dev-utils/src/blockchain_lifecycle.ts +++ /dev/null @@ -1,98 +0,0 @@ -import { logUtils } from '@0x/utils'; -import { NodeType, Web3Wrapper } from '@0x/web3-wrapper'; -import * as _ from 'lodash'; - -// HACK(albrow): 🐉 We have to do this so that debug.setHead works correctly. -// (Geth does not seem to like debug.setHead(0), so by sending some transactions -// we increase the current block number beyond 0). Additionally, some tests seem -// to break when there are fewer than 3 blocks in the chain. (We have no idea -// why, but it was consistently reproducible). -const MINIMUM_BLOCKS = 3; - -export class BlockchainLifecycle { - private readonly _web3Wrapper: Web3Wrapper; - private readonly _snapshotIdsStack: number[]; - private _addresses: string[] = []; - private _nodeType: NodeType | undefined; - constructor(web3Wrapper: Web3Wrapper) { - this._web3Wrapper = web3Wrapper; - this._snapshotIdsStack = []; - } - public async startAsync(): Promise { - const nodeType = await this._getNodeTypeAsync(); - switch (nodeType) { - case NodeType.Ganache: - const snapshotId = await this._web3Wrapper.takeSnapshotAsync(); - this._snapshotIdsStack.push(snapshotId); - break; - case NodeType.Geth: - let blockNumber = await this._web3Wrapper.getBlockNumberAsync(); - if (blockNumber < MINIMUM_BLOCKS) { - // If the minimum block number is not met, force Geth to - // mine some blocks by sending some dummy transactions. - await this._mineMinimumBlocksAsync(); - blockNumber = await this._web3Wrapper.getBlockNumberAsync(); - } - this._snapshotIdsStack.push(blockNumber); - // HACK(albrow) It's possible that we applied a time offset but - // the transaction we mined to put that time offset into the - // blockchain was reverted. As a workaround, we mine a new dummy - // block so that the latest block timestamp accounts for any - // possible time offsets. - await this._mineDummyBlockAsync(); - break; - default: - throw new Error(`Unknown node type: ${nodeType}`); - } - } - public async revertAsync(): Promise { - const nodeType = await this._getNodeTypeAsync(); - switch (nodeType) { - case NodeType.Ganache: - const snapshotId = this._snapshotIdsStack.pop() as number; - const didRevert = await this._web3Wrapper.revertSnapshotAsync(snapshotId); - if (!didRevert) { - throw new Error(`Snapshot with id #${snapshotId} failed to revert`); - } - break; - case NodeType.Geth: - const blockNumber = this._snapshotIdsStack.pop() as number; - await this._web3Wrapper.setHeadAsync(blockNumber); - break; - default: - throw new Error(`Unknown node type: ${nodeType}`); - } - } - private async _mineMinimumBlocksAsync(): Promise { - logUtils.warn('WARNING: minimum block number for tests not met. Mining additional blocks...'); - while ((await this._web3Wrapper.getBlockNumberAsync()) < MINIMUM_BLOCKS) { - logUtils.warn('Mining block...'); - await this._mineDummyBlockAsync(); - } - logUtils.warn('Done mining the minimum number of blocks.'); - } - private async _getNodeTypeAsync(): Promise { - if (this._nodeType === undefined) { - this._nodeType = await this._web3Wrapper.getNodeTypeAsync(); - } - return this._nodeType; - } - // Sends a transaction that has no real effect on the state and waits for it - // to be mined. - private async _mineDummyBlockAsync(): Promise { - if (this._addresses.length === 0) { - this._addresses = await this._web3Wrapper.getAvailableAddressesAsync(); - if (this._addresses.length === 0) { - throw new Error('No accounts found'); - } - } - await this._web3Wrapper.awaitTransactionMinedAsync( - await this._web3Wrapper.sendTransactionAsync({ - from: this._addresses[0], - to: this._addresses[0], - value: '0', - }), - 0, - ); - } -} diff --git a/packages/dev-utils/src/callback_error_reporter.ts b/packages/dev-utils/src/callback_error_reporter.ts deleted file mode 100644 index 251ab05095..0000000000 --- a/packages/dev-utils/src/callback_error_reporter.ts +++ /dev/null @@ -1,77 +0,0 @@ -import * as chai from 'chai'; -import * as _ from 'lodash'; - -import { DoneCallback } from '@0x/types'; - -const expect = chai.expect; - -export const callbackErrorReporter = { - reportNoErrorCallbackErrors( - done: DoneCallback, - expectToBeCalledOnce: boolean = true, - ): (f?: ((value: T) => void) | undefined) => (value: T) => void { - const callback = (f?: (value: T) => void) => { - const wrapped = (value: T) => { - if (f === undefined) { - done(); - return; - } - try { - f(value); - if (expectToBeCalledOnce) { - done(); - } - } catch (err) { - done(err); - } - }; - return wrapped; - }; - return callback; - }, - reportNodeCallbackErrors( - done: DoneCallback, - expectToBeCalledOnce: boolean = true, - ): (f?: ((value: T) => void) | undefined) => (error: Error | null, value: T | undefined) => void { - const callback = (f?: (value: T) => void) => { - const wrapped = (error: Error | null, value: T | undefined) => { - if (error !== null) { - done(error); - } else { - if (f === undefined) { - done(); - return; - } - try { - f(value as T); - if (expectToBeCalledOnce) { - done(); - } - } catch (err) { - done(err); - } - } - }; - return wrapped; - }; - return callback; - }, - assertNodeCallbackError( - done: DoneCallback, - errMsg: string, - ): (error: Error | null, value: T | undefined) => void { - const wrapped = (error: Error | null, _value: T | undefined) => { - if (error === null) { - done(new Error('Expected callback to receive an error')); - } else { - try { - expect(error.message).to.be.equal(errMsg); - done(); - } catch (err) { - done(err); - } - } - }; - return wrapped; - }, -}; diff --git a/packages/dev-utils/src/chai_revert_error.ts b/packages/dev-utils/src/chai_revert_error.ts deleted file mode 100644 index a470ae3970..0000000000 --- a/packages/dev-utils/src/chai_revert_error.ts +++ /dev/null @@ -1,142 +0,0 @@ -import { coerceThrownErrorAsRevertError, RevertError, StringRevertError } from '@0x/utils'; - -// tslint:disable only-arrow-functions prefer-conditional-expression - -type ChaiPromiseHandler = (x: any, ...rest: any[]) => Promise; -type ChaiAssertHandler = (x: any, ...rest: any[]) => void; - -interface Chai { - Assertion: ChaiAssertionType; -} - -interface ChaiAssertionInstance { - assert: ChaiAssert; - _obj: any; - __flags: any; -} - -interface ChaiAssertionType { - overwriteMethod: (name: string, _super: (expected: any) => any) => void; - new (): ChaiAssertionInstance; -} - -type ChaiAssert = ( - condition: boolean, - failMessage?: string, - negatedFailMessage?: string, - expected?: any, - actual?: any, -) => void; - -export function revertErrorHelper(_chai: Chai): void { - const proto = _chai.Assertion; - proto.overwriteMethod('revertWith', function(_super: ChaiPromiseHandler): ChaiPromiseHandler { - return async function(this: ChaiAssertionInstance, expected: any, ...rest: any[]): Promise { - const maybePromise = this._obj; - // Make sure we're working with a promise. - assertIsPromiseLike(_chai, maybePromise); - // Wait for the promise to reject. - let resolveValue; - let rejectValue: any; - let didReject = false; - try { - resolveValue = await maybePromise; - } catch (err) { - rejectValue = err; - didReject = true; - } - if (!didReject) { - chaiFail(_chai, `Expected promise to reject but instead resolved with: ${resolveValue}`); - } - if (!compareRevertErrors.call(this, _chai, rejectValue, expected, true)) { - // Wasn't handled by the comparison function so call the previous handler. - _super.call(this, expected, ...rest); - } - }; - }); - proto.overwriteMethod('become', function(_super: ChaiPromiseHandler): ChaiPromiseHandler { - return async function(this: ChaiAssertionInstance, expected: any, ...rest: any[]): Promise { - const maybePromise = this._obj; - // Make sure we're working with a promise. - assertIsPromiseLike(_chai, maybePromise); - // Wait for the promise to resolve. - if (!compareRevertErrors.call(this, _chai, await maybePromise, expected)) { - // Wasn't handled by the comparison function so call the previous handler. - _super.call(this, expected, ...rest); - } - }; - }); - proto.overwriteMethod('equal', function(_super: ChaiAssertHandler): ChaiAssertHandler { - return function(this: ChaiAssertionInstance, expected: any, ...rest: any[]): void { - if (!compareRevertErrors.call(this, _chai, this._obj, expected)) { - // Wasn't handled by the comparison function so call the previous handler. - _super.call(this, expected, ...rest); - } - }; - }); -} - -/** - * Compare two values as compatible RevertError types. - * @return `true` if the comparison was fully evaluated. `false` indicates that - * it should be deferred to another handler. - */ -function compareRevertErrors( - this: ChaiAssertionInstance, - _chai: Chai, - _actual: any, - _expected: any, - force?: boolean, -): boolean { - let actual = _actual; - let expected = _expected; - // If either subject is a RevertError, or the `force` is `true`, - // try to coerce the subjects into a RevertError. - // Some of this is for convenience, some is for backwards-compatibility. - if (force || expected instanceof RevertError || actual instanceof RevertError) { - // `actual` can be a RevertError, string, or an Error type. - if (!(actual instanceof RevertError)) { - if (typeof actual === 'string') { - actual = new StringRevertError(actual); - } else if (actual instanceof Error) { - actual = coerceThrownErrorAsRevertError(actual); - } else { - chaiAssert(_chai, false, `Result is not of type RevertError: ${actual}`); - } - } - // `expected` can be a RevertError or string. - if (typeof expected === 'string') { - expected = new StringRevertError(expected); - } - } - if (expected instanceof RevertError && actual instanceof RevertError) { - // Check for equality. - this.assert( - expected.equals(actual), - `${actual.toString()} != ${expected.toString()}`, - `${actual.toString()} == ${expected.toString()}`, - expected.toString(), - actual.toString(), - ); - // Return true to signal we handled it. - return true; - } - return false; -} - -function chaiAssert(_chai: Chai, condition: boolean, failMessage?: string, expected?: any, actual?: any): void { - const assert = new _chai.Assertion(); - assert.assert(condition, failMessage, undefined, expected, actual); -} - -function chaiFail(_chai: Chai, failMessage?: string, expected?: any, actual?: any): void { - const assert = new _chai.Assertion(); - assert.assert(false, failMessage, undefined, expected, actual); -} - -function assertIsPromiseLike(_chai: Chai, maybePromise: any): void { - if (maybePromise.then instanceof Function && maybePromise.catch instanceof Function) { - return; - } - chaiFail(_chai, `Expected ${maybePromise} to be a promise`, Promise.resolve(), maybePromise); -} diff --git a/packages/dev-utils/src/chai_setup.ts b/packages/dev-utils/src/chai_setup.ts deleted file mode 100644 index a3c3f98410..0000000000 --- a/packages/dev-utils/src/chai_setup.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { RevertError } from '@0x/utils'; -import * as chai from 'chai'; -import chaiAsPromised = require('chai-as-promised'); -import ChaiBigNumber = require('chai-bignumber'); -import * as dirtyChai from 'dirty-chai'; - -import { revertErrorHelper } from './chai_revert_error'; - -declare global { - namespace Chai { - export interface Assertion { - revertWith: (expected: string | RevertError) => Promise; - } - } -} - -export const chaiSetup = { - configure(): void { - chai.config.includeStack = true; - // Order matters. - chai.use(ChaiBigNumber()); - chai.use(chaiAsPromised); - chai.use(revertErrorHelper); - chai.use(dirtyChai); - }, -}; diff --git a/packages/dev-utils/src/constants.ts b/packages/dev-utils/src/constants.ts deleted file mode 100644 index 4c7dae589a..0000000000 --- a/packages/dev-utils/src/constants.ts +++ /dev/null @@ -1,6 +0,0 @@ -export const constants = { - RPC_URL: 'http://localhost:8545', - RPC_PORT: 8545, - GAS_LIMIT: 9e6, - TESTRPC_FIRST_ADDRESS: '0x5409ed021d9299bf6814279a6a1411a7e866a631', -}; diff --git a/packages/dev-utils/src/env.ts b/packages/dev-utils/src/env.ts deleted file mode 100644 index 50597c7495..0000000000 --- a/packages/dev-utils/src/env.ts +++ /dev/null @@ -1,27 +0,0 @@ -import * as _ from 'lodash'; -import * as process from 'process'; - -export enum EnvVars { - SolidityCoverage = 'SOLIDITY_COVERAGE', - SolidityProfiler = 'SOLIDITY_PROFILER', - SolidityRevertTrace = 'SOLIDITY_REVERT_TRACE', - VerboseGanache = 'VERBOSE_GANACHE', - UnlimitedContractSize = 'UNLIMITED_CONTRACT_SIZE', -} - -export const env = { - parseBoolean(key: string): boolean { - let isTrue: boolean; - const envVarValue = process.env[key]; - if (envVarValue === 'true') { - isTrue = true; - } else if (envVarValue === 'false' || envVarValue === undefined) { - isTrue = false; - } else { - throw new Error( - `Failed to parse ENV variable ${key} as boolean. Please make sure it's either true or false. Defaults to false`, - ); - } - return isTrue; - }, -}; diff --git a/packages/dev-utils/src/globals.d.ts b/packages/dev-utils/src/globals.d.ts deleted file mode 100644 index 94e63a32de..0000000000 --- a/packages/dev-utils/src/globals.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -declare module '*.json' { - const json: any; - /* tslint:disable */ - export default json; - /* tslint:enable */ -} diff --git a/packages/dev-utils/src/index.ts b/packages/dev-utils/src/index.ts deleted file mode 100644 index 7975d5499c..0000000000 --- a/packages/dev-utils/src/index.ts +++ /dev/null @@ -1,64 +0,0 @@ -export { BlockchainLifecycle } from './blockchain_lifecycle'; -export { web3Factory, Web3Config } from './web3_factory'; -export { constants as devConstants } from './constants'; -export { env, EnvVars } from './env'; -export { callbackErrorReporter } from './callback_error_reporter'; -export { chaiSetup } from './chai_setup'; -export { tokenUtils } from './token_utils'; -export { Web3Wrapper, NodeType } from '@0x/web3-wrapper'; -export import Web3ProviderEngine = require('web3-provider-engine'); -export { DoneCallback } from '@0x/types'; -export { AbiDecoder, DecodedCalldata } from '@0x/utils'; -export { - SupportedProvider, - CallData, - GethCallOverrides, - TransactionReceiptWithDecodedLogs, - BlockParam, - TxData, - BlockWithoutTransactionData, - BlockWithTransactionData, - FilterObject, - LogEntry, - Transaction, - TransactionReceipt, - TraceParams, - TransactionTrace, - JSONRPCRequestPayload, - LogTopic, - DecodedLogEntry, - LogEntryEvent, - TransactionReceiptStatus, - StructLog, - TxDataPayable, - BlockParamLiteral, - Web3JsProvider, - GanacheProvider, - EIP1193Provider, - ZeroExProvider, - AbiDefinition, - DecodedLogArgs, - LogWithDecodedArgs, - RawLog, - ContractEventArg, - DecodedLogEntryEvent, - EIP1193Event, - JSONRPCErrorCallback, - OpCode, - FunctionAbi, - EventAbi, - RevertErrorAbi, - Web3JsV1Provider, - Web3JsV2Provider, - Web3JsV3Provider, - EventParameter, - DataItem, - JSONRPCResponsePayload, - MethodAbi, - ConstructorAbi, - FallbackAbi, - ConstructorStateMutability, - TupleDataItem, - JSONRPCResponseError, - StateMutability, -} from 'ethereum-types'; diff --git a/packages/dev-utils/src/token_utils.ts b/packages/dev-utils/src/token_utils.ts deleted file mode 100644 index 1d4ee6b2ca..0000000000 --- a/packages/dev-utils/src/token_utils.ts +++ /dev/null @@ -1,21 +0,0 @@ -// Those addresses come from migrations. They're deterministic so it's relatively safe to hard-code them here. -// Before we were fetching them from the TokenRegistry but now we can't as it's deprecated and removed. -// TODO(albrow): Import these from the migrations package instead of hard-coding them. -const DUMMY_ERC_20_ADRESSES = [ - '0x34d402f14d58e001d8efbe6585051bf9706aa064', - '0x25b8fe1de9daf8ba351890744ff28cf7dfa8f5e3', - '0xcdb594a32b1cc3479d8746279712c39d18a07fc0', - '0x1e2f9e10d02a6b8f8f69fcbf515e75039d2ea30d', - '0xbe0037eaf2d64fe5529bca93c18c9702d3930376', -]; - -const DUMMY_ERC_721_ADRESSES = ['0x07f96aa816c1f244cbc6ef114bb2b023ba54a2eb']; - -export const tokenUtils = { - getDummyERC20TokenAddresses(): string[] { - return DUMMY_ERC_20_ADRESSES; - }, - getDummyERC721TokenAddresses(): string[] { - return DUMMY_ERC_721_ADRESSES; - }, -}; diff --git a/packages/dev-utils/src/web3_factory.ts b/packages/dev-utils/src/web3_factory.ts deleted file mode 100644 index 114bdbaf48..0000000000 --- a/packages/dev-utils/src/web3_factory.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { - EmptyWalletSubprovider, - FakeGasEstimateSubprovider, - GanacheSubprovider, - RPCSubprovider, - Web3ProviderEngine, -} from '@0x/subproviders'; -import { providerUtils } from '@0x/utils'; -import * as fs from 'fs'; -import * as _ from 'lodash'; - -import { constants } from './constants'; -import { env, EnvVars } from './env'; - -export interface Web3Config { - total_accounts?: number; // default: 10 - hasAddresses?: boolean; // default: true - shouldUseInProcessGanache?: boolean; // default: false - shouldThrowErrorsOnGanacheRPCResponse?: boolean; // default: true - rpcUrl?: string; // default: localhost:8545 - shouldUseFakeGasEstimate?: boolean; // default: true - ganacheDatabasePath?: string; // default: undefined, creates a tmp dir - shouldAllowUnlimitedContractSize?: boolean; - fork?: string; - blockTime?: number; - locked?: boolean; - unlocked_accounts?: string[]; - hardfork?: string; // default: istanbul -} - -export const web3Factory = { - getRpcProvider(config: Web3Config = {}): Web3ProviderEngine { - const provider = new Web3ProviderEngine(); - - const hasAddresses = config.hasAddresses === undefined || config.hasAddresses; - const shouldUseFakeGasEstimate = - config.shouldUseFakeGasEstimate === undefined || config.shouldUseFakeGasEstimate; - - if (!hasAddresses) { - provider.addProvider(new EmptyWalletSubprovider()); - } - if (shouldUseFakeGasEstimate) { - provider.addProvider(new FakeGasEstimateSubprovider(constants.GAS_LIMIT)); - } - - const logger = { - log: (arg: any) => { - fs.appendFileSync('ganache.log', `${arg}\n`); - }, - }; - const shouldUseInProcessGanache = !!config.shouldUseInProcessGanache; - if (shouldUseInProcessGanache) { - if (config.rpcUrl !== undefined) { - throw new Error('Cannot use both GanacheSubprovider and RPCSubprovider'); - } - - if (config.ganacheDatabasePath !== undefined) { - const doesDatabaseAlreadyExist = fs.existsSync(config.ganacheDatabasePath); - if (!doesDatabaseAlreadyExist) { - // Working with local DB snapshot. Ganache requires this directory to exist - fs.mkdirSync(config.ganacheDatabasePath); - } - } - - const shouldThrowErrorsOnGanacheRPCResponse = - config.shouldThrowErrorsOnGanacheRPCResponse === undefined || - config.shouldThrowErrorsOnGanacheRPCResponse; - - provider.addProvider( - new GanacheSubprovider({ - total_accounts: config.total_accounts, - vmErrorsOnRPCResponse: shouldThrowErrorsOnGanacheRPCResponse, - db_path: config.ganacheDatabasePath, - allowUnlimitedContractSize: config.shouldAllowUnlimitedContractSize, - gasLimit: constants.GAS_LIMIT, - logger, - verbose: env.parseBoolean(EnvVars.VerboseGanache), - port: 8545, - network_id: 50, - mnemonic: 'concert load couple harbor equip island argue ramp clarify fence smart topic', - fork: config.fork, - blockTime: config.blockTime, - locked: config.locked, - unlocked_accounts: config.unlocked_accounts, - hardfork: config.hardfork || 'istanbul', - } as any), // TODO remove any once types are merged in DefinitelyTyped - ); - } else { - provider.addProvider(new RPCSubprovider(config.rpcUrl || constants.RPC_URL)); - } - providerUtils.startProviderEngine(provider); - return provider; - }, -}; diff --git a/packages/dev-utils/test/.npmignore b/packages/dev-utils/test/.npmignore deleted file mode 100644 index 87bc304368..0000000000 --- a/packages/dev-utils/test/.npmignore +++ /dev/null @@ -1,5 +0,0 @@ -.* -yarn-error.log -/src/ -/scripts/ -tsconfig.json diff --git a/packages/dev-utils/test/blockchain_lifecycle_test.ts b/packages/dev-utils/test/blockchain_lifecycle_test.ts deleted file mode 100644 index d7e54f0e8c..0000000000 --- a/packages/dev-utils/test/blockchain_lifecycle_test.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { Web3Wrapper } from '@0x/web3-wrapper'; -import * as chai from 'chai'; -import 'mocha'; - -import { BlockchainLifecycle, web3Factory } from '../src'; - -const expect = chai.expect; - -describe('BlockchainLifecycle tests', () => { - const provider = web3Factory.getRpcProvider({ shouldUseInProcessGanache: true }); - const web3Wrapper = new Web3Wrapper(provider); - const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper); - describe('#startAsync/revertAsync', () => { - it('reverts changes in between', async () => { - const blockNumberBefore = await web3Wrapper.getBlockNumberAsync(); - await blockchainLifecycle.startAsync(); - await web3Wrapper.mineBlockAsync(); - const blockNumberAfter = await web3Wrapper.getBlockNumberAsync(); - // tslint:disable-next-line:restrict-plus-operands - expect(blockNumberAfter).to.be.equal(blockNumberBefore + 1); - await blockchainLifecycle.revertAsync(); - const blockNumberAfterRevert = await web3Wrapper.getBlockNumberAsync(); - expect(blockNumberAfterRevert).to.be.equal(blockNumberBefore); - }); - }); -}); diff --git a/packages/dev-utils/test/chai_test.ts b/packages/dev-utils/test/chai_test.ts deleted file mode 100644 index 32762679e0..0000000000 --- a/packages/dev-utils/test/chai_test.ts +++ /dev/null @@ -1,193 +0,0 @@ -import { StringRevertError } from '@0x/utils'; -import * as chai from 'chai'; - -import { chaiSetup } from '../src'; - -chaiSetup.configure(); -const expect = chai.expect; - -class DescendantRevertError extends StringRevertError { - constructor(msg: string) { - super(msg); - } -} - -describe('Chai tests', () => { - describe('RevertErrors', () => { - describe('#equal', () => { - it('should equate two identical RevertErrors', () => { - const message = 'foo'; - const revert1 = new StringRevertError(message); - const revert2 = new StringRevertError(message); - expect(revert1).is.equal(revert2); - }); - it('should equate two RevertErrors where one has missing fields', () => { - const revert1 = new StringRevertError('foo'); - const revert2 = new StringRevertError(); - expect(revert1).is.equal(revert2); - }); - it('should not equate two RevertErrors with diferent fields', () => { - const revert1 = new StringRevertError('foo1'); - const revert2 = new StringRevertError('foo2'); - expect(revert1).is.not.equal(revert2); - }); - it('should not equate two RevertErrors with diferent types', () => { - const message = 'foo'; - const revert1 = new StringRevertError(message); - const revert2 = new DescendantRevertError(message); - expect(revert1).is.not.equal(revert2); - }); - it('should equate a StringRevertError to a string equal to message', () => { - const message = 'foo'; - const revert = new StringRevertError(message); - expect(message).is.equal(revert); - }); - it('should equate an Error to a StringRevertError with an equal message', () => { - const message = 'foo'; - const revert = new StringRevertError(message); - const error = new Error(message); - expect(error).is.equal(revert); - }); - it('should equate a ganache transaction revert error with reason to a StringRevertError with an equal message', () => { - const message = 'foo'; - const error: any = new Error(`VM Exception while processing transaction: revert ${message}`); - error.hashes = ['0x1']; - error.results = { '0x1': { error: 'revert', program_counter: 1, return: '0x', reason: message } }; - const revert = new StringRevertError(message); - expect(error).is.equal(revert); - }); - it('should equate a ganache transaction revert error with return data to a StringRevertError with an equal message', () => { - const error: any = new Error(`VM Exception while processing transaction: revert`); - error.hashes = ['0x1']; - // Encoding for `Error(string message='foo')` - const returnData = - '0x08c379a000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000003666f6f0000000000000000000000000000000000000000000000000000000000'; - error.results = { - '0x1': { error: 'revert', program_counter: 1, return: returnData, reason: undefined }, - }; - const revert = new StringRevertError('foo'); - expect(error).is.equal(revert); - }); - it('should not equate a ganache transaction revert error with reason to a StringRevertError with a different message', () => { - const message = 'foo'; - const error: any = new Error(`VM Exception while processing transaction: revert ${message}`); - error.hashes = ['0x1']; - error.results = { '0x1': { error: 'revert', program_counter: 1, return: '0x', reason: message } }; - const revert = new StringRevertError('boo'); - expect(error).is.not.equal(revert); - }); - it('should not equate a ganache transaction revert error with return data to a StringRevertError with a different message', () => { - const error: any = new Error(`VM Exception while processing transaction: revert`); - error.hashes = ['0x1']; - // Encoding for `Error(string message='foo')` - const returnData = - '0x08c379a000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000003666f6f0000000000000000000000000000000000000000000000000000000000'; - error.results = { - '0x1': { error: 'revert', program_counter: 1, return: returnData, reason: undefined }, - }; - const revert = new StringRevertError('boo'); - expect(error).is.not.equal(revert); - }); - it('should equate an opaque geth transaction revert error to any RevertError', () => { - const error = new Error(`always failing transaction`); - const revert = new StringRevertError('foo'); - expect(error).is.equal(revert); - }); - it('should equate a string to a StringRevertError with the same message', () => { - const message = 'foo'; - const revert = new StringRevertError(message); - expect(revert).is.equal(message); - }); - it('should not equate a StringRevertError to a string not equal to message', () => { - const revert = new StringRevertError('foo1'); - expect('foo2').is.not.equal(revert); - }); - it('should not equate a string to a StringRevertError with a different message', () => { - const revert = new StringRevertError('foo1'); - expect(revert).is.not.equal('foo2'); - }); - it('should not equate an Error to a StringRevertError with a different message', () => { - const revert = new StringRevertError('foo1'); - const error = new Error('foo2'); - expect(error).is.not.equal(revert); - }); - }); - describe('#revertWith', () => { - it('should equate a promise that rejects to identical RevertErrors', async () => { - const message = 'foo'; - const revert1 = new StringRevertError(message); - const revert2 = new StringRevertError(message); - const promise = (async () => { - throw revert1; - })(); - return expect(promise).to.revertWith(revert2); - }); - it('should not equate a promise that rejects to a StringRevertError with a different messages', async () => { - const revert1 = new StringRevertError('foo1'); - const revert2 = new StringRevertError('foo2'); - const promise = (async () => { - throw revert1; - })(); - return expect(promise).to.not.revertWith(revert2); - }); - it('should not equate a promise that rejects to different RevertError types', async () => { - const message = 'foo'; - const revert1 = new StringRevertError(message); - const revert2 = new DescendantRevertError(message); - const promise = (async () => { - throw revert1; - })(); - return expect(promise).to.not.revertWith(revert2); - }); - }); - describe('#become', () => { - it('should equate a promise that resolves to an identical RevertErrors', async () => { - const message = 'foo'; - const revert1 = new StringRevertError(message); - const revert2 = new StringRevertError(message); - const promise = (async () => revert1)(); - return expect(promise).to.become(revert2); - }); - it('should not equate a promise that resolves to a StringRevertError with a different messages', async () => { - const revert1 = new StringRevertError('foo1'); - const revert2 = new StringRevertError('foo2'); - const promise = (async () => revert1)(); - return expect(promise).to.not.become(revert2); - }); - it('should not equate a promise that resolves to different RevertError types', async () => { - const message = 'foo'; - const revert1 = new StringRevertError(message); - const revert2 = new DescendantRevertError(message); - const promise = (async () => revert1)(); - return expect(promise).to.not.become(revert2); - }); - }); - // TODO: Remove these tests when we no longer coerce `Error` types to `StringRevertError` types - // for backwards compatibility. - describe('#rejectedWith (backwards compatibility)', () => { - it('should equate a promise that rejects with an Error to a string of the same message', async () => { - const message = 'foo'; - const revert1 = new Error(message); - const promise = (async () => { - throw revert1; - })(); - return expect(promise).to.rejectedWith(message); - }); - it('should equate a promise that rejects with an StringRevertErrors to a string of the same message', async () => { - const message = 'foo'; - const revert = new StringRevertError(message); - const promise = (async () => { - throw revert; - })(); - return expect(promise).to.rejectedWith(message); - }); - it('should not equate a promise that rejects with an StringRevertErrors to a string with different messages', async () => { - const revert = new StringRevertError('foo1'); - const promise = (async () => { - throw revert; - })(); - return expect(promise).to.not.be.rejectedWith('foo2'); - }); - }); - }); -}); diff --git a/packages/dev-utils/test/rpc_test.ts b/packages/dev-utils/test/rpc_test.ts deleted file mode 100644 index f8cea45807..0000000000 --- a/packages/dev-utils/test/rpc_test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { Web3Wrapper } from '@0x/web3-wrapper'; -import * as chai from 'chai'; -import { BlockParamLiteral } from 'ethereum-types'; -import 'mocha'; - -import { web3Factory } from '../src'; - -const expect = chai.expect; - -describe('RPC tests', () => { - const provider = web3Factory.getRpcProvider({ shouldUseInProcessGanache: true }); - const web3Wrapper = new Web3Wrapper(provider); - describe('#mineBlockAsync', () => { - it('increases block number when called', async () => { - const blockNumberBefore = await web3Wrapper.getBlockNumberAsync(); - await web3Wrapper.mineBlockAsync(); - const blockNumberAfter = await web3Wrapper.getBlockNumberAsync(); - // tslint:disable-next-line:restrict-plus-operands - expect(blockNumberAfter).to.be.equal(blockNumberBefore + 1); - }); - }); - describe('#increaseTimeAsync', () => { - it('increases time when called', async () => { - const TIME_DELTA = 1000; - const blockTimestampBefore = await web3Wrapper.getBlockTimestampAsync(BlockParamLiteral.Latest); - await web3Wrapper.increaseTimeAsync(TIME_DELTA); - await web3Wrapper.mineBlockAsync(); - const blockTimestampAfter = await web3Wrapper.getBlockTimestampAsync(BlockParamLiteral.Latest); - // tslint:disable-next-line:restrict-plus-operands - expect(blockTimestampAfter).to.be.at.least(blockTimestampBefore + TIME_DELTA); - }); - }); - describe('#takeSnapshotAsync/revertSnapshotAsync', () => { - it('reverts changes in between', async () => { - const blockNumberBefore = await web3Wrapper.getBlockNumberAsync(); - const snapshotId = await web3Wrapper.takeSnapshotAsync(); - await web3Wrapper.mineBlockAsync(); - await web3Wrapper.revertSnapshotAsync(snapshotId); - const blockNumberAfter = await web3Wrapper.getBlockNumberAsync(); - expect(blockNumberAfter).to.be.equal(blockNumberBefore); - }); - }); -}); diff --git a/packages/dev-utils/tsconfig.json b/packages/dev-utils/tsconfig.json deleted file mode 100644 index 2ee711adcc..0000000000 --- a/packages/dev-utils/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../tsconfig", - "compilerOptions": { - "outDir": "lib", - "rootDir": "." - }, - "include": ["./src/**/*", "./test/**/*"] -} diff --git a/packages/dev-utils/tslint.json b/packages/dev-utils/tslint.json deleted file mode 100644 index 631f46bcaa..0000000000 --- a/packages/dev-utils/tslint.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "extends": ["@0x/tslint-config"], - "rules": { - "completed-docs": false - } -} diff --git a/packages/devnet/Dockerfile b/packages/devnet/Dockerfile deleted file mode 100644 index 56311327ee..0000000000 --- a/packages/devnet/Dockerfile +++ /dev/null @@ -1,26 +0,0 @@ -FROM alpine:3.7 - -RUN \ - apk add --update go git make gcc musl-dev linux-headers ca-certificates && \ - # TODO(albrow): Change the Git URL and branch once we have all relvant PRs - # merged to upstream. - git clone --depth 1 --branch '0x-testing' https://github.com/0xProject/go-ethereum && \ - (cd go-ethereum && make geth) && \ - cp go-ethereum/build/bin/geth /geth && \ - apk del go git make gcc musl-dev linux-headers && \ - rm -rf /go-ethereum && rm -rf /var/cache/apk/* - -RUN mkdir ~/devnet -WORKDIR ~/devnet - -COPY genesis.json . -COPY node0/ ./node0 -COPY run.sh . - -RUN /geth --datadir node0/ init genesis.json - -EXPOSE 8501 -EXPOSE 8546 -EXPOSE 30310 - -ENTRYPOINT ./run.sh diff --git a/packages/devnet/README.md b/packages/devnet/README.md deleted file mode 100644 index c7267fe11b..0000000000 --- a/packages/devnet/README.md +++ /dev/null @@ -1,124 +0,0 @@ -## 0x Devnet - -A private, single-node PoA Ethereum network for testing purposes only. It uses -Geth and the PoA implementation called "Clique". - -## Usage - -The devnet requires Docker to run (the latest version is recommended). To start -the network, run: - -``` -docker run -it --rm -p 8501:8501 -p 8546:8546 0xorg/devnet -``` - -This will download the latest version of the `0xorg/devnet` container, which is -[hosted on DockerHub](https://hub.docker.com/r/0xorg/devnet). - -Depending on your OS and how you installed docker, you may need to prefix any -docker commands with `sudo`. - -The Docker container exposes the HTTP JSON RPC API at port 8501, and this is the -primary way you are expected to interact with the devnet. The following -endpoints are supported: `personal,db,eth,net,web3,txpool,miner,debug`. - -It also exposes the WS JSON RPC API at port 8546. The following -endpoints are supported: `personal,db,eth,net,web3,txpool,miner,debug`. - -You can stop the network with `docker stop` and it will automatically clean up -after itself. (`docker stop` typically requires you to use `docker ps` to find -the name of the currently running container). - -### Configuration - -The devnet network only has a single node and uses PoA instead of PoW. That -means that one node, called the "sealer", is the ultimate authority for -validating transactions and adding new blocks to the chain. Since there is no -PoW it also means that mining does not require significant computational -resources. You can learn more about PoA and the Geth-specific implementation -called "Clique" in [EIP-225](https://github.com/ethereum/EIPs/issues/225). - -The address of the "sealer" is `0xe8816898d851d5b61b7f950627d04d794c07ca37`. The -password associated with the account is "password" and the (encrypted) private -keys are visible in the **node0/keystore** directory. This account is already -"unlocked" in the Geth node by default, so you can do things like sign and send -transactions from this account using the JSON RPC endpoints directly. - -There are also a number of other addresses that have hard-coded starting -balances for testing purposes. You can see the details in the **genesis.json** -file. All of these accounts are also unlocked by default. - -### Additional JSON RPC Methods - -In addition to the -[standard JSON RPC methods](https://github.com/ethereum/wiki/wiki/JSON-RPC) and -the -[Geth Management API](https://github.com/ethereum/go-ethereum/wiki/Management-APIs) -The devnet node supports some additional JSON RPC methods: - -#### debug_increaseTime - -Increases the timestamp of the next mined block. - -##### Parameters - -`Number` - The number of seconds by which to increase the time offset. - -##### Returns - -`Number` - The total number of seconds by which the time offset has been -increased (this includes all calls to `debug_increaseTime`). - -##### Example - -```js -// Request -curl -X POST --data '{"jsonrpc":"2.0","method":"debug_increaseTime","params":[100],"id":67}' - -// Result -{ - "id":67, - "jsonrpc": "2.0", - "result": "5000" -} -``` - -### Mining - -The node will automatically (nearly instantly) mine a block whenever new -transactions are added to the transaction pool. If there are no transactions in -the pool, it will wait. - -To stop mining, use the -[`miner.stop`](https://github.com/ethereum/go-ethereum/wiki/Management-APIs#miner_stop) -method. - -To start mining again, you can use the -[`miner.start`](https://github.com/ethereum/go-ethereum/wiki/Management-APIs#miner_start) -JSON RPC method. - -## Contributing - -We strongly recommend that the community help us make improvements and determine -the future direction of the protocol. To report bugs within this package, please -create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting -started. - -### Building - -In the package root directory, run: - -``` -docker build -t 0xorg/devnet . -``` - -### Publishing - -To publish the docker image, you need to be logged in to DockerHub and have the -appropriate credentials (if you need access, contact @fabioberger). Then run: - -``` -docker push 0xorg/devnet -``` diff --git a/packages/devnet/docker-compose.yml b/packages/devnet/docker-compose.yml deleted file mode 100644 index 1c1e7ca757..0000000000 --- a/packages/devnet/docker-compose.yml +++ /dev/null @@ -1,8 +0,0 @@ -version: '3' -services: - devnet: - image: 0x-devnet:latest - build: - context: . - ports: - - 8501:8501 diff --git a/packages/devnet/genesis.json b/packages/devnet/genesis.json deleted file mode 100644 index 073672dd95..0000000000 --- a/packages/devnet/genesis.json +++ /dev/null @@ -1,60 +0,0 @@ -{ - "config": { - "chainId": 50, - "homesteadBlock": 1, - "eip150Block": 2, - "eip150Hash": "0x0000000000000000000000000000000000000000000000000000000000000000", - "eip155Block": 3, - "eip158Block": 3, - "byzantiumBlock": 4, - "clique": { - "period": 0, - "epoch": 30000 - } - }, - "nonce": "0x0", - "timestamp": "0x5af1ffac", - "extraData": "0x0000000000000000000000000000000000000000000000000000000000000000e8816898d851d5b61b7f950627d04d794c07ca370000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "gasLimit": "0x4c4b400000", - "difficulty": "0x1", - "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000", - "coinbase": "0x0000000000000000000000000000000000000000", - "alloc": { - "0xe8816898d851d5b61b7f950627d04d794c07ca37": { - "balance": "0x56BC75E2D63100000" - }, - "0x5409ed021d9299bf6814279a6a1411a7e866a631": { - "balance": "0x56BC75E2D63100000" - }, - "0x6ecbe1db9ef729cbe972c83fb886247691fb6beb": { - "balance": "0x56BC75E2D63100000" - }, - "0xe36ea790bc9d7ab70c55260c66d52b1eca985f84": { - "balance": "0x56BC75E2D63100000" - }, - "0xe834ec434daba538cd1b9fe1582052b880bd7e63": { - "balance": "0x56BC75E2D63100000" - }, - "0x78dc5d2d739606d31509c31d654056a45185ecb6": { - "balance": "0x56BC75E2D63100000" - }, - "0xa8dda8d7f5310e4a9e24f8eba77e091ac264f872": { - "balance": "0x56BC75E2D63100000" - }, - "0x06cef8e666768cc40cc78cf93d9611019ddcb628": { - "balance": "0x56BC75E2D63100000" - }, - "0x4404ac8bd8f9618d27ad2f1485aa1b2cfd82482d": { - "balance": "0x56BC75E2D63100000" - }, - "0x7457d5e02197480db681d3fdf256c7aca21bdc12": { - "balance": "0x56BC75E2D63100000" - }, - "0x91c987bf62d25945db517bdaa840a6c661374402": { - "balance": "0x56BC75E2D63100000" - } - }, - "number": "0x0", - "gasUsed": "0x0", - "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000" -} diff --git a/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-08.903003751Z--5409ed021d9299bf6814279a6a1411a7e866a631 b/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-08.903003751Z--5409ed021d9299bf6814279a6a1411a7e866a631 deleted file mode 100644 index 32c4002e04..0000000000 --- a/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-08.903003751Z--5409ed021d9299bf6814279a6a1411a7e866a631 +++ /dev/null @@ -1 +0,0 @@ -{"address":"5409ed021d9299bf6814279a6a1411a7e866a631","crypto":{"cipher":"aes-128-ctr","ciphertext":"7c7bdd62b303eb3a42d5d8e935825ed5a05a47cb2cef71e346c61b1bd582f1aa","cipherparams":{"iv":"7fd6c9d9f9893f2c480735b5386b6d75"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"79cc86edc3a668845a68fabb3913710b7504922e47aac8513ab3d6a28d090218"},"mac":"8a593ae0d0b964e47625bc964b6d389f5687f5bde631b4913136db4ab1b8083e"},"id":"29f637ba-6a65-4401-a0d1-30e1554bd776","version":3} diff --git a/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-09.794553183Z--6ecbe1db9ef729cbe972c83fb886247691fb6beb b/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-09.794553183Z--6ecbe1db9ef729cbe972c83fb886247691fb6beb deleted file mode 100644 index ba84ccfd26..0000000000 --- a/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-09.794553183Z--6ecbe1db9ef729cbe972c83fb886247691fb6beb +++ /dev/null @@ -1 +0,0 @@ -{"address":"6ecbe1db9ef729cbe972c83fb886247691fb6beb","crypto":{"cipher":"aes-128-ctr","ciphertext":"ecaf4f2839d74d92e2cb87c2fc7d52862661b46e697d70acfbe43f0893db73ed","cipherparams":{"iv":"7641c3a107228f8a901c07a07ea1f70d"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"c67c9fb30648df6985c0490b6603382147e7dc1ea28ca8c934af4a453ec0555b"},"mac":"985dca9ce65ad400fa4c9009742be2d409f402fe05203fc1278cfd1451729e8d"},"id":"e8634edc-08e6-415e-8d65-7985c4c4a05c","version":3} diff --git a/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-10.696351411Z--e36ea790bc9d7ab70c55260c66d52b1eca985f84 b/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-10.696351411Z--e36ea790bc9d7ab70c55260c66d52b1eca985f84 deleted file mode 100644 index e889c38b34..0000000000 --- a/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-10.696351411Z--e36ea790bc9d7ab70c55260c66d52b1eca985f84 +++ /dev/null @@ -1 +0,0 @@ -{"address":"e36ea790bc9d7ab70c55260c66d52b1eca985f84","crypto":{"cipher":"aes-128-ctr","ciphertext":"49f89d7d612049f5f3581fc7c97d32ec9c9a2ca3c11165587139f16bfb29de6b","cipherparams":{"iv":"9767e0687a097c5b57e9cb30eec9bc0a"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"3e8f23332df99d519b602a0f6f4724338ba3fd9e7e313c337a92ffd1cafa19f1"},"mac":"4892051a669d45bb7de32a5eab63ee8fe52485a02218ce1806515da2adbd6584"},"id":"3488ad36-4a9d-4282-8651-7939b822429d","version":3} diff --git a/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-11.479938556Z--e834ec434daba538cd1b9fe1582052b880bd7e63 b/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-11.479938556Z--e834ec434daba538cd1b9fe1582052b880bd7e63 deleted file mode 100644 index c12742c542..0000000000 --- a/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-11.479938556Z--e834ec434daba538cd1b9fe1582052b880bd7e63 +++ /dev/null @@ -1 +0,0 @@ -{"address":"e834ec434daba538cd1b9fe1582052b880bd7e63","crypto":{"cipher":"aes-128-ctr","ciphertext":"a8ae3896739c63fc3bfe034277f6a1924a1c0ddc3f6747391dada8e61e15a928","cipherparams":{"iv":"f4f4d786cd3650a428a8bac5a6c824b1"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"9acecc321bcab9b69ffdea494b8894ad0221c30f05c17d2302e315db8708ecc6"},"mac":"fc416b8f539fdc1e39e87a3bd2a69b04455875de701ced60cc8948b222171380"},"id":"0d9703e8-14fc-45d0-a425-2c40b8ae846a","version":3} diff --git a/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-12.260348580Z--78dc5d2d739606d31509c31d654056a45185ecb6 b/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-12.260348580Z--78dc5d2d739606d31509c31d654056a45185ecb6 deleted file mode 100644 index 691e31dcff..0000000000 --- a/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-12.260348580Z--78dc5d2d739606d31509c31d654056a45185ecb6 +++ /dev/null @@ -1 +0,0 @@ -{"address":"78dc5d2d739606d31509c31d654056a45185ecb6","crypto":{"cipher":"aes-128-ctr","ciphertext":"25e90e593f08e9e3adc426c8685d90db5d1c04957e9dc8d5fab4ae30c3306b61","cipherparams":{"iv":"72ece22297a27363e795b678bcbd6be5"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"2201502b9d3c4e2076d9d15bfd9da3a6c75d9e2e574aabb29c3bc5a3b5ec55a5"},"mac":"13d709ed4bd2f5bf4973fc1373f8434835f0d12dc99b32c6fc14d9df7f41c62d"},"id":"3902dff4-5681-4646-b825-849f96efeec5","version":3} diff --git a/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-13.178294829Z--a8dda8d7f5310e4a9e24f8eba77e091ac264f872 b/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-13.178294829Z--a8dda8d7f5310e4a9e24f8eba77e091ac264f872 deleted file mode 100644 index 9054e0019b..0000000000 --- a/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-13.178294829Z--a8dda8d7f5310e4a9e24f8eba77e091ac264f872 +++ /dev/null @@ -1 +0,0 @@ -{"address":"a8dda8d7f5310e4a9e24f8eba77e091ac264f872","crypto":{"cipher":"aes-128-ctr","ciphertext":"0d67c13cf0b130e8ffa1aaca5df372f727164e633f8e0e28a3e54d0884ffb568","cipherparams":{"iv":"619cd539cda9f40abb45bba00b5fe53d"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"4effcd9b6fe71ee31cfe9057290154329b9af3acb6dcc46be7f78b5b9dcd3f42"},"mac":"c6eecd25944f4250b7b875d76bfbb60cc4e8db1d081621d1a2ddb72ea4e52a6d"},"id":"556bd3f1-1e5b-47a4-9b6e-448b9989d7d3","version":3} diff --git a/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-13.960499696Z--06cef8e666768cc40cc78cf93d9611019ddcb628 b/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-13.960499696Z--06cef8e666768cc40cc78cf93d9611019ddcb628 deleted file mode 100644 index 0870638dde..0000000000 --- a/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-13.960499696Z--06cef8e666768cc40cc78cf93d9611019ddcb628 +++ /dev/null @@ -1 +0,0 @@ -{"address":"06cef8e666768cc40cc78cf93d9611019ddcb628","crypto":{"cipher":"aes-128-ctr","ciphertext":"38c9ca150932dc8c5ec5c65796425b2de98295cae64db08b816da2c06fc52c20","cipherparams":{"iv":"512127e8e606c481612473e7bc4d38f1"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"16c4cabfd13cae2df66d8ff9acc7f503c95c808b00d0bb6a12932203889c679b"},"mac":"52297b496e8751627dea1ee17bf5cbea1926f90bcde3ffc8baa089184672f875"},"id":"31102097-86e4-4e19-ad73-03c3de67bf3b","version":3} diff --git a/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-14.757010386Z--4404ac8bd8f9618d27ad2f1485aa1b2cfd82482d b/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-14.757010386Z--4404ac8bd8f9618d27ad2f1485aa1b2cfd82482d deleted file mode 100644 index 5f28db78f5..0000000000 --- a/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-14.757010386Z--4404ac8bd8f9618d27ad2f1485aa1b2cfd82482d +++ /dev/null @@ -1 +0,0 @@ -{"address":"4404ac8bd8f9618d27ad2f1485aa1b2cfd82482d","crypto":{"cipher":"aes-128-ctr","ciphertext":"ca7aedbacc960fc0fcb418606d7bdf042c36cc2808a5c94ac222cc0b44a9970d","cipherparams":{"iv":"3b1fe5da1cf5d6cd2ceaaf24c008c897"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"a94e4d41d77ff6dc54beda30c7a46d8f3cc312ebeffa0352d679f7e3fc5301dc"},"mac":"9a82bf60103d05878f8af3c07765c22cba3df9b1c4376eaf859e47b805666e42"},"id":"ab68c67b-e15a-4ade-b3d9-2180a32b28fe","version":3} diff --git a/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-15.554233052Z--7457d5e02197480db681d3fdf256c7aca21bdc12 b/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-15.554233052Z--7457d5e02197480db681d3fdf256c7aca21bdc12 deleted file mode 100644 index 2a2c0194ad..0000000000 --- a/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-15.554233052Z--7457d5e02197480db681d3fdf256c7aca21bdc12 +++ /dev/null @@ -1 +0,0 @@ -{"address":"7457d5e02197480db681d3fdf256c7aca21bdc12","crypto":{"cipher":"aes-128-ctr","ciphertext":"720dcc2889c7b3636f9f659650181b0d46d82420460e23454277273f528baaee","cipherparams":{"iv":"1510028e2b9988d1a73b71cbb692d085"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"5db2b62f4d1f55a3f24c014c4f23f3ec9a2992dca6c2a89c24a566f99a079396"},"mac":"22c6fb134fd0a748195ea83e9ccb490ab2c9a3e8761f9d74ea6d02abbdeb8a43"},"id":"704c31f8-8ca2-4b49-9fdc-5923f5712dad","version":3} diff --git a/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-16.342711541Z--91c987bf62d25945db517bdaa840a6c661374402 b/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-16.342711541Z--91c987bf62d25945db517bdaa840a6c661374402 deleted file mode 100644 index edc6d7531f..0000000000 --- a/packages/devnet/node0/keystore/UTC--2018-05-11T21-29-16.342711541Z--91c987bf62d25945db517bdaa840a6c661374402 +++ /dev/null @@ -1 +0,0 @@ -{"address":"91c987bf62d25945db517bdaa840a6c661374402","crypto":{"cipher":"aes-128-ctr","ciphertext":"8f461f3c74643f382f7fc1f71719d5a89ed8cf75854d8a1b53e133997b53a386","cipherparams":{"iv":"cf595fb7680d36b4f5a01599ee54d2d1"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"73a9e599369d2bfaedd044559415147240c3517f6cd1dec8f77a98993d1ceaf8"},"mac":"c8be4dc59ad28d40f7b549a6b72834d149c84d67dc35e687676bbee0e07be395"},"id":"21cca6fb-7876-4e39-a986-a0a37f90da6d","version":3} diff --git a/packages/devnet/node0/keystore/UTC--2018-05-15T21-50-24.532037737Z--e8816898d851d5b61b7f950627d04d794c07ca37 b/packages/devnet/node0/keystore/UTC--2018-05-15T21-50-24.532037737Z--e8816898d851d5b61b7f950627d04d794c07ca37 deleted file mode 100644 index cd2c97a886..0000000000 --- a/packages/devnet/node0/keystore/UTC--2018-05-15T21-50-24.532037737Z--e8816898d851d5b61b7f950627d04d794c07ca37 +++ /dev/null @@ -1 +0,0 @@ -{"address":"e8816898d851d5b61b7f950627d04d794c07ca37","crypto":{"cipher":"aes-128-ctr","ciphertext":"1ff4add6955cba7ddaf29f66d7d21c5e1d714ef6191fbc651ae60f2ea3c95e8f","cipherparams":{"iv":"3ff869fbdbe1a523cdb327780365976e"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"7372dbae5fb318f8684902e099c311d4188721d677974d729711762c7ef6030c"},"mac":"485fa5dc701067782baa1589716a53110c7f917eb259e35ebca7265bbb7150b1"},"id":"89edb004-5b00-4607-a3af-a0d9ab9b1c34","version":3} \ No newline at end of file diff --git a/packages/devnet/node0/password.txt b/packages/devnet/node0/password.txt deleted file mode 100644 index 9842d2661f..0000000000 --- a/packages/devnet/node0/password.txt +++ /dev/null @@ -1,11 +0,0 @@ -password -password -password -password -password -password -password -password -password -password -password diff --git a/packages/devnet/run.sh b/packages/devnet/run.sh deleted file mode 100755 index 3d4a2e8a60..0000000000 --- a/packages/devnet/run.sh +++ /dev/null @@ -1,31 +0,0 @@ -set -e - -# Create log directory for Geth -mkdir -p /var/log - -# Start Geth and direct output to stdout -/geth \ - --verbosity 5 \ - --datadir node0/ \ - --syncmode 'full' \ - --nat none \ - --nodiscover \ - --port 30310 \ - --txpool.journal '' \ - --rpc \ - --rpcaddr '0.0.0.0' \ - --rpcport 8501 \ - --rpcvhosts '*' \ - --rpcapi 'personal,db,eth,net,web3,txpool,miner,debug' \ - --ws \ - --wsaddr 0.0.0.0 \ - --wsport 8546 \ - --wsorigins '*' \ - --wsapi 'personal,db,eth,net,web3,txpool,miner,debug' \ - --networkid 50 \ - --gasprice '2000000000' \ - --targetgaslimit '0x4c4b400000' \ - --mine \ - --etherbase '0xe8816898d851d5b61b7f950627d04d794c07ca37' \ - --unlock '0xe8816898d851d5b61b7f950627d04d794c07ca37,0x5409ed021d9299bf6814279a6a1411a7e866a631,0x6ecbe1db9ef729cbe972c83fb886247691fb6beb,0xe36ea790bc9d7ab70c55260c66d52b1eca985f84,0xe834ec434daba538cd1b9fe1582052b880bd7e63,0x78dc5d2d739606d31509c31d654056a45185ecb6,0xa8dda8d7f5310e4a9e24f8eba77e091ac264f872,0x06cef8e666768cc40cc78cf93d9611019ddcb628,0x4404ac8bd8f9618d27ad2f1485aa1b2cfd82482d,0x7457d5e02197480db681d3fdf256c7aca21bdc12,0x91c987bf62d25945db517bdaa840a6c661374402' \ - --password=node0/password.txt diff --git a/packages/ethereum-types/.npmignore b/packages/ethereum-types/.npmignore deleted file mode 100644 index ea588d4859..0000000000 --- a/packages/ethereum-types/.npmignore +++ /dev/null @@ -1,9 +0,0 @@ -# Blacklist all files -.* -* -# Whitelist lib -!lib/**/* -# Blacklist tests and publish scripts -/lib/test/* -/lib/monorepo_scripts/ -# Package specific ignore diff --git a/packages/ethereum-types/CHANGELOG.json b/packages/ethereum-types/CHANGELOG.json deleted file mode 100644 index 7262e20b92..0000000000 --- a/packages/ethereum-types/CHANGELOG.json +++ /dev/null @@ -1,369 +0,0 @@ -[ - { - "version": "3.3.0", - "changes": [ - { - "note": "Make `payable` field in `ConstructorAbi` optional", - "pr": 2648 - } - ] - }, - { - "version": "3.2.0", - "changes": [ - { - "note": "Add geth eth_call types", - "pr": 2620 - }, - { - "note": "Touch this package to fix publish", - "pr": 2628 - } - ], - "timestamp": 1594788383 - }, - { - "timestamp": 1592969527, - "version": "3.1.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.1.0", - "changes": [ - { - "note": "Add `linkReferences` to `EvmBytecodeOutput` and `EvmBytecodeOutputLinkReferences` type", - "pr": 2462 - }, - { - "note": "Update `MethodAbi` definition for solidity 0.6", - "pr": 2540 - } - ], - "timestamp": 1581204851 - }, - { - "version": "3.0.0", - "changes": [ - { - "note": "All references to network ID have been removed, and references to chain ID have been introduced instead", - "pr": 2313 - }, - { - "note": "Add `RevertErrorAbi` interface as part of `AbiDefinition` types", - "pr": 1761 - }, - { - "note": "Add `DecodedLogs` type", - "pr": 2220 - } - ], - "timestamp": 1575296764 - }, - { - "version": "2.2.0-beta.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1574030254 - }, - { - "version": "2.2.0-beta.1", - "changes": [ - { - "note": "All references to network ID have been removed, and references to chain ID have been introduced instead", - "pr": 2313 - } - ], - "timestamp": 1573159180 - }, - { - "version": "2.2.0-beta.0", - "changes": [ - { - "note": "Add `RevertErrorAbi` interface as part of `AbiDefinition` types", - "pr": 1761 - }, - { - "note": "Add `DecodedLogs` type", - "pr": 2220 - } - ], - "timestamp": 1570135330 - }, - { - "timestamp": 1568744790, - "version": "2.1.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1567521715, - "version": "2.1.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.1.4", - "changes": [ - { - "note": "new interface TupleDataItem, a DataItem that definitely has a `components` field", - "pr": 1919 - } - ], - "timestamp": 1563957393 - }, - { - "version": "2.1.3", - "changes": [ - { - "note": "Made most fields in DevdocOutput optional, as they may not all be present just because devdoc is", - "pr": 1878 - } - ], - "timestamp": 1563006338 - }, - { - "version": "2.1.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1554997931 - }, - { - "timestamp": 1553091633, - "version": "2.1.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.1.0", - "changes": [ - { - "note": "Added types SupportedProvider, GanacheProvider, Web3JsProvider, ZeroExProvider, EIP1193Provider", - "pr": 1627 - }, - { - "note": "Added all existing opcodes to `OpCode` type", - "pr": 1638 - } - ], - "timestamp": 1551130135 - }, - { - "version": "2.0.0", - "changes": [ - { - "note": "Upgrade the bignumber.js to v8.0.2", - "pr": 1517 - } - ], - "timestamp": 1549373905 - }, - { - "timestamp": 1547561734, - "version": "1.1.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547225310, - "version": "1.1.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.1.4", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544739608 - }, - { - "version": "1.1.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544570656 - }, - { - "version": "1.1.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1541740904 - }, - { - "version": "1.1.1", - "changes": [ - { - "note": "Add `JSONRPCResponseError` and error field on `JSONRPCResponsePayload`.", - "pr": 1102 - } - ], - "timestamp": 1539871071 - }, - { - "version": "1.1.0", - "changes": [ - { - "note": "Unpublished package." - } - ] - }, - { - "timestamp": 1538693146, - "version": "1.0.11", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1538475601, - "version": "1.0.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1538157789, - "version": "1.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537907159, - "version": "1.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537541580, - "version": "1.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1536142250, - "version": "1.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1535133899, - "version": "1.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1534210131, - "version": "1.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532614997, - "version": "1.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532605697, - "version": "1.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532357734, - "version": "1.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532043000, - "version": "1.0.0", - "changes": [ - { - "note": "Add `TraceParams` interface for `debug_traceTransaction` parameters", - "pr": 675 - }, - { - "note": "Add `TransactionReceiptStatus` type", - "pr": 812 - }, - { - "note": "Add Artifact types: `CompilerSettings`, `CompilerOptions`, `OutputField`", - "pr": 924 - } - ] - }, - { - "version": "0.0.2", - "changes": [ - { - "note": "Initial publish", - "pr": "642" - } - ], - "timestamp": 1527811200 - } -] diff --git a/packages/ethereum-types/CHANGELOG.md b/packages/ethereum-types/CHANGELOG.md deleted file mode 100644 index c8b5c0e1a5..0000000000 --- a/packages/ethereum-types/CHANGELOG.md +++ /dev/null @@ -1,154 +0,0 @@ - - -CHANGELOG - -## v3.2.0 - _July 15, 2020_ - - * Add geth eth_call types (#2620) - * Touch this package to fix publish (#2628) - -## v3.1.1 - _June 24, 2020_ - - * Dependencies updated - -## v3.1.0 - _February 8, 2020_ - - * Add `linkReferences` to `EvmBytecodeOutput` and `EvmBytecodeOutputLinkReferences` type (#2462) - * Update `MethodAbi` definition for solidity 0.6 (#2540) - -## v3.0.0 - _December 2, 2019_ - - * All references to network ID have been removed, and references to chain ID have been introduced instead (#2313) - * Add `RevertErrorAbi` interface as part of `AbiDefinition` types (#1761) - * Add `DecodedLogs` type (#2220) - -## v2.2.0-beta.2 - _November 17, 2019_ - - * Dependencies updated - -## v2.2.0-beta.1 - _November 7, 2019_ - - * All references to network ID have been removed, and references to chain ID have been introduced instead (#2313) - -## v2.2.0-beta.0 - _October 3, 2019_ - - * Add `RevertErrorAbi` interface as part of `AbiDefinition` types (#1761) - * Add `DecodedLogs` type (#2220) - -## v2.1.6 - _September 17, 2019_ - - * Dependencies updated - -## v2.1.5 - _September 3, 2019_ - - * Dependencies updated - -## v2.1.4 - _July 24, 2019_ - - * new interface TupleDataItem, a DataItem that definitely has a `components` field (#1919) - -## v2.1.3 - _July 13, 2019_ - - * Made most fields in DevdocOutput optional, as they may not all be present just because devdoc is (#1878) - -## v2.1.2 - _April 11, 2019_ - - * Dependencies updated - -## v2.1.1 - _March 20, 2019_ - - * Dependencies updated - -## v2.1.0 - _February 25, 2019_ - - * Added types SupportedProvider, GanacheProvider, Web3JsProvider, ZeroExProvider, EIP1193Provider (#1627) - * Added all existing opcodes to `OpCode` type (#1638) - -## v2.0.0 - _February 5, 2019_ - - * Upgrade the bignumber.js to v8.0.2 (#1517) - -## v1.1.6 - _January 15, 2019_ - - * Dependencies updated - -## v1.1.5 - _January 11, 2019_ - - * Dependencies updated - -## v1.1.4 - _December 13, 2018_ - - * Dependencies updated - -## v1.1.3 - _December 11, 2018_ - - * Dependencies updated - -## v1.1.2 - _November 9, 2018_ - - * Dependencies updated - -## v1.1.1 - _October 18, 2018_ - - * Add `JSONRPCResponseError` and error field on `JSONRPCResponsePayload`. (#1102) - -## v1.1.0 - _Invalid date_ - - * Unpublished package. - -## v1.0.11 - _October 4, 2018_ - - * Dependencies updated - -## v1.0.10 - _October 2, 2018_ - - * Dependencies updated - -## v1.0.9 - _September 28, 2018_ - - * Dependencies updated - -## v1.0.8 - _September 25, 2018_ - - * Dependencies updated - -## v1.0.7 - _September 21, 2018_ - - * Dependencies updated - -## v1.0.6 - _September 5, 2018_ - - * Dependencies updated - -## v1.0.5 - _August 24, 2018_ - - * Dependencies updated - -## v1.0.4 - _August 14, 2018_ - - * Dependencies updated - -## v1.0.3 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.2 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.1 - _July 23, 2018_ - - * Dependencies updated - -## v1.0.0 - _July 19, 2018_ - - * Add `TraceParams` interface for `debug_traceTransaction` parameters (#675) - * Add `TransactionReceiptStatus` type (#812) - * Add Artifact types: `CompilerSettings`, `CompilerOptions`, `OutputField` (#924) - -## v0.0.2 - _June 1, 2018_ - - * Initial publish (#642) diff --git a/packages/ethereum-types/README.md b/packages/ethereum-types/README.md deleted file mode 100644 index 2b992a1c75..0000000000 --- a/packages/ethereum-types/README.md +++ /dev/null @@ -1,61 +0,0 @@ -## ethereum-types - -TypeScript types shared across Ethereum-related packages/libraries/tools. - -## Installation - -```bash -yarn add -D ethereum-types -``` - -## Usage - -```javascript -import { TransactionReceipt, TxData, TxDataPayable } from 'ethereum-types'; -``` - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install dependencies - -If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: - -```bash -yarn config set workspaces-experimental true -``` - -Then install dependencies - -```bash -yarn install -``` - -### Build - -To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory: - -```bash -PKG=ethereum-types yarn build -``` - -Or continuously rebuild on change: - -```bash -PKG=ethereum-types yarn watch -``` - -### Clean - -```bash -yarn clean -``` - -### Lint - -```bash -yarn lint -``` diff --git a/packages/ethereum-types/docs/reference.mdx b/packages/ethereum-types/docs/reference.mdx deleted file mode 100644 index 618e639969..0000000000 --- a/packages/ethereum-types/docs/reference.mdx +++ /dev/null @@ -1,4612 +0,0 @@ -# Interface: GanacheProvider - - -## Methods - -### sendAsync - -▸ **sendAsync**(`payload`: [JSONRPCRequestPayload](_index_.jsonrpcrequestpayload.md), `callback`: [JSONRPCErrorCallback](#jsonrpcerrorcallback)): *void* - -*Defined in [index.ts:14](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L14)* - -**Parameters:** - -Name | Type | ------- | ------ | -`payload` | [JSONRPCRequestPayload](#class-jsonrpcrequestpayload) | -`callback` | [JSONRPCErrorCallback](#jsonrpcerrorcallback) | - -**Returns:** *void* - -
- -# Enumeration: BlockParamLiteral - - -## Enumeration members - -### Earliest - -• **Earliest**: = "earliest" - -*Defined in [index.ts:479](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L479)* - -___ - -### Latest - -• **Latest**: = "latest" - -*Defined in [index.ts:480](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L480)* - -___ - -### Pending - -• **Pending**: = "pending" - -*Defined in [index.ts:481](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L481)* - -
- -# Enumeration: OpCode - - -## Enumeration members - -### Add - -• **Add**: = "ADD" - -*Defined in [index.ts:148](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L148)* - -___ - -### AddMod - -• **AddMod**: = "ADDMOD" - -*Defined in [index.ts:155](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L155)* - -___ - -### Address - -• **Address**: = "ADDRESS" - -*Defined in [index.ts:174](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L174)* - -___ - -### And - -• **And**: = "AND" - -*Defined in [index.ts:166](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L166)* - -___ - -### Balance - -• **Balance**: = "BALANCE" - -*Defined in [index.ts:175](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L175)* - -___ - -### BlockHash - -• **BlockHash**: = "BLOCKHASH" - -*Defined in [index.ts:190](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L190)* - -___ - -### Byte - -• **Byte**: = "BYTE" - -*Defined in [index.ts:170](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L170)* - -___ - -### Call - -• **Call**: = "CALL" - -*Defined in [index.ts:283](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L283)* - -___ - -### CallCode - -• **CallCode**: = "CALLCODE" - -*Defined in [index.ts:284](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L284)* - -___ - -### CallDataCopy - -• **CallDataCopy**: = "CALLDATACOPY" - -*Defined in [index.ts:181](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L181)* - -___ - -### CallDataLoad - -• **CallDataLoad**: = "CALLDATALOAD" - -*Defined in [index.ts:179](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L179)* - -___ - -### CallDataSize - -• **CallDataSize**: = "CALLDATASIZE" - -*Defined in [index.ts:180](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L180)* - -___ - -### CallValue - -• **CallValue**: = "CALLVALUE" - -*Defined in [index.ts:178](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L178)* - -___ - -### Caller - -• **Caller**: = "CALLER" - -*Defined in [index.ts:177](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L177)* - -___ - -### CodeCopy - -• **CodeCopy**: = "CODECOPY" - -*Defined in [index.ts:183](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L183)* - -___ - -### CodeSize - -• **CodeSize**: = "CODESIZE" - -*Defined in [index.ts:182](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L182)* - -___ - -### Coinbase - -• **Coinbase**: = "COINBASE" - -*Defined in [index.ts:191](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L191)* - -___ - -### Create - -• **Create**: = "CREATE" - -*Defined in [index.ts:282](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L282)* - -___ - -### DelegateCall - -• **DelegateCall**: = "DELEGATECALL" - -*Defined in [index.ts:286](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L286)* - -___ - -### Difficulty - -• **Difficulty**: = "DIFFICULTY" - -*Defined in [index.ts:194](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L194)* - -___ - -### Div - -• **Div**: = "DIV" - -*Defined in [index.ts:151](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L151)* - -___ - -### Dup1 - -• **Dup1**: = "DUP1" - -*Defined in [index.ts:243](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L243)* - -___ - -### Dup10 - -• **Dup10**: = "DUP10" - -*Defined in [index.ts:252](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L252)* - -___ - -### Dup11 - -• **Dup11**: = "DUP11" - -*Defined in [index.ts:253](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L253)* - -___ - -### Dup12 - -• **Dup12**: = "DUP12" - -*Defined in [index.ts:254](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L254)* - -___ - -### Dup13 - -• **Dup13**: = "DUP13" - -*Defined in [index.ts:255](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L255)* - -___ - -### Dup14 - -• **Dup14**: = "DUP14" - -*Defined in [index.ts:256](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L256)* - -___ - -### Dup15 - -• **Dup15**: = "DUP15" - -*Defined in [index.ts:257](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L257)* - -___ - -### Dup16 - -• **Dup16**: = "DUP16" - -*Defined in [index.ts:258](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L258)* - -___ - -### Dup2 - -• **Dup2**: = "DUP2" - -*Defined in [index.ts:244](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L244)* - -___ - -### Dup3 - -• **Dup3**: = "DUP3" - -*Defined in [index.ts:245](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L245)* - -___ - -### Dup4 - -• **Dup4**: = "DUP4" - -*Defined in [index.ts:246](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L246)* - -___ - -### Dup5 - -• **Dup5**: = "DUP5" - -*Defined in [index.ts:247](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L247)* - -___ - -### Dup6 - -• **Dup6**: = "DUP6" - -*Defined in [index.ts:248](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L248)* - -___ - -### Dup7 - -• **Dup7**: = "DUP7" - -*Defined in [index.ts:249](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L249)* - -___ - -### Dup8 - -• **Dup8**: = "DUP8" - -*Defined in [index.ts:250](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L250)* - -___ - -### Dup9 - -• **Dup9**: = "DUP9" - -*Defined in [index.ts:251](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L251)* - -___ - -### Eq - -• **Eq**: = "EQ" - -*Defined in [index.ts:164](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L164)* - -___ - -### Exp - -• **Exp**: = "EXP" - -*Defined in [index.ts:157](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L157)* - -___ - -### ExtCodeCopy - -• **ExtCodeCopy**: = "EXTCODECOPY" - -*Defined in [index.ts:186](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L186)* - -___ - -### ExtCodeSize - -• **ExtCodeSize**: = "EXTCODESIZE" - -*Defined in [index.ts:185](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L185)* - -___ - -### Gas - -• **Gas**: = "GAS" - -*Defined in [index.ts:207](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L207)* - -___ - -### GasPrice - -• **GasPrice**: = "GASPRICE" - -*Defined in [index.ts:184](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L184)* - -___ - -### Gaslimit - -• **Gaslimit**: = "GASLIMIT" - -*Defined in [index.ts:195](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L195)* - -___ - -### Gt - -• **Gt**: = "GT" - -*Defined in [index.ts:161](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L161)* - -___ - -### Invalid - -• **Invalid**: = "INVALID" - -*Defined in [index.ts:289](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L289)* - -___ - -### IsZero - -• **IsZero**: = "ISZERO" - -*Defined in [index.ts:165](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L165)* - -___ - -### Jump - -• **Jump**: = "JUMP" - -*Defined in [index.ts:203](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L203)* - -___ - -### JumpDest - -• **JumpDest**: = "JUMPDEST" - -*Defined in [index.ts:208](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L208)* - -___ - -### Jumpi - -• **Jumpi**: = "JUMPI" - -*Defined in [index.ts:204](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L204)* - -___ - -### Log1 - -• **Log1**: = "LOG1" - -*Defined in [index.ts:277](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L277)* - -___ - -### Log2 - -• **Log2**: = "LOG2" - -*Defined in [index.ts:278](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L278)* - -___ - -### Log3 - -• **Log3**: = "LOG3" - -*Defined in [index.ts:279](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L279)* - -___ - -### Log4 - -• **Log4**: = "LOG4" - -*Defined in [index.ts:280](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L280)* - -___ - -### Lt - -• **Lt**: = "LT" - -*Defined in [index.ts:160](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L160)* - -___ - -### MLoad - -• **MLoad**: = "MLOAD" - -*Defined in [index.ts:198](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L198)* - -___ - -### MSize - -• **MSize**: = "MSIZE" - -*Defined in [index.ts:206](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L206)* - -___ - -### MStore - -• **MStore**: = "MSTORE" - -*Defined in [index.ts:199](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L199)* - -___ - -### MStore8 - -• **MStore8**: = "MSTORE8" - -*Defined in [index.ts:200](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L200)* - -___ - -### Mod - -• **Mod**: = "MOD" - -*Defined in [index.ts:153](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L153)* - -___ - -### Mul - -• **Mul**: = "MUL" - -*Defined in [index.ts:149](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L149)* - -___ - -### MulMod - -• **MulMod**: = "MULMOD" - -*Defined in [index.ts:156](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L156)* - -___ - -### Not - -• **Not**: = "NOT" - -*Defined in [index.ts:169](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L169)* - -___ - -### Number - -• **Number**: = "NUMBER" - -*Defined in [index.ts:193](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L193)* - -___ - -### Or - -• **Or**: = "OR" - -*Defined in [index.ts:167](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L167)* - -___ - -### Origin - -• **Origin**: = "ORIGIN" - -*Defined in [index.ts:176](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L176)* - -___ - -### Pc - -• **Pc**: = "PC" - -*Defined in [index.ts:205](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L205)* - -___ - -### Pop - -• **Pop**: = "POP" - -*Defined in [index.ts:197](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L197)* - -___ - -### Push1 - -• **Push1**: = "PUSH1" - -*Defined in [index.ts:210](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L210)* - -___ - -### Push10 - -• **Push10**: = "PUSH10" - -*Defined in [index.ts:219](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L219)* - -___ - -### Push11 - -• **Push11**: = "PUSH11" - -*Defined in [index.ts:220](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L220)* - -___ - -### Push12 - -• **Push12**: = "PUSH12" - -*Defined in [index.ts:221](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L221)* - -___ - -### Push13 - -• **Push13**: = "PUSH13" - -*Defined in [index.ts:222](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L222)* - -___ - -### Push14 - -• **Push14**: = "PUSH14" - -*Defined in [index.ts:223](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L223)* - -___ - -### Push15 - -• **Push15**: = "PUSH15" - -*Defined in [index.ts:224](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L224)* - -___ - -### Push16 - -• **Push16**: = "PUSH16" - -*Defined in [index.ts:225](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L225)* - -___ - -### Push17 - -• **Push17**: = "PUSH17" - -*Defined in [index.ts:226](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L226)* - -___ - -### Push18 - -• **Push18**: = "PUSH18" - -*Defined in [index.ts:227](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L227)* - -___ - -### Push19 - -• **Push19**: = "PUSH19" - -*Defined in [index.ts:228](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L228)* - -___ - -### Push2 - -• **Push2**: = "PUSH2" - -*Defined in [index.ts:211](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L211)* - -___ - -### Push20 - -• **Push20**: = "PUSH20" - -*Defined in [index.ts:229](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L229)* - -___ - -### Push21 - -• **Push21**: = "PUSH21" - -*Defined in [index.ts:230](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L230)* - -___ - -### Push22 - -• **Push22**: = "PUSH22" - -*Defined in [index.ts:231](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L231)* - -___ - -### Push23 - -• **Push23**: = "PUSH23" - -*Defined in [index.ts:232](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L232)* - -___ - -### Push24 - -• **Push24**: = "PUSH24" - -*Defined in [index.ts:233](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L233)* - -___ - -### Push25 - -• **Push25**: = "PUSH25" - -*Defined in [index.ts:234](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L234)* - -___ - -### Push26 - -• **Push26**: = "PUSH26" - -*Defined in [index.ts:235](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L235)* - -___ - -### Push27 - -• **Push27**: = "PUSH27" - -*Defined in [index.ts:236](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L236)* - -___ - -### Push28 - -• **Push28**: = "PUSH28" - -*Defined in [index.ts:237](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L237)* - -___ - -### Push29 - -• **Push29**: = "PUSH29" - -*Defined in [index.ts:238](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L238)* - -___ - -### Push3 - -• **Push3**: = "PUSH3" - -*Defined in [index.ts:212](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L212)* - -___ - -### Push30 - -• **Push30**: = "PUSH30" - -*Defined in [index.ts:239](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L239)* - -___ - -### Push31 - -• **Push31**: = "PUSH31" - -*Defined in [index.ts:240](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L240)* - -___ - -### Push32 - -• **Push32**: = "PUSH32" - -*Defined in [index.ts:241](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L241)* - -___ - -### Push4 - -• **Push4**: = "PUSH4" - -*Defined in [index.ts:213](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L213)* - -___ - -### Push5 - -• **Push5**: = "PUSH5" - -*Defined in [index.ts:214](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L214)* - -___ - -### Push6 - -• **Push6**: = "PUSH6" - -*Defined in [index.ts:215](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L215)* - -___ - -### Push7 - -• **Push7**: = "PUSH7" - -*Defined in [index.ts:216](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L216)* - -___ - -### Push8 - -• **Push8**: = "PUSH8" - -*Defined in [index.ts:217](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L217)* - -___ - -### Push9 - -• **Push9**: = "PUSH9" - -*Defined in [index.ts:218](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L218)* - -___ - -### Return - -• **Return**: = "RETURN" - -*Defined in [index.ts:285](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L285)* - -___ - -### ReturnDataCopy - -• **ReturnDataCopy**: = "RETURNDATACOPY" - -*Defined in [index.ts:188](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L188)* - -___ - -### ReturnDataSize - -• **ReturnDataSize**: = "RETURNDATASIZE" - -*Defined in [index.ts:187](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L187)* - -___ - -### Revert - -• **Revert**: = "REVERT" - -*Defined in [index.ts:288](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L288)* - -___ - -### SDiv - -• **SDiv**: = "SDIV" - -*Defined in [index.ts:152](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L152)* - -___ - -### SGt - -• **SGt**: = "SGT" - -*Defined in [index.ts:163](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L163)* - -___ - -### SLoad - -• **SLoad**: = "SLOAD" - -*Defined in [index.ts:201](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L201)* - -___ - -### SLt - -• **SLt**: = "SLT" - -*Defined in [index.ts:162](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L162)* - -___ - -### SMod - -• **SMod**: = "SMOD" - -*Defined in [index.ts:154](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L154)* - -___ - -### SStore - -• **SStore**: = "SSTORE" - -*Defined in [index.ts:202](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L202)* - -___ - -### SelfDestruct - -• **SelfDestruct**: = "SELFDESTRUCT" - -*Defined in [index.ts:290](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L290)* - -___ - -### Sha3 - -• **Sha3**: = "SHA3" - -*Defined in [index.ts:172](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L172)* - -___ - -### SignExtend - -• **SignExtend**: = "SIGNEXTEND" - -*Defined in [index.ts:158](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L158)* - -___ - -### StaticCall - -• **StaticCall**: = "STATICCALL" - -*Defined in [index.ts:287](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L287)* - -___ - -### Stop - -• **Stop**: = "STOP" - -*Defined in [index.ts:147](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L147)* - -___ - -### Sub - -• **Sub**: = "SUB" - -*Defined in [index.ts:150](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L150)* - -___ - -### Swap1 - -• **Swap1**: = "SWAP1" - -*Defined in [index.ts:260](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L260)* - -___ - -### Swap10 - -• **Swap10**: = "SWAP10" - -*Defined in [index.ts:269](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L269)* - -___ - -### Swap11 - -• **Swap11**: = "SWAP11" - -*Defined in [index.ts:270](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L270)* - -___ - -### Swap12 - -• **Swap12**: = "SWAP12" - -*Defined in [index.ts:271](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L271)* - -___ - -### Swap13 - -• **Swap13**: = "SWAP13" - -*Defined in [index.ts:272](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L272)* - -___ - -### Swap14 - -• **Swap14**: = "SWAP14" - -*Defined in [index.ts:273](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L273)* - -___ - -### Swap15 - -• **Swap15**: = "SWAP15" - -*Defined in [index.ts:274](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L274)* - -___ - -### Swap16 - -• **Swap16**: = "SWAP16" - -*Defined in [index.ts:275](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L275)* - -___ - -### Swap2 - -• **Swap2**: = "SWAP2" - -*Defined in [index.ts:261](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L261)* - -___ - -### Swap3 - -• **Swap3**: = "SWAP3" - -*Defined in [index.ts:262](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L262)* - -___ - -### Swap4 - -• **Swap4**: = "SWAP4" - -*Defined in [index.ts:263](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L263)* - -___ - -### Swap5 - -• **Swap5**: = "SWAP5" - -*Defined in [index.ts:264](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L264)* - -___ - -### Swap6 - -• **Swap6**: = "SWAP6" - -*Defined in [index.ts:265](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L265)* - -___ - -### Swap7 - -• **Swap7**: = "SWAP7" - -*Defined in [index.ts:266](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L266)* - -___ - -### Swap8 - -• **Swap8**: = "SWAP8" - -*Defined in [index.ts:267](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L267)* - -___ - -### Swap9 - -• **Swap9**: = "SWAP9" - -*Defined in [index.ts:268](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L268)* - -___ - -### TimeStamp - -• **TimeStamp**: = "TimeStamp" - -*Defined in [index.ts:192](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L192)* - -___ - -### Xor - -• **Xor**: = "XOR" - -*Defined in [index.ts:168](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L168)* - -
- -# Enumeration: SolidityTypes - - -## Enumeration members - -### Address - -• **Address**: = "address" - -*Defined in [index.ts:498](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L498)* - -___ - -### Bool - -• **Bool**: = "bool" - -*Defined in [index.ts:499](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L499)* - -___ - -### Bytes - -• **Bytes**: = "bytes" - -*Defined in [index.ts:500](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L500)* - -___ - -### Int - -• **Int**: = "int" - -*Defined in [index.ts:501](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L501)* - -___ - -### String - -• **String**: = "string" - -*Defined in [index.ts:502](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L502)* - -___ - -### Tuple - -• **Tuple**: = "tuple" - -*Defined in [index.ts:503](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L503)* - -___ - -### Uint - -• **Uint**: = "uint" - -*Defined in [index.ts:506](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L506)* - -___ - -### Uint256 - -• **Uint256**: = "uint256" - -*Defined in [index.ts:504](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L504)* - -___ - -### Uint8 - -• **Uint8**: = "uint8" - -*Defined in [index.ts:505](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L505)* - -
- -# Interface: AbstractBlock - - -## Properties - -### difficulty - -• **difficulty**: *`BigNumber`* - -*Defined in [index.ts:357](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L357)* - -___ - -### extraData - -• **extraData**: *string* - -*Defined in [index.ts:359](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L359)* - -___ - -### gasLimit - -• **gasLimit**: *number* - -*Defined in [index.ts:361](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L361)* - -___ - -### gasUsed - -• **gasUsed**: *number* - -*Defined in [index.ts:362](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L362)* - -___ - -### hash - -• **hash**: *string | null* - -*Defined in [index.ts:349](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L349)* - -___ - -### logsBloom - -• **logsBloom**: *string | null* - -*Defined in [index.ts:353](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L353)* - -___ - -### miner - -• **miner**: *string* - -*Defined in [index.ts:356](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L356)* - -___ - -### nonce - -• **nonce**: *string | null* - -*Defined in [index.ts:351](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L351)* - -___ - -### number - -• **number**: *number | null* - -*Defined in [index.ts:348](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L348)* - -___ - -### parentHash - -• **parentHash**: *string* - -*Defined in [index.ts:350](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L350)* - -___ - -### sha3Uncles - -• **sha3Uncles**: *string* - -*Defined in [index.ts:352](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L352)* - -___ - -### size - -• **size**: *number* - -*Defined in [index.ts:360](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L360)* - -___ - -### stateRoot - -• **stateRoot**: *string* - -*Defined in [index.ts:355](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L355)* - -___ - -### timestamp - -• **timestamp**: *number* - -*Defined in [index.ts:363](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L363)* - -___ - -### totalDifficulty - -• **totalDifficulty**: *`BigNumber`* - -*Defined in [index.ts:358](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L358)* - -___ - -### transactionsRoot - -• **transactionsRoot**: *string* - -*Defined in [index.ts:354](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L354)* - -___ - -### uncles - -• **uncles**: *string[]* - -*Defined in [index.ts:364](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L364)* - -
- -# Interface: BlockRange - - -## Properties - -### fromBlock - -• **fromBlock**: *[BlockParam](#blockparam)* - -*Defined in [index.ts:743](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L743)* - -___ - -### toBlock - -• **toBlock**: *[BlockParam](#blockparam)* - -*Defined in [index.ts:744](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L744)* - -
- -# Interface: BlockWithoutTransactionData - - -## Properties - -### difficulty - -• **difficulty**: *`BigNumber`* - -*Inherited from [AbstractBlock](#interface-abstractblock).[difficulty](#difficulty)* - -*Defined in [index.ts:357](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L357)* - -___ - -### extraData - -• **extraData**: *string* - -*Inherited from [AbstractBlock](#interface-abstractblock).[extraData](#extradata)* - -*Defined in [index.ts:359](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L359)* - -___ - -### gasLimit - -• **gasLimit**: *number* - -*Inherited from [AbstractBlock](#interface-abstractblock).[gasLimit](#gaslimit)* - -*Defined in [index.ts:361](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L361)* - -___ - -### gasUsed - -• **gasUsed**: *number* - -*Inherited from [AbstractBlock](#interface-abstractblock).[gasUsed](#gasused)* - -*Defined in [index.ts:362](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L362)* - -___ - -### hash - -• **hash**: *string | null* - -*Inherited from [AbstractBlock](#interface-abstractblock).[hash](#hash)* - -*Defined in [index.ts:349](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L349)* - -___ - -### logsBloom - -• **logsBloom**: *string | null* - -*Inherited from [AbstractBlock](#interface-abstractblock).[logsBloom](#logsbloom)* - -*Defined in [index.ts:353](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L353)* - -___ - -### miner - -• **miner**: *string* - -*Inherited from [AbstractBlock](#interface-abstractblock).[miner](#miner)* - -*Defined in [index.ts:356](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L356)* - -___ - -### nonce - -• **nonce**: *string | null* - -*Inherited from [AbstractBlock](#interface-abstractblock).[nonce](#nonce)* - -*Defined in [index.ts:351](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L351)* - -___ - -### number - -• **number**: *number | null* - -*Inherited from [AbstractBlock](#interface-abstractblock).[number](#number)* - -*Defined in [index.ts:348](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L348)* - -___ - -### parentHash - -• **parentHash**: *string* - -*Inherited from [AbstractBlock](#interface-abstractblock).[parentHash](#parenthash)* - -*Defined in [index.ts:350](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L350)* - -___ - -### sha3Uncles - -• **sha3Uncles**: *string* - -*Inherited from [AbstractBlock](#interface-abstractblock).[sha3Uncles](#sha3uncles)* - -*Defined in [index.ts:352](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L352)* - -___ - -### size - -• **size**: *number* - -*Inherited from [AbstractBlock](#interface-abstractblock).[size](#size)* - -*Defined in [index.ts:360](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L360)* - -___ - -### stateRoot - -• **stateRoot**: *string* - -*Inherited from [AbstractBlock](#interface-abstractblock).[stateRoot](#stateroot)* - -*Defined in [index.ts:355](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L355)* - -___ - -### timestamp - -• **timestamp**: *number* - -*Inherited from [AbstractBlock](#interface-abstractblock).[timestamp](#timestamp)* - -*Defined in [index.ts:363](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L363)* - -___ - -### totalDifficulty - -• **totalDifficulty**: *`BigNumber`* - -*Inherited from [AbstractBlock](#interface-abstractblock).[totalDifficulty](#totaldifficulty)* - -*Defined in [index.ts:358](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L358)* - -___ - -### transactions - -• **transactions**: *string[]* - -*Defined in [index.ts:368](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L368)* - -___ - -### transactionsRoot - -• **transactionsRoot**: *string* - -*Inherited from [AbstractBlock](#interface-abstractblock).[transactionsRoot](#transactionsroot)* - -*Defined in [index.ts:354](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L354)* - -___ - -### uncles - -• **uncles**: *string[]* - -*Inherited from [AbstractBlock](#interface-abstractblock).[uncles](#uncles)* - -*Defined in [index.ts:364](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L364)* - -
- -# Interface: BlockWithTransactionData - - -## Properties - -### difficulty - -• **difficulty**: *`BigNumber`* - -*Inherited from [AbstractBlock](#interface-abstractblock).[difficulty](#difficulty)* - -*Defined in [index.ts:357](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L357)* - -___ - -### extraData - -• **extraData**: *string* - -*Inherited from [AbstractBlock](#interface-abstractblock).[extraData](#extradata)* - -*Defined in [index.ts:359](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L359)* - -___ - -### gasLimit - -• **gasLimit**: *number* - -*Inherited from [AbstractBlock](#interface-abstractblock).[gasLimit](#gaslimit)* - -*Defined in [index.ts:361](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L361)* - -___ - -### gasUsed - -• **gasUsed**: *number* - -*Inherited from [AbstractBlock](#interface-abstractblock).[gasUsed](#gasused)* - -*Defined in [index.ts:362](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L362)* - -___ - -### hash - -• **hash**: *string | null* - -*Inherited from [AbstractBlock](#interface-abstractblock).[hash](#hash)* - -*Defined in [index.ts:349](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L349)* - -___ - -### logsBloom - -• **logsBloom**: *string | null* - -*Inherited from [AbstractBlock](#interface-abstractblock).[logsBloom](#logsbloom)* - -*Defined in [index.ts:353](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L353)* - -___ - -### miner - -• **miner**: *string* - -*Inherited from [AbstractBlock](#interface-abstractblock).[miner](#miner)* - -*Defined in [index.ts:356](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L356)* - -___ - -### nonce - -• **nonce**: *string | null* - -*Inherited from [AbstractBlock](#interface-abstractblock).[nonce](#nonce)* - -*Defined in [index.ts:351](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L351)* - -___ - -### number - -• **number**: *number | null* - -*Inherited from [AbstractBlock](#interface-abstractblock).[number](#number)* - -*Defined in [index.ts:348](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L348)* - -___ - -### parentHash - -• **parentHash**: *string* - -*Inherited from [AbstractBlock](#interface-abstractblock).[parentHash](#parenthash)* - -*Defined in [index.ts:350](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L350)* - -___ - -### sha3Uncles - -• **sha3Uncles**: *string* - -*Inherited from [AbstractBlock](#interface-abstractblock).[sha3Uncles](#sha3uncles)* - -*Defined in [index.ts:352](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L352)* - -___ - -### size - -• **size**: *number* - -*Inherited from [AbstractBlock](#interface-abstractblock).[size](#size)* - -*Defined in [index.ts:360](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L360)* - -___ - -### stateRoot - -• **stateRoot**: *string* - -*Inherited from [AbstractBlock](#interface-abstractblock).[stateRoot](#stateroot)* - -*Defined in [index.ts:355](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L355)* - -___ - -### timestamp - -• **timestamp**: *number* - -*Inherited from [AbstractBlock](#interface-abstractblock).[timestamp](#timestamp)* - -*Defined in [index.ts:363](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L363)* - -___ - -### totalDifficulty - -• **totalDifficulty**: *`BigNumber`* - -*Inherited from [AbstractBlock](#interface-abstractblock).[totalDifficulty](#totaldifficulty)* - -*Defined in [index.ts:358](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L358)* - -___ - -### transactions - -• **transactions**: *[Transaction](#class-transaction)[]* - -*Defined in [index.ts:372](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L372)* - -___ - -### transactionsRoot - -• **transactionsRoot**: *string* - -*Inherited from [AbstractBlock](#interface-abstractblock).[transactionsRoot](#transactionsroot)* - -*Defined in [index.ts:354](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L354)* - -___ - -### uncles - -• **uncles**: *string[]* - -*Inherited from [AbstractBlock](#interface-abstractblock).[uncles](#uncles)* - -*Defined in [index.ts:364](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L364)* - -
- -# Interface: CallData - - -## Properties - -### `Optional` data - -• **data**? : *undefined | string* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[data](#optional-data)* - -*Defined in [index.ts:394](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L394)* - -___ - -### `Optional` from - -• **from**? : *undefined | string* - -*Defined in [index.ts:403](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L403)* - -___ - -### `Optional` gas - -• **gas**? : *number | string | `BigNumber`* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[gas](#optional-gas)* - -*Defined in [index.ts:392](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L392)* - -___ - -### `Optional` gasPrice - -• **gasPrice**? : *number | string | `BigNumber`* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[gasPrice](#optional-gasprice)* - -*Defined in [index.ts:393](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L393)* - -___ - -### `Optional` nonce - -• **nonce**? : *undefined | number* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[nonce](#optional-nonce)* - -*Defined in [index.ts:395](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L395)* - -___ - -### `Optional` to - -• **to**? : *undefined | string* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[to](#optional-to)* - -*Defined in [index.ts:390](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L390)* - -___ - -### `Optional` value - -• **value**? : *number | string | `BigNumber`* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[value](#optional-value)* - -*Defined in [index.ts:391](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L391)* - -
- -# Interface: CallTxDataBase - - -## Properties - -### `Optional` data - -• **data**? : *undefined | string* - -*Defined in [index.ts:394](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L394)* - -___ - -### `Optional` gas - -• **gas**? : *number | string | `BigNumber`* - -*Defined in [index.ts:392](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L392)* - -___ - -### `Optional` gasPrice - -• **gasPrice**? : *number | string | `BigNumber`* - -*Defined in [index.ts:393](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L393)* - -___ - -### `Optional` nonce - -• **nonce**? : *undefined | number* - -*Defined in [index.ts:395](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L395)* - -___ - -### `Optional` to - -• **to**? : *undefined | string* - -*Defined in [index.ts:390](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L390)* - -___ - -### `Optional` value - -• **value**? : *number | string | `BigNumber`* - -*Defined in [index.ts:391](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L391)* - -
- -# Interface: CompilerOptions - -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. -useDockerisedSolc: If set to true - sol-compiler will try calling a dockerized installations of solc to achieve faster compilation times. Otherwise and by default - solcjs will be used. Defaults to false. -isOfflineMode: If set to true - sol-compiler will not fetch the list of solc releases from github. It will use the hardcoded list. Defaults to false. -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. -shouldSaveStandardInput: Write the standard JSON input in ${contractsDir}/${contractName}.input.json - - -## Properties - -### `Optional` artifactsDir - -• **artifactsDir**? : *undefined | string* - -*Defined in [index.ts:733](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L733)* - -___ - -### `Optional` compilerSettings - -• **compilerSettings**? : *[CompilerSettings](#class-compilersettings)* - -*Defined in [index.ts:734](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L734)* - -___ - -### `Optional` contracts - -• **contracts**? : *string[] | "*"* - -*Defined in [index.ts:735](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L735)* - -___ - -### `Optional` contractsDir - -• **contractsDir**? : *undefined | string* - -*Defined in [index.ts:732](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L732)* - -___ - -### `Optional` isOfflineMode - -• **isOfflineMode**? : *undefined | false | true* - -*Defined in [index.ts:737](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L737)* - -___ - -### `Optional` shouldSaveStandardInput - -• **shouldSaveStandardInput**? : *undefined | false | true* - -*Defined in [index.ts:739](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L739)* - -___ - -### `Optional` solcVersion - -• **solcVersion**? : *undefined | string* - -*Defined in [index.ts:738](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L738)* - -___ - -### `Optional` useDockerisedSolc - -• **useDockerisedSolc**? : *undefined | false | true* - -*Defined in [index.ts:736](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L736)* - -
- -# Interface: CompilerOpts - - -## Properties - -### name - -• **name**: *"solc"* - -*Defined in [index.ts:656](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L656)* - -___ - -### settings - -• **settings**: *[CompilerSettings](#class-compilersettings)* - -*Defined in [index.ts:658](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L658)* - -___ - -### version - -• **version**: *string* - -*Defined in [index.ts:657](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L657)* - -
- -# Interface: CompilerSettings - - -## Properties - -### `Optional` evmVersion - -• **evmVersion**? : *"homestead" | "tangerineWhistle" | "spuriousDragon" | "byzantium" | "constantinople"* - -*Defined in [index.ts:690](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L690)* - -___ - -### `Optional` libraries - -• **libraries**? : *undefined | object* - -*Defined in [index.ts:692](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L692)* - -___ - -### `Optional` metadata - -• **metadata**? : *[CompilerSettingsMetadata](#class-compilersettingsmetadata)* - -*Defined in [index.ts:691](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L691)* - -___ - -### `Optional` optimizer - -• **optimizer**? : *[OptimizerSettings](#class-optimizersettings)* - -*Defined in [index.ts:689](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L689)* - -___ - -### outputSelection - -• **outputSelection**: *object* - -*Defined in [index.ts:697](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L697)* - -#### Type declaration: - -● \[▪ **fileName**: *string*\]: object - -● \[▪ **contractName**: *string*\]: [OutputField](#outputfield)[] - -___ - -### `Optional` remappings - -• **remappings**? : *string[]* - -*Defined in [index.ts:688](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L688)* - -
- -# Interface: CompilerSettingsMetadata - - -## Properties - -### useLiteralContent - -• **useLiteralContent**: *true* - -*Defined in [index.ts:705](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L705)* - -
- -# Interface: ConstructorAbi - - -## Properties - -### inputs - -• **inputs**: *[DataItem](#class-dataitem)[]* - -*Defined in [index.ts:103](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L103)* - -___ - -### payable - -• **payable**: *boolean* - -*Defined in [index.ts:104](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L104)* - -___ - -### stateMutability - -• **stateMutability**: *[ConstructorStateMutability](#constructorstatemutability)* - -*Defined in [index.ts:105](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L105)* - -___ - -### type - -• **type**: *string* - -*Defined in [index.ts:102](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L102)* - -
- -# Interface: ContractArtifact - -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 -chains: Chain specific information by chain (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 - - -## Properties - -### chains - -• **chains**: *[ContractChains](#class-contractchains)* - -*Defined in [index.ts:677](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L677)* - -___ - -### compiler - -• **compiler**: *[CompilerOpts](#class-compileropts)* - -*Inherited from [ContractVersionData](#interface-contractversiondata).[compiler](#compiler)* - -*Defined in [index.ts:642](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L642)* - -___ - -### compilerOutput - -• **compilerOutput**: *[StandardContractOutput](#class-standardcontractoutput)* - -*Inherited from [ContractVersionData](#interface-contractversiondata).[compilerOutput](#compileroutput)* - -*Defined in [index.ts:652](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L652)* - -___ - -### contractName - -• **contractName**: *string* - -*Defined in [index.ts:676](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L676)* - -___ - -### schemaVersion - -• **schemaVersion**: *string* - -*Defined in [index.ts:675](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L675)* - -___ - -### sourceCodes - -• **sourceCodes**: *object* - -*Inherited from [ContractVersionData](#interface-contractversiondata).[sourceCodes](#sourcecodes)* - -*Defined in [index.ts:648](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L648)* - -#### Type declaration: - -● \[▪ **sourceName**: *string*\]: string - -___ - -### sourceTreeHashHex - -• **sourceTreeHashHex**: *string* - -*Inherited from [ContractVersionData](#interface-contractversiondata).[sourceTreeHashHex](#sourcetreehashhex)* - -*Defined in [index.ts:651](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L651)* - -___ - -### sources - -• **sources**: *object* - -*Inherited from [ContractVersionData](#interface-contractversiondata).[sources](#sources)* - -*Defined in [index.ts:643](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L643)* - -#### Type declaration: - -● \[▪ **sourceName**: *string*\]: object - -
- -# Interface: ContractChainData - - -## Properties - -### address - -• **address**: *string* - -*Defined in [index.ts:555](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L555)* - -___ - -Args - -• **constructorArgs**: *string* - -*Defined in [index.ts:559](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L559)* - -___ - -### links - -• **links**: *object* - -*Defined in [index.ts:556](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L556)* - -#### Type declaration: - -● \[▪ **linkName**: *string*\]: string - -
- -# Interface: ContractChains - - -## Hierarchy - -* **ContractVersionData** - - * [ContractArtifact](#class-contractartifact) - - -## Properties - -### compiler - -• **compiler**: *[CompilerOpts](#class-compileropts)* - -*Defined in [index.ts:642](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L642)* - -___ - -### compilerOutput - -• **compilerOutput**: *[StandardContractOutput](#class-standardcontractoutput)* - -*Defined in [index.ts:652](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L652)* - -___ - -### sourceCodes - -• **sourceCodes**: *object* - -*Defined in [index.ts:648](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L648)* - -#### Type declaration: - -● \[▪ **sourceName**: *string*\]: string - -___ - -### sourceTreeHashHex - -• **sourceTreeHashHex**: *string* - -*Defined in [index.ts:651](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L651)* - -___ - -### sources - -• **sources**: *object* - -*Defined in [index.ts:643](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L643)* - -#### Type declaration: - -● \[▪ **sourceName**: *string*\]: object - -
- -# Interface: DataItem - - -## Properties - -### `Optional` components - -• **components**? : *[DataItem](#class-dataitem)[]* - -*Defined in [index.ts:138](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L138)* - -___ - -### `Optional` internalType - -• **internalType**? : *undefined | string* - -*Defined in [index.ts:137](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L137)* - -___ - -### name - -• **name**: *string* - -*Defined in [index.ts:135](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L135)* - -___ - -### type - -• **type**: *string* - -*Defined in [index.ts:136](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L136)* - -
- -# Interface: DecodedLogArgs - - -## Type parameters - -▪ **A** - - -## Properties - -### address - -• **address**: *string* - -*Inherited from [LogEntry](#interface-logentry).[address](#address)* - -*Defined in [index.ts:435](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L435)* - -___ - -### args - -• **args**: *`A`* - -*Defined in [index.ts:418](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L418)* - -___ - -### blockHash - -• **blockHash**: *string | null* - -*Inherited from [LogEntry](#interface-logentry).[blockHash](#blockhash)* - -*Defined in [index.ts:433](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L433)* - -___ - -### blockNumber - -• **blockNumber**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[blockNumber](#blocknumber)* - -*Defined in [index.ts:434](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L434)* - -___ - -### data - -• **data**: *string* - -*Inherited from [LogEntry](#interface-logentry).[data](#data)* - -*Defined in [index.ts:436](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L436)* - -___ - -### event - -• **event**: *string* - -*Defined in [index.ts:417](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L417)* - -___ - -### logIndex - -• **logIndex**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[logIndex](#logindex)* - -*Defined in [index.ts:430](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L430)* - -___ - -### topics - -• **topics**: *string[]* - -*Inherited from [LogEntry](#interface-logentry).[topics](#topics)* - -*Defined in [index.ts:437](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L437)* - -___ - -### transactionHash - -• **transactionHash**: *string* - -*Inherited from [LogEntry](#interface-logentry).[transactionHash](#transactionhash)* - -*Defined in [index.ts:432](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L432)* - -___ - -### transactionIndex - -• **transactionIndex**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[transactionIndex](#transactionindex)* - -*Defined in [index.ts:431](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L431)* - -
- -# Interface: DecodedLogEntryEvent <**A**> - -## Type parameters - -▪ **A** - - -## Properties - -### address - -• **address**: *string* - -*Inherited from [LogEntry](#interface-logentry).[address](#address)* - -*Defined in [index.ts:435](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L435)* - -___ - -### args - -• **args**: *`A`* - -*Inherited from [DecodedLogEntry](#interface-decodedlogentry).[args](#args)* - -*Defined in [index.ts:418](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L418)* - -___ - -### blockHash - -• **blockHash**: *string | null* - -*Inherited from [LogEntry](#interface-logentry).[blockHash](#blockhash)* - -*Defined in [index.ts:433](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L433)* - -___ - -### blockNumber - -• **blockNumber**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[blockNumber](#blocknumber)* - -*Defined in [index.ts:434](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L434)* - -___ - -### data - -• **data**: *string* - -*Inherited from [LogEntry](#interface-logentry).[data](#data)* - -*Defined in [index.ts:436](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L436)* - -___ - -### event - -• **event**: *string* - -*Inherited from [DecodedLogEntry](#interface-decodedlogentry).[event](#event)* - -*Defined in [index.ts:417](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L417)* - -___ - -### logIndex - -• **logIndex**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[logIndex](#logindex)* - -*Defined in [index.ts:430](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L430)* - -___ - -### removed - -• **removed**: *boolean* - -*Defined in [index.ts:422](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L422)* - -___ - -### topics - -• **topics**: *string[]* - -*Inherited from [LogEntry](#interface-logentry).[topics](#topics)* - -*Defined in [index.ts:437](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L437)* - -___ - -### transactionHash - -• **transactionHash**: *string* - -*Inherited from [LogEntry](#interface-logentry).[transactionHash](#transactionhash)* - -*Defined in [index.ts:432](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L432)* - -___ - -### transactionIndex - -• **transactionIndex**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[transactionIndex](#transactionindex)* - -*Defined in [index.ts:431](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L431)* - -
- -# Interface: DevdocOutput - - -## Properties - -### `Optional` author - -• **author**? : *undefined | string* - -*Defined in [index.ts:629](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L629)* - -___ - -### methods - -• **methods**: *object* - -*Defined in [index.ts:630](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L630)* - -#### Type declaration: - -● \[▪ **signature**: *string*\]: object - -___ - -### `Optional` title - -• **title**? : *undefined | string* - -*Defined in [index.ts:628](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L628)* - -
- -# Interface: EIP1193Provider - - -## Properties - -### isEIP1193 - -• **isEIP1193**: *boolean* - -*Defined in [index.ts:73](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L73)* - -## Methods - -### on - -▸ **on**(`event`: [EIP1193Event](#eip1193event), `listener`: function): *this* - -*Defined in [index.ts:75](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L75)* - -**Parameters:** - -▪ **event**: *[EIP1193Event](#eip1193event)* - -▪ **listener**: *function* - -▸ (`result`: any): *void* - -**Parameters:** - -Name | Type | ------- | ------ | -`result` | any | - -**Returns:** *this* - -___ - -### send - -▸ **send**(`method`: string, `params?`: any[]): *`Promise`* - -*Defined in [index.ts:74](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L74)* - -**Parameters:** - -Name | Type | ------- | ------ | -`method` | string | -`params?` | any[] | - -**Returns:** *`Promise`* - -
- -# Interface: EventAbi - - -## Properties - -### anonymous - -• **anonymous**: *boolean* - -*Defined in [index.ts:131](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L131)* - -___ - -### inputs - -• **inputs**: *[EventParameter](#class-eventparameter)[]* - -*Defined in [index.ts:130](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L130)* - -___ - -### name - -• **name**: *string* - -*Defined in [index.ts:129](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L129)* - -___ - -### type - -• **type**: *string* - -*Defined in [index.ts:128](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L128)* - -
- -# Interface: EventParameter - - -## Properties - -### `Optional` components - -• **components**? : *[DataItem](#class-dataitem)[]* - -*Inherited from [DataItem](#interface-dataitem).[components](#optional-components)* - -*Defined in [index.ts:138](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L138)* - -___ - -### indexed - -• **indexed**: *boolean* - -*Defined in [index.ts:116](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L116)* - -___ - -### `Optional` internalType - -• **internalType**? : *undefined | string* - -*Inherited from [DataItem](#interface-dataitem).[internalType](#optional-internaltype)* - -*Defined in [index.ts:137](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L137)* - -___ - -### name - -• **name**: *string* - -*Inherited from [DataItem](#interface-dataitem).[name](#name)* - -*Defined in [index.ts:135](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L135)* - -___ - -### type - -• **type**: *string* - -*Inherited from [DataItem](#interface-dataitem).[type](#type)* - -*Defined in [index.ts:136](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L136)* - -
- -# Interface: EvmBytecodeOutput - - -## Properties - -### object - -• **object**: *string* - -*Defined in [index.ts:623](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L623)* - -___ - -### sourceMap - -• **sourceMap**: *string* - -*Defined in [index.ts:624](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L624)* - -
- -# Interface: EvmOutput - - -## Properties - -### bytecode - -• **bytecode**: *[EvmBytecodeOutput](#class-evmbytecodeoutput)* - -*Defined in [index.ts:618](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L618)* - -___ - -### deployedBytecode - -• **deployedBytecode**: *[EvmBytecodeOutput](#class-evmbytecodeoutput)* - -*Defined in [index.ts:619](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L619)* - -
- -# Interface: FallbackAbi - - -## Properties - -### payable - -• **payable**: *boolean* - -*Defined in [index.ts:112](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L112)* - -___ - -### type - -• **type**: *string* - -*Defined in [index.ts:111](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L111)* - -
- -# Interface: FilterObject - - -## Properties - -### `Optional` address - -• **address**? : *undefined | string* - -*Defined in [index.ts:410](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L410)* - -___ - -### `Optional` blockHash - -• **blockHash**? : *undefined | string* - -*Defined in [index.ts:409](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L409)* - -___ - -### `Optional` fromBlock - -• **fromBlock**? : *number | string* - -*Defined in [index.ts:407](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L407)* - -___ - -### `Optional` toBlock - -• **toBlock**? : *number | string* - -*Defined in [index.ts:408](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L408)* - -___ - -### `Optional` topics - -• **topics**? : *[LogTopic](#logtopic)[]* - -*Defined in [index.ts:411](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L411)* - -
- -# Enumeration: AbiType - - -## Enumeration members - -### Constructor - -• **Constructor**: = "constructor" - -*Defined in [index.ts:464](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L464)* - -___ - -### Event - -• **Event**: = "event" - -*Defined in [index.ts:465](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L465)* - -___ - -### Fallback - -• **Fallback**: = "fallback" - -*Defined in [index.ts:466](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L466)* - -___ - -### Function - -• **Function**: = "function" - -*Defined in [index.ts:463](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L463)* - -
- -# Interface: GeneratedCompilerOptions - - -## Properties - -### name - -• **name**: *"solc"* - -*Defined in [index.ts:681](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L681)* - -___ - -### settings - -• **settings**: *[CompilerSettings](#class-compilersettings)* - -*Defined in [index.ts:683](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L683)* - -___ - -### version - -• **version**: *string* - -*Defined in [index.ts:682](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L682)* - -
- -# Interface: JSONRPCRequestPayload - - -## Properties - -### id - -• **id**: *number* - -*Defined in [index.ts:331](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L331)* - -___ - -### jsonrpc - -• **jsonrpc**: *string* - -*Defined in [index.ts:332](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L332)* - -___ - -### method - -• **method**: *string* - -*Defined in [index.ts:330](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L330)* - -___ - -### params - -• **params**: *any[]* - -*Defined in [index.ts:329](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L329)* - -
- -# Interface: JSONRPCResponseError - - -## Properties - -### code - -• **code**: *number* - -*Defined in [index.ts:337](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L337)* - -___ - -### message - -• **message**: *string* - -*Defined in [index.ts:336](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L336)* - -
- -# Interface: JSONRPCResponsePayload - - -## Properties - -### `Optional` error - -• **error**? : *[JSONRPCResponseError](#class-jsonrpcresponseerror)* - -*Defined in [index.ts:344](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L344)* - -___ - -### id - -• **id**: *number* - -*Defined in [index.ts:342](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L342)* - -___ - -### jsonrpc - -• **jsonrpc**: *string* - -*Defined in [index.ts:343](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L343)* - -___ - -### result - -• **result**: *any* - -*Defined in [index.ts:341](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L341)* - -
- -# Interface: LogEntry - - -## Properties - -### address - -• **address**: *string* - -*Defined in [index.ts:435](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L435)* - -___ - -### blockHash - -• **blockHash**: *string | null* - -*Defined in [index.ts:433](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L433)* - -___ - -### blockNumber - -• **blockNumber**: *number | null* - -*Defined in [index.ts:434](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L434)* - -___ - -### data - -• **data**: *string* - -*Defined in [index.ts:436](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L436)* - -___ - -### logIndex - -• **logIndex**: *number | null* - -*Defined in [index.ts:430](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L430)* - -___ - -### topics - -• **topics**: *string[]* - -*Defined in [index.ts:437](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L437)* - -___ - -### transactionHash - -• **transactionHash**: *string* - -*Defined in [index.ts:432](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L432)* - -___ - -### transactionIndex - -• **transactionIndex**: *number | null* - -*Defined in [index.ts:431](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L431)* - -
- -# Interface: LogEntryEvent - - -## Properties - -### address - -• **address**: *string* - -*Inherited from [LogEntry](#interface-logentry).[address](#address)* - -*Defined in [index.ts:435](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L435)* - -___ - -### blockHash - -• **blockHash**: *string | null* - -*Inherited from [LogEntry](#interface-logentry).[blockHash](#blockhash)* - -*Defined in [index.ts:433](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L433)* - -___ - -### blockNumber - -• **blockNumber**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[blockNumber](#blocknumber)* - -*Defined in [index.ts:434](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L434)* - -___ - -### data - -• **data**: *string* - -*Inherited from [LogEntry](#interface-logentry).[data](#data)* - -*Defined in [index.ts:436](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L436)* - -___ - -### logIndex - -• **logIndex**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[logIndex](#logindex)* - -*Defined in [index.ts:430](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L430)* - -___ - -### removed - -• **removed**: *boolean* - -*Defined in [index.ts:426](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L426)* - -___ - -### topics - -• **topics**: *string[]* - -*Inherited from [LogEntry](#interface-logentry).[topics](#topics)* - -*Defined in [index.ts:437](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L437)* - -___ - -### transactionHash - -• **transactionHash**: *string* - -*Inherited from [LogEntry](#interface-logentry).[transactionHash](#transactionhash)* - -*Defined in [index.ts:432](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L432)* - -___ - -### transactionIndex - -• **transactionIndex**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[transactionIndex](#transactionindex)* - -*Defined in [index.ts:431](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L431)* - -
- -# Interface: LogWithDecodedArgs <**ArgsType**> - -## Type parameters - -▪ **ArgsType**: *[DecodedLogArgs](#class-decodedlogargs)* - - -## Properties - -### address - -• **address**: *string* - -*Inherited from [LogEntry](#interface-logentry).[address](#address)* - -*Defined in [index.ts:435](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L435)* - -___ - -### args - -• **args**: *`ArgsType`* - -*Inherited from [DecodedLogEntry](#interface-decodedlogentry).[args](#args)* - -*Defined in [index.ts:418](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L418)* - -___ - -### blockHash - -• **blockHash**: *string | null* - -*Inherited from [LogEntry](#interface-logentry).[blockHash](#blockhash)* - -*Defined in [index.ts:433](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L433)* - -___ - -### blockNumber - -• **blockNumber**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[blockNumber](#blocknumber)* - -*Defined in [index.ts:434](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L434)* - -___ - -### data - -• **data**: *string* - -*Inherited from [LogEntry](#interface-logentry).[data](#data)* - -*Defined in [index.ts:436](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L436)* - -___ - -### event - -• **event**: *string* - -*Inherited from [DecodedLogEntry](#interface-decodedlogentry).[event](#event)* - -*Defined in [index.ts:417](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L417)* - -___ - -### logIndex - -• **logIndex**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[logIndex](#logindex)* - -*Defined in [index.ts:430](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L430)* - -___ - -### topics - -• **topics**: *string[]* - -*Inherited from [LogEntry](#interface-logentry).[topics](#topics)* - -*Defined in [index.ts:437](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L437)* - -___ - -### transactionHash - -• **transactionHash**: *string* - -*Inherited from [LogEntry](#interface-logentry).[transactionHash](#transactionhash)* - -*Defined in [index.ts:432](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L432)* - -___ - -### transactionIndex - -• **transactionIndex**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[transactionIndex](#transactionindex)* - -*Defined in [index.ts:431](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L431)* - -
- -# Interface: MethodAbi - - -## Properties - -### constant - -• **constant**: *boolean* - -*Defined in [index.ts:94](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L94)* - -___ - -### inputs - -• **inputs**: *[DataItem](#class-dataitem)[]* - -*Defined in [index.ts:92](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L92)* - -___ - -### name - -• **name**: *string* - -*Defined in [index.ts:91](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L91)* - -___ - -### outputs - -• **outputs**: *[DataItem](#class-dataitem)[]* - -*Defined in [index.ts:93](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L93)* - -___ - -### payable - -• **payable**: *boolean* - -*Defined in [index.ts:96](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L96)* - -___ - -### stateMutability - -• **stateMutability**: *[StateMutability](#statemutability)* - -*Defined in [index.ts:95](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L95)* - -___ - -### type - -• **type**: *string* - -*Defined in [index.ts:90](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L90)* - -
- -# Interface: OptimizerSettings - - -## Properties - -### enabled - -• **enabled**: *boolean* - -*Defined in [index.ts:709](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L709)* - -___ - -### `Optional` runs - -• **runs**? : *undefined | number* - -*Defined in [index.ts:710](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L710)* - -
- -# Interface: Provider - - -## Methods - -### sendAsync - -▸ **sendAsync**(`payload`: [JSONRPCRequestPayload](_index_.jsonrpcrequestpayload.md), `callback`: [JSONRPCErrorCallback](#jsonrpcerrorcallback)): *void* - -*Defined in [index.ts:20](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L20)* - -**Parameters:** - -Name | Type | ------- | ------ | -`payload` | [JSONRPCRequestPayload](#class-jsonrpcrequestpayload) | -`callback` | [JSONRPCErrorCallback](#jsonrpcerrorcallback) | - -**Returns:** *void* - -
- -# Interface: RawLogEntry - - -## Properties - -### address - -• **address**: *string* - -*Defined in [index.ts:492](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L492)* - -___ - -### blockHash - -• **blockHash**: *string | null* - -*Defined in [index.ts:490](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L490)* - -___ - -### blockNumber - -• **blockNumber**: *string | null* - -*Defined in [index.ts:491](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L491)* - -___ - -### data - -• **data**: *string* - -*Defined in [index.ts:493](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L493)* - -___ - -### logIndex - -• **logIndex**: *string | null* - -*Defined in [index.ts:487](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L487)* - -___ - -### topics - -• **topics**: *string[]* - -*Defined in [index.ts:494](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L494)* - -___ - -### transactionHash - -• **transactionHash**: *string* - -*Defined in [index.ts:489](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L489)* - -___ - -### transactionIndex - -• **transactionIndex**: *string | null* - -*Defined in [index.ts:488](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L488)* - -
- -# Interface: RevertErrorAbi - - -## Properties - -### `Optional` arguments - -• **arguments**? : *[DataItem](#class-dataitem)[]* - -*Defined in [index.ts:122](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L122)* - -___ - -### name - -• **name**: *string* - -*Defined in [index.ts:121](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L121)* - -___ - -### type - -• **type**: *"error"* - -*Defined in [index.ts:120](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L120)* - -
- -# Interface: SolcError - - -## Properties - -### component - -• **component**: *"general" | "ewasm"* - -*Defined in [index.ts:605](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L605)* - -___ - -### `Optional` formattedMessage - -• **formattedMessage**? : *undefined | string* - -*Defined in [index.ts:608](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L608)* - -___ - -### message - -• **message**: *string* - -*Defined in [index.ts:607](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L607)* - -___ - -### severity - -• **severity**: *[ErrorSeverity](#errorseverity)* - -*Defined in [index.ts:606](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L606)* - -___ - -### `Optional` sourceLocation - -• **sourceLocation**? : *[SourceLocation](#class-sourcelocation)* - -*Defined in [index.ts:603](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L603)* - -___ - -### type - -• **type**: *[ErrorType](#errortype)* - -*Defined in [index.ts:604](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L604)* - -
- -# Interface: Source - - -## Properties - -### id - -• **id**: *number* - -*Defined in [index.ts:714](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L714)* - -
- -# Interface: SourceLocation - - -## Properties - -### end - -• **end**: *number* - -*Defined in [index.ts:614](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L614)* - -___ - -### file - -• **file**: *string* - -*Defined in [index.ts:612](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L612)* - -___ - -### start - -• **start**: *number* - -*Defined in [index.ts:613](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L613)* - -
- -# Interface: StandardContractOutput - - -## Properties - -### abi - -• **abi**: *[ContractAbi](#contractabi)* - -*Defined in [index.ts:565](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L565)* - -___ - -### `Optional` devdoc - -• **devdoc**? : *[DevdocOutput](#class-devdocoutput)* - -*Defined in [index.ts:567](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L567)* - -___ - -### evm - -• **evm**: *[EvmOutput](#class-evmoutput)* - -*Defined in [index.ts:566](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L566)* - -
- -# Interface: StandardOutput - - -## Properties - -### contracts - -• **contracts**: *object* - -*Defined in [index.ts:579](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L579)* - -#### Type declaration: - -● \[▪ **fileName**: *string*\]: object - -● \[▪ **contractName**: *string*\]: [StandardContractOutput](#class-standardcontractoutput) - -___ - -### errors - -• **errors**: *[SolcError](#class-solcerror)[]* - -*Defined in [index.ts:571](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L571)* - -___ - -### sources - -• **sources**: *object* - -*Defined in [index.ts:572](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L572)* - -#### Type declaration: - -● \[▪ **fileName**: *string*\]: object - -
- -# Interface: StructLog - - -## Properties - -### depth - -• **depth**: *number* - -*Defined in [index.ts:294](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L294)* - -___ - -### error - -• **error**: *string* - -*Defined in [index.ts:295](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L295)* - -___ - -### gas - -• **gas**: *number* - -*Defined in [index.ts:296](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L296)* - -___ - -### gasCost - -• **gasCost**: *number* - -*Defined in [index.ts:297](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L297)* - -___ - -### memory - -• **memory**: *string[]* - -*Defined in [index.ts:298](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L298)* - -___ - -### op - -• **op**: *[OpCode](#enumeration-opcode)* - -*Defined in [index.ts:299](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L299)* - -___ - -### pc - -• **pc**: *number* - -*Defined in [index.ts:300](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L300)* - -___ - -### stack - -• **stack**: *string[]* - -*Defined in [index.ts:301](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L301)* - -___ - -### storage - -• **storage**: *object* - -*Defined in [index.ts:302](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L302)* - -#### Type declaration: - -● \[▪ **location**: *string*\]: string - -
- -# Interface: TraceParams - - -## Properties - -### `Optional` disableMemory - -• **disableMemory**? : *undefined | false | true* - -*Defined in [index.ts:519](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L519)* - -___ - -### `Optional` disableStack - -• **disableStack**? : *undefined | false | true* - -*Defined in [index.ts:520](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L520)* - -___ - -### `Optional` disableStorage - -• **disableStorage**? : *undefined | false | true* - -*Defined in [index.ts:521](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L521)* - -___ - -### `Optional` timeout - -• **timeout**? : *undefined | string* - -*Defined in [index.ts:523](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L523)* - -___ - -### `Optional` tracer - -• **tracer**? : *undefined | string* - -*Defined in [index.ts:522](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L522)* - -
- -# Interface: Transaction - - -## Properties - -### blockHash - -• **blockHash**: *string | null* - -*Defined in [index.ts:378](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L378)* - -___ - -### blockNumber - -• **blockNumber**: *number | null* - -*Defined in [index.ts:379](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L379)* - -___ - -### from - -• **from**: *string* - -*Defined in [index.ts:381](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L381)* - -___ - -### gas - -• **gas**: *number* - -*Defined in [index.ts:385](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L385)* - -___ - -### gasPrice - -• **gasPrice**: *`BigNumber`* - -*Defined in [index.ts:384](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L384)* - -___ - -### hash - -• **hash**: *string* - -*Defined in [index.ts:376](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L376)* - -___ - -### input - -• **input**: *string* - -*Defined in [index.ts:386](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L386)* - -___ - -### nonce - -• **nonce**: *number* - -*Defined in [index.ts:377](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L377)* - -___ - -### to - -• **to**: *string | null* - -*Defined in [index.ts:382](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L382)* - -___ - -### transactionIndex - -• **transactionIndex**: *number | null* - -*Defined in [index.ts:380](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L380)* - -___ - -### value - -• **value**: *`BigNumber`* - -*Defined in [index.ts:383](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L383)* - -
- -# Interface: TransactionReceipt - - -## Properties - -### blockHash - -• **blockHash**: *string* - -*Defined in [index.ts:449](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L449)* - -___ - -### blockNumber - -• **blockNumber**: *number* - -*Defined in [index.ts:450](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L450)* - -___ - -### contractAddress - -• **contractAddress**: *string | null* - -*Defined in [index.ts:458](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L458)* - -___ - -### cumulativeGasUsed - -• **cumulativeGasUsed**: *number* - -*Defined in [index.ts:456](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L456)* - -___ - -### from - -• **from**: *string* - -*Defined in [index.ts:453](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L453)* - -___ - -### gasUsed - -• **gasUsed**: *number* - -*Defined in [index.ts:457](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L457)* - -___ - -### logs - -• **logs**: *[LogEntry](#class-logentry)[]* - -*Defined in [index.ts:459](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L459)* - -___ - -### status - -• **status**: *[TransactionReceiptStatus](#transactionreceiptstatus)* - -*Defined in [index.ts:455](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L455)* - -___ - -### to - -• **to**: *string* - -*Defined in [index.ts:454](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L454)* - -___ - -### transactionHash - -• **transactionHash**: *string* - -*Defined in [index.ts:451](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L451)* - -___ - -### transactionIndex - -• **transactionIndex**: *number* - -*Defined in [index.ts:452](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L452)* - -
- -# Interface: TransactionReceiptWithDecodedLogs - -Contains the logs returned by a TransactionReceipt. We attempt to decode the -logs using AbiDecoder. If we have the logs corresponding ABI, we decode it, -otherwise we don't. - - -## Properties - -### blockHash - -• **blockHash**: *string* - -*Inherited from [TransactionReceipt](#interface-transactionreceipt).[blockHash](#blockhash)* - -*Defined in [index.ts:449](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L449)* - -___ - -### blockNumber - -• **blockNumber**: *number* - -*Inherited from [TransactionReceipt](#interface-transactionreceipt).[blockNumber](#blocknumber)* - -*Defined in [index.ts:450](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L450)* - -___ - -### contractAddress - -• **contractAddress**: *string | null* - -*Inherited from [TransactionReceipt](#interface-transactionreceipt).[contractAddress](#contractaddress)* - -*Defined in [index.ts:458](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L458)* - -___ - -### cumulativeGasUsed - -• **cumulativeGasUsed**: *number* - -*Inherited from [TransactionReceipt](#interface-transactionreceipt).[cumulativeGasUsed](#cumulativegasused)* - -*Defined in [index.ts:456](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L456)* - -___ - -### from - -• **from**: *string* - -*Inherited from [TransactionReceipt](#interface-transactionreceipt).[from](#from)* - -*Defined in [index.ts:453](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L453)* - -___ - -### gasUsed - -• **gasUsed**: *number* - -*Inherited from [TransactionReceipt](#interface-transactionreceipt).[gasUsed](#gasused)* - -*Defined in [index.ts:457](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L457)* - -___ - -### logs - -• **logs**: *`Array | LogEntry>`* - -*Overrides [TransactionReceipt](_index_.transactionreceipt.md).[logs](#logs)* - -*Defined in [index.ts:515](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L515)* - -___ - -### status - -• **status**: *[TransactionReceiptStatus](#transactionreceiptstatus)* - -*Inherited from [TransactionReceipt](#interface-transactionreceipt).[status](#status)* - -*Defined in [index.ts:455](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L455)* - -___ - -### to - -• **to**: *string* - -*Inherited from [TransactionReceipt](#interface-transactionreceipt).[to](#to)* - -*Defined in [index.ts:454](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L454)* - -___ - -### transactionHash - -• **transactionHash**: *string* - -*Inherited from [TransactionReceipt](#interface-transactionreceipt).[transactionHash](#transactionhash)* - -*Defined in [index.ts:451](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L451)* - -___ - -### transactionIndex - -• **transactionIndex**: *number* - -*Inherited from [TransactionReceipt](#interface-transactionreceipt).[transactionIndex](#transactionindex)* - -*Defined in [index.ts:452](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L452)* - -
- -# Interface: TransactionTrace - - -## Properties - -### gas - -• **gas**: *number* - -*Defined in [index.ts:306](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L306)* - -___ - -### returnValue - -• **returnValue**: *any* - -*Defined in [index.ts:307](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L307)* - -___ - -### structLogs - -• **structLogs**: *[StructLog](#class-structlog)[]* - -*Defined in [index.ts:308](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L308)* - -
- -# Interface: TupleDataItem - - -## Properties - -### components - -• **components**: *[DataItem](#class-dataitem)[]* - -*Overrides [DataItem](_index_.dataitem.md).[components](#optional-components)* - -*Defined in [index.ts:142](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L142)* - -___ - -### `Optional` internalType - -• **internalType**? : *undefined | string* - -*Inherited from [DataItem](#interface-dataitem).[internalType](#optional-internaltype)* - -*Defined in [index.ts:137](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L137)* - -___ - -### name - -• **name**: *string* - -*Inherited from [DataItem](#interface-dataitem).[name](#name)* - -*Defined in [index.ts:135](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L135)* - -___ - -### type - -• **type**: *string* - -*Inherited from [DataItem](#interface-dataitem).[type](#type)* - -*Defined in [index.ts:136](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L136)* - -
- -# Interface: TxData - - -## Properties - -### `Optional` data - -• **data**? : *undefined | string* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[data](#optional-data)* - -*Defined in [index.ts:394](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L394)* - -___ - -### from - -• **from**: *string* - -*Defined in [index.ts:399](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L399)* - -___ - -### `Optional` gas - -• **gas**? : *number | string | `BigNumber`* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[gas](#optional-gas)* - -*Defined in [index.ts:392](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L392)* - -___ - -### `Optional` gasPrice - -• **gasPrice**? : *number | string | `BigNumber`* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[gasPrice](#optional-gasprice)* - -*Defined in [index.ts:393](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L393)* - -___ - -### `Optional` nonce - -• **nonce**? : *undefined | number* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[nonce](#optional-nonce)* - -*Defined in [index.ts:395](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L395)* - -___ - -### `Optional` to - -• **to**? : *undefined | string* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[to](#optional-to)* - -*Defined in [index.ts:390](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L390)* - -___ - -### `Optional` value - -• **value**? : *number | string | `BigNumber`* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[value](#optional-value)* - -*Defined in [index.ts:391](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L391)* - -
- -# Interface: TxDataPayable - - -## Properties - -### `Optional` data - -• **data**? : *undefined | string* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[data](#optional-data)* - -*Defined in [index.ts:394](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L394)* - -___ - -### from - -• **from**: *string* - -*Inherited from [TxData](#interface-txdata).[from](#from)* - -*Defined in [index.ts:399](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L399)* - -___ - -### `Optional` gas - -• **gas**? : *number | string | `BigNumber`* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[gas](#optional-gas)* - -*Defined in [index.ts:392](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L392)* - -___ - -### `Optional` gasPrice - -• **gasPrice**? : *number | string | `BigNumber`* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[gasPrice](#optional-gasprice)* - -*Defined in [index.ts:393](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L393)* - -___ - -### `Optional` nonce - -• **nonce**? : *undefined | number* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[nonce](#optional-nonce)* - -*Defined in [index.ts:395](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L395)* - -___ - -### `Optional` to - -• **to**? : *undefined | string* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[to](#optional-to)* - -*Defined in [index.ts:390](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L390)* - -___ - -### `Optional` value - -• **value**? : *`BigNumber`* - -*Overrides [CallTxDataBase](_index_.calltxdatabase.md).[value](#optional-value)* - -*Defined in [index.ts:443](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L443)* - -
- -# Interface: Web3JsV1Provider - -Web3.js version 1 provider interface -This provider interface was implemented in the pre-1.0Beta releases for Web3.js. -This interface allowed sending synchonous requests, support for which was later dropped. - - -## Methods - -### send - -▸ **send**(`payload`: [JSONRPCRequestPayload](_index_.jsonrpcrequestpayload.md)): *[JSONRPCResponsePayload](#class-jsonrpcresponsepayload)* - -*Defined in [index.ts:45](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L45)* - -**Parameters:** - -Name | Type | ------- | ------ | -`payload` | [JSONRPCRequestPayload](#class-jsonrpcrequestpayload) | - -**Returns:** *[JSONRPCResponsePayload](#class-jsonrpcresponsepayload)* - -___ - -### sendAsync - -▸ **sendAsync**(`payload`: [JSONRPCRequestPayload](_index_.jsonrpcrequestpayload.md), `callback`: [JSONRPCErrorCallback](#jsonrpcerrorcallback)): *void* - -*Defined in [index.ts:44](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L44)* - -**Parameters:** - -Name | Type | ------- | ------ | -`payload` | [JSONRPCRequestPayload](#class-jsonrpcrequestpayload) | -`callback` | [JSONRPCErrorCallback](#jsonrpcerrorcallback) | - -**Returns:** *void* - -
- -# Interface: Web3JsV2Provider - -Web3.js version 2 provider interface -This provider interface was used in a couple of Web3.js 1.0 beta releases -before the first attempts to conform to EIP1193 - - -## Methods - -### send - -▸ **send**(`payload`: [JSONRPCRequestPayload](_index_.jsonrpcrequestpayload.md), `callback`: [JSONRPCErrorCallback](#jsonrpcerrorcallback)): *void* - -*Defined in [index.ts:54](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L54)* - -**Parameters:** - -Name | Type | ------- | ------ | -`payload` | [JSONRPCRequestPayload](#class-jsonrpcrequestpayload) | -`callback` | [JSONRPCErrorCallback](#jsonrpcerrorcallback) | - -**Returns:** *void* - -
- -# Interface: Web3JsV3Provider - -Web3.js version 3 provider interface -This provider interface was implemented with the hopes for conforming to the EIP1193 spec, -however it does not conform entirely. - - -## Methods - -### send - -▸ **send**(`method`: string, `params?`: any[]): *`Promise`* - -*Defined in [index.ts:63](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L63)* - -**Parameters:** - -Name | Type | ------- | ------ | -`method` | string | -`params?` | any[] | - -**Returns:** *`Promise`* - -
- -# Interface: ZeroExProvider - -The interface for the provider used internally by 0x libraries -Any property we use from any SupportedProvider should we explicitly -add here - - -## Properties - -### `Optional` isMetaMask - -• **isMetaMask**? : *undefined | false | true* - -*Defined in [index.ts:31](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L31)* - -___ - -### `Optional` isParity - -• **isParity**? : *undefined | false | true* - -*Defined in [index.ts:32](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L32)* - -___ - -### `Optional` isZeroExProvider - -• **isZeroExProvider**? : *undefined | false | true* - -*Defined in [index.ts:30](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L30)* - -## Methods - -### `Optional` enable - -▸ **enable**(): *`Promise`* - -*Defined in [index.ts:34](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L34)* - -**Returns:** *`Promise`* - -___ - -### sendAsync - -▸ **sendAsync**(`payload`: [JSONRPCRequestPayload](_index_.jsonrpcrequestpayload.md), `callback`: [JSONRPCErrorCallback](#jsonrpcerrorcallback)): *void* - -*Defined in [index.ts:35](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L35)* - -**Parameters:** - -Name | Type | ------- | ------ | -`payload` | [JSONRPCRequestPayload](#class-jsonrpcrequestpayload) | -`callback` | [JSONRPCErrorCallback](#jsonrpcerrorcallback) | - -**Returns:** *void* - -___ - -### `Optional` stop - -▸ **stop**(): *void* - -*Defined in [index.ts:33](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L33)* - -**Returns:** *void* - -
- - - - -## Type aliases - -### AbiDefinition - -Ƭ **AbiDefinition**: *[FunctionAbi](_index_.md#functionabi) | [EventAbi](#interface-eventabi) | [RevertErrorAbi](#interface-reverterrorabi)* - -*Defined in [index.ts:80](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L80)* - -___ - -### BlockParam - -Ƭ **BlockParam**: *[BlockParamLiteral](#enumeration-blockparamliteral) | number* - -*Defined in [index.ts:484](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L484)* - -___ - -### ConstructorStateMutability - -Ƭ **ConstructorStateMutability**: *"nonpayable" | "payable"* - -*Defined in [index.ts:84](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L84)* - -___ - -### ContractAbi - -Ƭ **ContractAbi**: *[AbiDefinition](#abidefinition)[]* - -*Defined in [index.ts:78](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L78)* - -___ - -### ContractEventArg - -Ƭ **ContractEventArg**: *any* - -*Defined in [index.ts:469](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L469)* - -___ - -### DecodedLogs - -Ƭ **DecodedLogs**: *`Array>`* - -*Defined in [index.ts:440](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L440)* - -___ - -### EIP1193Event - -Ƭ **EIP1193Event**: *"accountsChanged" | "networkChanged" | "close" | "connect" | "notification"* - -*Defined in [index.ts:70](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L70)* - -Interface for providers that conform to EIP 1193 -Source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md - -___ - -### ErrorSeverity - -Ƭ **ErrorSeverity**: *"error" | "warning"* - -*Defined in [index.ts:600](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L600)* - -___ - -### ErrorType - -Ƭ **ErrorType**: *"JSONError" | "IOError" | "ParserError" | "DocstringParsingError" | "SyntaxError" | "DeclarationError" | "TypeError" | "UnimplementedFeatureError" | "InternalCompilerError" | "Exception" | "CompilerError" | "FatalError" | "Warning"* - -*Defined in [index.ts:586](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L586)* - -___ - -### FunctionAbi - -Ƭ **FunctionAbi**: *[MethodAbi](#interface-methodabi) | [ConstructorAbi](#interface-constructorabi) | [FallbackAbi](#interface-fallbackabi)* - -*Defined in [index.ts:82](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L82)* - -___ - -### JSONRPCErrorCallback - -Ƭ **JSONRPCErrorCallback**: *function* - -*Defined in [index.ts:3](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L3)* - -#### Type declaration: - -▸ (`err`: `Error` | null, `result?`: [JSONRPCResponsePayload](#interface-jsonrpcresponsepayload)): *void* - -**Parameters:** - -Name | Type | ------- | ------ | -`err` | `Error` \| null | -`result?` | [JSONRPCResponsePayload](#interface-jsonrpcresponsepayload) | - -___ - -### LogTopic - -Ƭ **LogTopic**: *null | string | string[]* - -*Defined in [index.ts:414](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L414)* - -___ - -### OutputField - -Ƭ **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"* - -*Defined in [index.ts:526](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L526)* - -___ - -### ParamDescription - -Ƭ **ParamDescription**: *string* - -*Defined in [index.ts:562](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L562)* - -___ - -### RawLog - -Ƭ **RawLog**: *[LogEntry](#interface-logentry)* - -*Defined in [index.ts:476](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L476)* - -___ - -### StateMutability - -Ƭ **StateMutability**: *"pure" | "view" | [ConstructorStateMutability](#constructorstatemutability)* - -*Defined in [index.ts:85](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L85)* - -___ - -### SupportedProvider - -Ƭ **SupportedProvider**: *[Web3JsProvider](_index_.md#web3jsprovider) | [GanacheProvider](#interface-ganacheprovider) | [EIP1193Provider](#interface-eip1193provider) | [ZeroExProvider](#interface-zeroexprovider)* - -*Defined in [index.ts:9](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L9)* - -Do not create your own provider. Use an existing provider from a Web3 or ProviderEngine library -Read more about Providers in the guides section of the 0x docs. - -___ - -### TransactionReceiptStatus - -Ƭ **TransactionReceiptStatus**: *null | string | `0` | `1`* - -*Defined in [index.ts:446](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L446)* - -___ - -### Unit - -Ƭ **Unit**: *"kwei" | "ada" | "mwei" | "babbage" | "gwei" | "shannon" | "szabo" | "finney" | "ether" | "kether" | "grand" | "einstein" | "mether" | "gether" | "tether"* - -*Defined in [index.ts:311](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L311)* - -___ - -### Web3JsProvider - -Ƭ **Web3JsProvider**: *[Web3JsV1Provider](#interface-web3jsv1provider) | [Web3JsV2Provider](#interface-web3jsv2provider) | [Web3JsV3Provider](#interface-web3jsv3provider)* - -*Defined in [index.ts:11](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L11)* - -
- diff --git a/packages/ethereum-types/package.json b/packages/ethereum-types/package.json deleted file mode 100644 index 05b45622fb..0000000000 --- a/packages/ethereum-types/package.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "name": "ethereum-types", - "version": "3.2.0", - "engines": { - "node": ">=6.12" - }, - "description": "Ethereum types", - "main": "lib/index.js", - "types": "lib/index.d.ts", - "scripts": { - "build": "tsc -b", - "build:ci": "yarn build", - "clean": "shx rm -rf lib generated_docs", - "lint": "tslint --format stylish --project .", - "fix": "tslint --fix --format stylish --project .", - "diff_docs": "git diff --exit-code ./docs", - "docs:md": "ts-doc-gen --sourceDir='$PROJECT_FILES' --output=$MD_FILE_DIR --fileExtension=mdx --tsconfig=./typedoc-tsconfig.json", - "docs:json": "typedoc --excludePrivate --excludeExternals --excludeProtected --ignoreCompilerErrors --target ES5 --tsconfig typedoc-tsconfig.json --json $JSON_FILE_PATH $PROJECT_FILES" - }, - "config": { - "postpublish": { - "assets": [] - } - }, - "license": "Apache-2.0", - "repository": { - "type": "git", - "url": "https://github.com/0xProject/0x-monorepo.git" - }, - "bugs": { - "url": "https://github.com/0xProject/0x-monorepo/issues" - }, - "homepage": "https://github.com/0xProject/0x-monorepo/packages/ethereum-types/README.md", - "devDependencies": { - "@0x/ts-doc-gen": "^0.0.22", - "@0x/tslint-config": "^4.1.0", - "make-promises-safe": "^1.1.0", - "shx": "^0.2.2", - "tslint": "5.11.0", - "typedoc": "^0.15.0", - "typescript": "3.0.1" - }, - "dependencies": { - "@types/node": "12.12.54", - "bignumber.js": "~9.0.0" - }, - "publishConfig": { - "access": "public" - }, - "gitHead": "4f91bfd907996b2f4dd383778b50c479c2602b56" -} diff --git a/packages/ethereum-types/src/globals.d.ts b/packages/ethereum-types/src/globals.d.ts deleted file mode 100644 index 94e63a32de..0000000000 --- a/packages/ethereum-types/src/globals.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -declare module '*.json' { - const json: any; - /* tslint:disable */ - export default json; - /* tslint:enable */ -} diff --git a/packages/ethereum-types/src/index.ts b/packages/ethereum-types/src/index.ts deleted file mode 100644 index 87be4b8e66..0000000000 --- a/packages/ethereum-types/src/index.ts +++ /dev/null @@ -1,761 +0,0 @@ -import { BigNumber } from 'bignumber.js'; - -export type JSONRPCErrorCallback = (err: Error | null, result?: JSONRPCResponsePayload) => void; - -/** - * Do not create your own provider. Use an existing provider from a Web3 or ProviderEngine library - * Read more about Providers in the guides section of the 0x docs. - */ -export type SupportedProvider = Web3JsProvider | GanacheProvider | EIP1193Provider | ZeroExProvider; - -export type Web3JsProvider = Web3JsV1Provider | Web3JsV2Provider | Web3JsV3Provider; - -export interface GanacheProvider { - sendAsync(payload: JSONRPCRequestPayload, callback: JSONRPCErrorCallback): void; -} - -// DEPRECATED(fabio): This interface should be replaced with the EIP 1193 provider interface -// We will leave it here until the ecosystem has migrated fully to the new standard -export interface Provider { - sendAsync(payload: JSONRPCRequestPayload, callback: JSONRPCErrorCallback): void; -} - -/** - * The interface for the provider used internally by 0x libraries - * Any property we use from any SupportedProvider should we explicitly - * add here - */ -export interface ZeroExProvider { - // TODO: Consolidate these bools into a single enum value - isZeroExProvider?: boolean; - isMetaMask?: boolean; - isParity?: boolean; - stop?(): void; - enable?(): Promise; - sendAsync(payload: JSONRPCRequestPayload, callback: JSONRPCErrorCallback): void; -} - -/** - * Web3.js version 1 provider interface - * This provider interface was implemented in the pre-1.0Beta releases for Web3.js. - * This interface allowed sending synchonous requests, support for which was later dropped. - */ -export interface Web3JsV1Provider { - sendAsync(payload: JSONRPCRequestPayload, callback: JSONRPCErrorCallback): void; - send(payload: JSONRPCRequestPayload): JSONRPCResponsePayload; -} - -/** - * Web3.js version 2 provider interface - * This provider interface was used in a couple of Web3.js 1.0 beta releases - * before the first attempts to conform to EIP1193 - */ -export interface Web3JsV2Provider { - send(payload: JSONRPCRequestPayload, callback: JSONRPCErrorCallback): void; -} - -/** - * Web3.js version 3 provider interface - * This provider interface was implemented with the hopes for conforming to the EIP1193 spec, - * however it does not conform entirely. - */ -export interface Web3JsV3Provider { - send(method: string, params?: any[]): Promise; -} - -/** - * Interface for providers that conform to EIP 1193 - * Source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md - */ -export type EIP1193Event = 'accountsChanged' | 'networkChanged' | 'close' | 'connect' | 'notification'; - -export interface EIP1193Provider { - isEIP1193: boolean; - send(method: string, params?: any[]): Promise; - on(event: EIP1193Event, listener: (result: any) => void): this; -} - -export type ContractAbi = AbiDefinition[]; - -export type AbiDefinition = FunctionAbi | EventAbi | RevertErrorAbi; - -export type FunctionAbi = MethodAbi | ConstructorAbi | FallbackAbi; - -export type ConstructorStateMutability = 'nonpayable' | 'payable'; -export type StateMutability = 'pure' | 'view' | ConstructorStateMutability; - -export interface MethodAbi { - // Ideally this would be set to: `'function'` but then TS complains when artifacts are loaded - // from JSON files, and this value has type `string` not type `'function'` - type: string; - name: string; - inputs: DataItem[]; - outputs: DataItem[]; - constant?: boolean; - stateMutability: StateMutability; - payable?: boolean; -} - -export interface ConstructorAbi { - // Ideally this would be set to: `'constructor'` but then TS complains when artifacts are loaded - // from JSON files, and this value has type `string` not type `'constructor'` - type: string; - inputs: DataItem[]; - payable?: boolean; - stateMutability: ConstructorStateMutability; -} - -export interface FallbackAbi { - // Ideally this would be set to: `'fallback'` but then TS complains when artifacts are loaded - // from JSON files, and this value has type `string` not type `'fallback'` - type: string; - payable: boolean; -} - -export interface EventParameter extends DataItem { - indexed: boolean; -} - -export interface RevertErrorAbi { - type: 'error'; - name: string; - arguments?: DataItem[]; -} - -export interface EventAbi { - // Ideally this would be set to: `'event'` but then TS complains when artifacts are loaded - // from JSON files, and this value has type `string` not type `'event'` - type: string; - name: string; - inputs: EventParameter[]; - anonymous: boolean; -} - -export interface DataItem { - name: string; - type: string; - internalType?: string; - components?: DataItem[]; -} - -export interface TupleDataItem extends DataItem { - components: DataItem[]; -} - -export enum OpCode { - // 0s: Stop and Arithmetic Operations - Stop = 'STOP', - Add = 'ADD', - Mul = 'MUL', - Sub = 'SUB', - Div = 'DIV', - SDiv = 'SDIV', - Mod = 'MOD', - SMod = 'SMOD', - AddMod = 'ADDMOD', - MulMod = 'MULMOD', - Exp = 'EXP', - SignExtend = 'SIGNEXTEND', - // 10s: Comparison & Bitwise Logic Operations - Lt = 'LT', - Gt = 'GT', - SLt = 'SLT', - SGt = 'SGT', - Eq = 'EQ', - IsZero = 'ISZERO', - And = 'AND', - Or = 'OR', - Xor = 'XOR', - Not = 'NOT', - Byte = 'BYTE', - // 20s: SHA3 - Sha3 = 'SHA3', - // 30s: Environmental Information - Address = 'ADDRESS', - Balance = 'BALANCE', - Origin = 'ORIGIN', - Caller = 'CALLER', - CallValue = 'CALLVALUE', - CallDataLoad = 'CALLDATALOAD', - CallDataSize = 'CALLDATASIZE', - CallDataCopy = 'CALLDATACOPY', - CodeSize = 'CODESIZE', - CodeCopy = 'CODECOPY', - GasPrice = 'GASPRICE', - ExtCodeSize = 'EXTCODESIZE', - ExtCodeCopy = 'EXTCODECOPY', - ReturnDataSize = 'RETURNDATASIZE', - ReturnDataCopy = 'RETURNDATACOPY', - // 40s: Block Information - BlockHash = 'BLOCKHASH', - Coinbase = 'COINBASE', - TimeStamp = 'TimeStamp', - Number = 'NUMBER', - Difficulty = 'DIFFICULTY', - Gaslimit = 'GASLIMIT', - // 50s: Stack, Memory, Storage and Flow Operations - Pop = 'POP', - MLoad = 'MLOAD', - MStore = 'MSTORE', - MStore8 = 'MSTORE8', - SLoad = 'SLOAD', - SStore = 'SSTORE', - Jump = 'JUMP', - Jumpi = 'JUMPI', - Pc = 'PC', - MSize = 'MSIZE', - Gas = 'GAS', - JumpDest = 'JUMPDEST', - // 60s & 70s: Push Operations - Push1 = 'PUSH1', - Push2 = 'PUSH2', - Push3 = 'PUSH3', - Push4 = 'PUSH4', - Push5 = 'PUSH5', - Push6 = 'PUSH6', - Push7 = 'PUSH7', - Push8 = 'PUSH8', - Push9 = 'PUSH9', - Push10 = 'PUSH10', - Push11 = 'PUSH11', - Push12 = 'PUSH12', - Push13 = 'PUSH13', - Push14 = 'PUSH14', - Push15 = 'PUSH15', - Push16 = 'PUSH16', - Push17 = 'PUSH17', - Push18 = 'PUSH18', - Push19 = 'PUSH19', - Push20 = 'PUSH20', - Push21 = 'PUSH21', - Push22 = 'PUSH22', - Push23 = 'PUSH23', - Push24 = 'PUSH24', - Push25 = 'PUSH25', - Push26 = 'PUSH26', - Push27 = 'PUSH27', - Push28 = 'PUSH28', - Push29 = 'PUSH29', - Push30 = 'PUSH30', - Push31 = 'PUSH31', - Push32 = 'PUSH32', - // 80s: Duplication Operation - Dup1 = 'DUP1', - Dup2 = 'DUP2', - Dup3 = 'DUP3', - Dup4 = 'DUP4', - Dup5 = 'DUP5', - Dup6 = 'DUP6', - Dup7 = 'DUP7', - Dup8 = 'DUP8', - Dup9 = 'DUP9', - Dup10 = 'DUP10', - Dup11 = 'DUP11', - Dup12 = 'DUP12', - Dup13 = 'DUP13', - Dup14 = 'DUP14', - Dup15 = 'DUP15', - Dup16 = 'DUP16', - // 90s: Exchange Operation - Swap1 = 'SWAP1', - Swap2 = 'SWAP2', - Swap3 = 'SWAP3', - Swap4 = 'SWAP4', - Swap5 = 'SWAP5', - Swap6 = 'SWAP6', - Swap7 = 'SWAP7', - Swap8 = 'SWAP8', - Swap9 = 'SWAP9', - Swap10 = 'SWAP10', - Swap11 = 'SWAP11', - Swap12 = 'SWAP12', - Swap13 = 'SWAP13', - Swap14 = 'SWAP14', - Swap15 = 'SWAP15', - Swap16 = 'SWAP16', - // a0s: Logging Operations - Log1 = 'LOG1', - Log2 = 'LOG2', - Log3 = 'LOG3', - Log4 = 'LOG4', - // f0s: System operations - Create = 'CREATE', - Call = 'CALL', - CallCode = 'CALLCODE', - Return = 'RETURN', - DelegateCall = 'DELEGATECALL', - StaticCall = 'STATICCALL', - Revert = 'REVERT', - Invalid = 'INVALID', - SelfDestruct = 'SELFDESTRUCT', -} - -export interface StructLog { - depth: number; - error: string; - gas: number; - gasCost: number; - memory: string[]; - op: OpCode; - pc: number; - stack: string[]; - storage: { [location: string]: string }; -} - -export interface TransactionTrace { - gas: number; - returnValue: any; - structLogs: StructLog[]; -} - -export type Unit = - | 'kwei' - | 'ada' - | 'mwei' - | 'babbage' - | 'gwei' - | 'shannon' - | 'szabo' - | 'finney' - | 'ether' - | 'kether' - | 'grand' - | 'einstein' - | 'mether' - | 'gether' - | 'tether'; - -export interface JSONRPCRequestPayload { - params: any[]; - method: string; - id: number; - jsonrpc: string; -} - -export interface JSONRPCResponseError { - message: string; - code: number; -} - -export interface JSONRPCResponsePayload { - result: any; - id: number; - jsonrpc: string; - error?: JSONRPCResponseError; -} - -export interface AbstractBlock { - number: number | null; - hash: string | null; - parentHash: string; - nonce: string | null; - sha3Uncles: string; - logsBloom: string | null; - transactionsRoot: string; - stateRoot: string; - miner: string; - difficulty: BigNumber; - totalDifficulty: BigNumber; - extraData: string; - size: number; - gasLimit: number; - gasUsed: number; - timestamp: number; - uncles: string[]; -} - -export interface BlockWithoutTransactionData extends AbstractBlock { - transactions: string[]; -} - -export interface BlockWithTransactionData extends AbstractBlock { - transactions: Transaction[]; -} - -export interface Transaction { - hash: string; - nonce: number; - blockHash: string | null; - blockNumber: number | null; - transactionIndex: number | null; - from: string; - to: string | null; - value: BigNumber; - gasPrice: BigNumber; - gas: number; - input: string; -} - -export interface CallTxDataBase { - to?: string; - value?: number | string | BigNumber; - gas?: number | string | BigNumber; - gasPrice?: number | string | BigNumber; - data?: string; - nonce?: number; -} - -export interface TxData extends CallTxDataBase { - from: string; -} - -export interface GethCallOverrides { - [address: string]: { - code?: string; - nonce?: number; - balance?: number | string | BigNumber; - }; -} - -export interface CallData extends CallTxDataBase { - from?: string; - overrides?: GethCallOverrides; -} - -export interface FilterObject { - fromBlock?: number | string; - toBlock?: number | string; - blockHash?: string; - address?: string; - topics?: LogTopic[]; -} - -export type LogTopic = null | string | string[]; - -export interface DecodedLogEntry extends LogEntry { - event: string; - args: A; -} - -export interface DecodedLogEntryEvent extends DecodedLogEntry { - removed: boolean; -} - -export interface LogEntryEvent extends LogEntry { - removed: boolean; -} - -export interface LogEntry { - logIndex: number | null; - transactionIndex: number | null; - transactionHash: string; - blockHash: string | null; - blockNumber: number | null; - address: string; - data: string; - topics: string[]; -} - -export type DecodedLogs = Array>; - -export interface TxDataPayable extends TxData { - value?: BigNumber; -} - -export type TransactionReceiptStatus = null | string | 0 | 1; - -export interface TransactionReceipt { - blockHash: string; - blockNumber: number; - transactionHash: string; - transactionIndex: number; - from: string; - to: string; - status: TransactionReceiptStatus; - cumulativeGasUsed: number; - gasUsed: number; - contractAddress: string | null; - logs: LogEntry[]; -} - -export enum AbiType { - Function = 'function', - Constructor = 'constructor', - Event = 'event', - Fallback = 'fallback', -} - -export type ContractEventArg = any; - -export interface DecodedLogArgs { - [argName: string]: ContractEventArg; -} - -export interface LogWithDecodedArgs extends DecodedLogEntry {} -export type RawLog = LogEntry; - -export enum BlockParamLiteral { - Earliest = 'earliest', - Latest = 'latest', - Pending = 'pending', -} - -export type BlockParam = BlockParamLiteral | number; - -export interface RawLogEntry { - logIndex: string | null; - transactionIndex: string | null; - transactionHash: string; - blockHash: string | null; - blockNumber: string | null; - address: string; - data: string; - topics: string[]; -} - -export enum SolidityTypes { - Address = 'address', - Bool = 'bool', - Bytes = 'bytes', - Int = 'int', - String = 'string', - Tuple = 'tuple', - Uint256 = 'uint256', - Uint8 = 'uint8', - Uint = 'uint', -} - -/** - * Contains the logs returned by a TransactionReceipt. We attempt to decode the - * logs using AbiDecoder. If we have the logs corresponding ABI, we decode it, - * otherwise we don't. - */ -export interface TransactionReceiptWithDecodedLogs extends TransactionReceipt { - logs: Array | LogEntry>; -} - -export interface TraceParams { - disableMemory?: boolean; - disableStack?: boolean; - disableStorage?: boolean; - tracer?: string; - timeout?: string; -} - -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 ContractChains { - [chainId: number]: ContractChainData; -} - -export interface ContractChainData { - address: string; - links: { - [linkName: string]: string; - }; - constructorArgs: string; -} - -export type ParamDescription = string; - -export interface StandardContractOutput { - abi: ContractAbi; - evm: EvmOutput; - devdoc?: DevdocOutput; -} - -export interface StandardOutput { - errors: SolcError[]; - sources: { - [fileName: string]: { - id: number; - ast?: object; - legacyAST?: object; - }; - }; - contracts: { - [fileName: string]: { - [contractName: string]: StandardContractOutput; - }; - }; -} - -export type ErrorType = - | 'JSONError' - | 'IOError' - | 'ParserError' - | 'DocstringParsingError' - | 'SyntaxError' - | 'DeclarationError' - | 'TypeError' - | 'UnimplementedFeatureError' - | 'InternalCompilerError' - | 'Exception' - | 'CompilerError' - | 'FatalError' - | 'Warning'; -export type ErrorSeverity = 'error' | 'warning'; - -export interface SolcError { - sourceLocation?: SourceLocation; - type: ErrorType; - component: 'general' | 'ewasm'; - severity: ErrorSeverity; - message: string; - formattedMessage?: string; -} - -export interface SourceLocation { - file: string; - start: number; - end: number; -} - -export interface EvmOutput { - bytecode: EvmBytecodeOutput; - deployedBytecode: EvmBytecodeOutput; -} - -export interface EvmBytecodeOutput { - linkReferences: EvmBytecodeOutputLinkReferences; - object: string; - sourceMap: string; -} - -export interface EvmBytecodeOutputLinkReferences { - [sourceFile: string]: { - [libraryName: string]: Array<{ start: number; length: number }>; - }; -} - -export interface DevdocOutput { - title?: string; - author?: string; - methods: { - [signature: string]: { - details?: string; - params?: { - [name: string]: ParamDescription; - }; - return?: 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 - * chains: Chain specific information by chain (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; - chains: ContractChains; -} - -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. - * useDockerisedSolc: If set to true - sol-compiler will try calling a dockerized installations of solc to achieve faster compilation times. Otherwise and by default - solcjs will be used. Defaults to false. - * isOfflineMode: If set to true - sol-compiler will not fetch the list of solc releases from github. It will use the hardcoded list. Defaults to false. - * 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. - * shouldSaveStandardInput: Write the standard JSON input in ${contractsDir}/${contractName}.input.json - */ -export interface CompilerOptions { - contractsDir?: string; - artifactsDir?: string; - compilerSettings?: CompilerSettings; - contracts?: string[] | '*'; - useDockerisedSolc?: boolean; - isOfflineMode?: boolean; - solcVersion?: string; - shouldSaveStandardInput?: boolean; -} - -export interface BlockRange { - fromBlock: BlockParam; - toBlock: BlockParam; -} // tslint:disable-line:max-file-line-count diff --git a/packages/ethereum-types/tsconfig.json b/packages/ethereum-types/tsconfig.json deleted file mode 100644 index 9ab22ac8ad..0000000000 --- a/packages/ethereum-types/tsconfig.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "extends": "../../tsconfig", - "compilerOptions": { - "typeRoots": ["../../node_modules/@types"], - "outDir": "lib", - "rootDir": "src" - }, - "include": ["src/**/*"] -} diff --git a/packages/ethereum-types/tslint.json b/packages/ethereum-types/tslint.json deleted file mode 100644 index dd9053357e..0000000000 --- a/packages/ethereum-types/tslint.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": ["@0x/tslint-config"] -} diff --git a/packages/ethereum-types/typedoc-tsconfig.json b/packages/ethereum-types/typedoc-tsconfig.json deleted file mode 100644 index f71153ec0f..0000000000 --- a/packages/ethereum-types/typedoc-tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../typedoc-tsconfig", - "compilerOptions": { - "typeRoots": ["../../node_modules/@types"], - "outDir": "lib" - }, - "include": ["src/**/*"] -} diff --git a/packages/instant/.dogfood.discharge.json b/packages/instant/.dogfood.discharge.json deleted file mode 100644 index 8232f03937..0000000000 --- a/packages/instant/.dogfood.discharge.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "domain": "0x-instant-dogfood", - "build_command": "WEBPACK_OUTPUT_PATH=public dotenv yarn build -- --env.discharge_target=dogfood", - "upload_directory": "public", - "index_key": "index.html", - "error_key": "index.html", - "trailing_slashes": true, - "cache": 3600, - "aws_profile": "0xproject", - "aws_region": "us-east-1", - "cdn": false, - "dns_configured": true, - "should_keep_files_in_s3": true -} diff --git a/packages/instant/.env_example b/packages/instant/.env_example deleted file mode 100644 index 60c8fa70ef..0000000000 --- a/packages/instant/.env_example +++ /dev/null @@ -1,11 +0,0 @@ -INSTANT_ROLLBAR_PUBLISH_TOKEN= -INSTANT_ROLLBAR_CLIENT_TOKEN= -INSTANT_HEAP_ANALYTICS_ID_PRODUCTION= -INSTANT_HEAP_ANALYTICS_ID_DEVELOPMENT= -INSTANT_FORTMATIC_API_KEY_PRODUCTION= -INSTANT_FORTMATIC_API_KEY_DEVELOPMENT= -INSTANT_INFURA_PROJECT_ID_PRODUCTION= -INSTANT_INFURA_PROJECT_ID_DEVELOPMENT= -# if you want to report to heap or rollbar when building in development mode, you can use the following: -# INSTANT_HEAP_FORCE_DEVELOPMENT=true -# INSTANT_ROLLBAR_FORCE_DEVELOPMENT=true \ No newline at end of file diff --git a/packages/instant/.gitignore b/packages/instant/.gitignore deleted file mode 100644 index 2e65f192d4..0000000000 --- a/packages/instant/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -public/instant.js -public/instant.js.map -umd/* -.env \ No newline at end of file diff --git a/packages/instant/.npmignore b/packages/instant/.npmignore deleted file mode 100644 index 5b63a0e7b3..0000000000 --- a/packages/instant/.npmignore +++ /dev/null @@ -1,11 +0,0 @@ -# Blacklist all files -.* -* -# Whitelist lib -!lib/**/* -# Blacklist tests and publish scripts -/lib/test/* -/lib/monorepo_scripts/ -# Package specific ignore -!umd/**/* -.env diff --git a/packages/instant/.production.discharge.json b/packages/instant/.production.discharge.json deleted file mode 100644 index 1df19a18f7..0000000000 --- a/packages/instant/.production.discharge.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "domain": "instant.0x.org", - "build_command": "dotenv yarn build -- --env.discharge_target=production", - "upload_directory": "umd", - "index_key": "instant.js", - "error_key": "404.html", - "trailing_slashes": true, - "cache": 3600, - "aws_profile": "0xproject", - "aws_region": "us-east-1", - "cdn": true, - "dns_configured": true, - "should_keep_files_in_s3": true -} diff --git a/packages/instant/.staging.discharge.json b/packages/instant/.staging.discharge.json deleted file mode 100644 index 08d0751d8d..0000000000 --- a/packages/instant/.staging.discharge.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "domain": "0x-instant-staging", - "build_command": "WEBPACK_OUTPUT_PATH=public dotenv yarn build -- --env.discharge_target=staging", - "upload_directory": "public", - "index_key": "index.html", - "error_key": "index.html", - "trailing_slashes": true, - "cache": 3600, - "aws_profile": "0xproject", - "aws_region": "us-east-1", - "cdn": false, - "dns_configured": true, - "should_keep_files_in_s3": true -} diff --git a/packages/instant/CHANGELOG.json b/packages/instant/CHANGELOG.json deleted file mode 100644 index 2b420e0bcb..0000000000 --- a/packages/instant/CHANGELOG.json +++ /dev/null @@ -1,72 +0,0 @@ -[ - { - "version": "4.2.0", - "changes": [ - { - "note": "Clean up heartbeat functions on close", - "pr": 2492 - }, - { - "note": "Fix ERC721 asset support", - "pr": 2491 - }, - { - "note": "Remove `slippagePercentage` SwapQuoter config.", - "pr": 2513 - }, - { - "note": "Pin `asset-swapper` dependency", - "pr": 2591 - } - ] - }, - { - "version": "4.1.0", - "changes": [ - { - "note": "Run Web3ProviderEngine without excess block polling", - "pr": 1695 - } - ] - }, - { - "version": "4.0.0", - "changes": [ - { - "note": "Add support for EIP1193 providers & Web3.js providers >= 1.0-beta.38", - "pr": 1627 - }, - { - "note": "Update provider params to type SupportedProvider which outlines all supported providers", - "pr": 1627 - } - ] - }, - { - "version": "3.0.0", - "changes": [ - { - "note": "Upgrade the bignumber.js to v8.0.2", - "pr": 1517 - } - ] - }, - { - "version": "2.0.0", - "changes": [ - { - "note": "Renamed ActionTypes enum members to PascalCase to conform with tslint enum-naming rule", - "pr": 1474 - } - ] - }, - { - "timestamp": 1542821676, - "version": "1.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - } -] diff --git a/packages/instant/CHANGELOG.md b/packages/instant/CHANGELOG.md deleted file mode 100644 index c8be0c644f..0000000000 --- a/packages/instant/CHANGELOG.md +++ /dev/null @@ -1,10 +0,0 @@ - - -CHANGELOG - -## v1.0.1 - _November 21, 2018_ - - * Dependencies updated diff --git a/packages/instant/README.md b/packages/instant/README.md deleted file mode 100644 index 35a1c5dbdf..0000000000 --- a/packages/instant/README.md +++ /dev/null @@ -1,114 +0,0 @@ -## @0x/instant - -## ⚠️ Deprecation Warning ️️⚠️ - -This project is no longer being actively maintained. - -## Integration - -Looking to integrate 0x Instant into your web application or site? Check out the dedicated [instant documentation](https://0x.org/docs/guides/integrate-instant#ui-integration) to get started. The documentation covers instant and related topics in depth. For a more "drag and drop" experience, check out our [configurator tool](https://0x.org/instant#configure). For on demand developer support, join our [Discord](https://discordapp.com/invite/d3FTX3M). - -Check out a live sample integration [here](https://www.rexrelay.com/instant). - -## Installation - -The package is available as a UMD module named `zeroExInstant` at https://instant.0x.org/instant.js. - -```html - - - - -
- - -``` - -## Deploying - -To run any of the following commands you need to configure your `.env` file. There is an example `.env_example` file to show you what values are required. - -You can deploy a work-in-progress version of 0x Instant at http://0x-instant-dogfood.s3-website-us-east-1.amazonaws.com/instant.js for easy sharing. - -To build and deploy the bundle run - -``` -yarn deploy_dogfood -``` - -We also have a staging bucket that is to be updated less frequently can be used to share a beta version of instant externally: http://0x-instant-staging.s3-website-us-east-1.amazonaws.com/instant.js - -To build and deploy to this bundle, run - -``` -yarn deploy_staging -``` - -Finally, we have our live production bundle that is only meant to be updated with stable, polished releases: https://instant.0x.org/instant.js - -To build and deploy to this bundle, run - -``` -yarn deploy_production -``` - -**NOTE: On deploying the site to staging and dogfood, it will say the site is available at a non-existent URL. Please ignore and use the (now updated) URL above.** - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install dependencies - -If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: - -```bash -yarn config set workspaces-experimental true -``` - -Then install dependencies - -```bash -yarn install -``` - -### Build - -To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory: - -```bash -PKG=@0x/instant yarn build -``` - -Or continuously rebuild on change: - -```bash -PKG=@0x/instant yarn watch -``` - -### Clean - -```bash -yarn clean -``` - -### Lint - -```bash -yarn lint -``` - -### Run Tests - -```bash -yarn test -``` diff --git a/packages/instant/jest.config.js b/packages/instant/jest.config.js deleted file mode 100644 index 29c365835f..0000000000 --- a/packages/instant/jest.config.js +++ /dev/null @@ -1,10 +0,0 @@ -module.exports = { - roots: ['/test'], - coverageDirectory: 'coverage', - transform: { - '.*.tsx?$': 'ts-jest', - }, - testRegex: '(/__test__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$', - moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], - collectCoverageFrom: ['src/**/*.{ts,tsx}', '!src/index.tsx'], -}; diff --git a/packages/instant/package.json b/packages/instant/package.json deleted file mode 100644 index a95c48c655..0000000000 --- a/packages/instant/package.json +++ /dev/null @@ -1,114 +0,0 @@ -{ - "name": "@0x/instant", - "version": "1.0.53", - "engines": { - "node": ">=6.12" - }, - "private": true, - "description": "0x Instant React Component", - "main": "umd/instant.js", - "scripts": { - "build": "NODE_ENV=production node --max_old_space_size=8192 ../../node_modules/.bin/webpack --mode production", - "build:dev": "webpack --mode development", - "build:ci": "yarn build", - "dev": "dotenv webpack-dev-server -- --mode development", - "lint": "tslint --format stylish --project .", - "fix": "tslint --fix --format stylish --project .", - "test": "jest", - "test:coverage": "jest --coverage", - "rebuild_and_test": "run-s clean build test", - "test:circleci": "yarn test:coverage", - "clean": "shx rm -rf lib coverage scripts", - "deploy_dogfood": "discharge deploy -c .dogfood.discharge.json", - "deploy_staging": "discharge deploy -c .staging.discharge.json", - "deploy_production": "discharge deploy -c .production.discharge.json", - "manual:postpublish": "yarn build; node ./scripts/postpublish.js" - }, - "config": { - "postpublish": { - "assets": [ - "packages/instant/umd/instant.js", - "packages/instant/umd/instant.js.map" - ] - } - }, - "repository": { - "type": "git", - "url": "https://github.com/0xProject/0x-monorepo.git" - }, - "author": "Francesco Agosti", - "license": "Apache-2.0", - "bugs": { - "url": "https://github.com/0xProject/0x-monorepo/issues" - }, - "homepage": "https://github.com/0xProject/0x-monorepo/packages/instant/README.md", - "dependencies": { - "@0x/assert": "^3.0.9", - "@0x/asset-swapper": "^4.6.0", - "@0x/contract-wrappers": "^13.8.0", - "@0x/json-schemas": "^5.1.0", - "@0x/subproviders": "^6.1.1", - "@0x/utils": "^5.5.1", - "@0x/web3-wrapper": "^7.2.0", - "babel-runtime": "^6.26.0", - "bowser": "^1.9.4", - "copy-to-clipboard": "^3.0.8", - "fortmatic": "^1.0.1", - "lodash": "^4.17.11", - "polished": "^1.9.2", - "react": "^16.5.2", - "react-dom": "^16.5.2", - "react-redux": "^5.0.7", - "redux": "^4.0.0", - "redux-devtools-extension": "^2.13.5", - "rollbar": "^2.5.0", - "styled-components": "4.1.2", - "ts-optchain": "^0.1.1" - }, - "devDependencies": { - "@0x/tslint-config": "^4.1.0", - "@0x/types": "^3.2.0", - "@0x/typescript-typings": "^5.1.1", - "@static/discharge": "https://github.com/0xProject/discharge.git", - "@types/enzyme": "^3.1.14", - "@types/enzyme-adapter-react-16": "^1.0.3", - "@types/jest": "^23.3.5", - "@types/lodash": "4.14.104", - "@types/node": "12.12.54", - "@types/react": "16.4.16", - "@types/react-dom": "16.0.6", - "@types/react-redux": "^6.0.9", - "@types/redux": "^3.6.0", - "@types/styled-components": "4.1.2", - "awesome-typescript-loader": "^5.2.1", - "babel-loader": "^7.1.5", - "babel-plugin-transform-es3-member-expression-literals": "^6.22.0", - "babel-plugin-transform-es3-property-literals": "^6.22.0", - "babel-plugin-transform-object-assign": "^6.22.0", - "babel-plugin-transform-object-rest-spread": "^6.26.0", - "babel-plugin-transform-runtime": "^6.23.0", - "babel-preset-env": "^1.7.0", - "dotenv-cli": "^1.4.0", - "enzyme": "^3.6.0", - "enzyme-adapter-react-16": "^1.5.0", - "ethereum-types": "^3.2.0", - "ip": "^1.1.5", - "jest": "^23.6.0", - "make-promises-safe": "^1.1.0", - "npm-run-all": "^4.1.2", - "nyc": "^11.0.1", - "rollbar-sourcemap-webpack-plugin": "^2.4.0", - "shx": "^0.2.2", - "source-map-loader": "^0.2.4", - "svg-react-loader": "^0.4.6", - "ts-jest": "^23.10.3", - "tslint": "5.11.0", - "typescript": "3.0.1", - "webpack": "^4.20.2", - "webpack-cli": "3.1.2", - "webpack-dev-server": "^3.1.9" - }, - "publishConfig": { - "access": "private" - } -} diff --git a/packages/instant/public/external.css b/packages/instant/public/external.css deleted file mode 100644 index 21278577ee..0000000000 --- a/packages/instant/public/external.css +++ /dev/null @@ -1,29 +0,0 @@ -/* - CSS file meant to represent an external (integrators) stylesheet and - help ensure that instant looks consistent across environments. -*/ - -button { - font-size: 50px; - height: 200px; - background-color: red; -} - -input { - padding: 100px; - font-size: 50px; - height: 100px; -} - -input::-webkit-input-placeholder { - color: #b4b4b4 !important; -} - -div { - padding: 3px; -} - -p { - background-color: green; - margin: 10px; -} diff --git a/packages/instant/public/index.html b/packages/instant/public/index.html deleted file mode 100644 index ca114cc15b..0000000000 --- a/packages/instant/public/index.html +++ /dev/null @@ -1,228 +0,0 @@ - - - - - - 0x Instant Dev Environment - - - - - - - - - -
-
-
- - - - -
-
-
- - - diff --git a/packages/instant/src/assets/icons/ae.svg b/packages/instant/src/assets/icons/ae.svg deleted file mode 100644 index 592400d1a2..0000000000 --- a/packages/instant/src/assets/icons/ae.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/packages/instant/src/assets/icons/agi.svg b/packages/instant/src/assets/icons/agi.svg deleted file mode 100644 index 9ed9784a45..0000000000 --- a/packages/instant/src/assets/icons/agi.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/packages/instant/src/assets/icons/ant.svg b/packages/instant/src/assets/icons/ant.svg deleted file mode 100644 index ed7e1491a7..0000000000 --- a/packages/instant/src/assets/icons/ant.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/packages/instant/src/assets/icons/ast.svg b/packages/instant/src/assets/icons/ast.svg deleted file mode 100644 index 8136fb6887..0000000000 --- a/packages/instant/src/assets/icons/ast.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/packages/instant/src/assets/icons/bat.svg b/packages/instant/src/assets/icons/bat.svg deleted file mode 100644 index 9b69ddf9d3..0000000000 --- a/packages/instant/src/assets/icons/bat.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/packages/instant/src/assets/icons/chevronRight.svg b/packages/instant/src/assets/icons/chevronRight.svg deleted file mode 100644 index f03eac2407..0000000000 --- a/packages/instant/src/assets/icons/chevronRight.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/packages/instant/src/assets/icons/cvc.svg b/packages/instant/src/assets/icons/cvc.svg deleted file mode 100644 index bddc90e160..0000000000 --- a/packages/instant/src/assets/icons/cvc.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/packages/instant/src/assets/icons/dai.svg b/packages/instant/src/assets/icons/dai.svg deleted file mode 100644 index 391aa964fa..0000000000 --- a/packages/instant/src/assets/icons/dai.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/packages/instant/src/assets/icons/dgd.svg b/packages/instant/src/assets/icons/dgd.svg deleted file mode 100644 index 371f895842..0000000000 --- a/packages/instant/src/assets/icons/dgd.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/packages/instant/src/assets/icons/dgx.svg b/packages/instant/src/assets/icons/dgx.svg deleted file mode 100644 index 2e4a90a5d5..0000000000 --- a/packages/instant/src/assets/icons/dgx.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/packages/instant/src/assets/icons/dnt.svg b/packages/instant/src/assets/icons/dnt.svg deleted file mode 100644 index 7d54593437..0000000000 --- a/packages/instant/src/assets/icons/dnt.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/packages/instant/src/assets/icons/fun.svg b/packages/instant/src/assets/icons/fun.svg deleted file mode 100644 index bb4347df21..0000000000 --- a/packages/instant/src/assets/icons/fun.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/packages/instant/src/assets/icons/gno.svg b/packages/instant/src/assets/icons/gno.svg deleted file mode 100644 index ebf6290cf9..0000000000 --- a/packages/instant/src/assets/icons/gno.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/packages/instant/src/assets/icons/gnt.svg b/packages/instant/src/assets/icons/gnt.svg deleted file mode 100644 index 7315ce459b..0000000000 --- a/packages/instant/src/assets/icons/gnt.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/packages/instant/src/assets/icons/knc.svg b/packages/instant/src/assets/icons/knc.svg deleted file mode 100644 index 70d35bc2fb..0000000000 --- a/packages/instant/src/assets/icons/knc.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/packages/instant/src/assets/icons/link.svg b/packages/instant/src/assets/icons/link.svg deleted file mode 100644 index 2fddf7ef18..0000000000 --- a/packages/instant/src/assets/icons/link.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/packages/instant/src/assets/icons/lpt.svg b/packages/instant/src/assets/icons/lpt.svg deleted file mode 100644 index cbe4f22028..0000000000 --- a/packages/instant/src/assets/icons/lpt.svg +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/packages/instant/src/assets/icons/mana.svg b/packages/instant/src/assets/icons/mana.svg deleted file mode 100644 index 45be622e4b..0000000000 --- a/packages/instant/src/assets/icons/mana.svg +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/packages/instant/src/assets/icons/mkr.svg b/packages/instant/src/assets/icons/mkr.svg deleted file mode 100644 index e09d474442..0000000000 --- a/packages/instant/src/assets/icons/mkr.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/packages/instant/src/assets/icons/mln.svg b/packages/instant/src/assets/icons/mln.svg deleted file mode 100644 index a0b821c57b..0000000000 --- a/packages/instant/src/assets/icons/mln.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/packages/instant/src/assets/icons/omg.svg b/packages/instant/src/assets/icons/omg.svg deleted file mode 100644 index a906509aff..0000000000 --- a/packages/instant/src/assets/icons/omg.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/packages/instant/src/assets/icons/phone.svg b/packages/instant/src/assets/icons/phone.svg deleted file mode 100644 index 0986ef2eba..0000000000 --- a/packages/instant/src/assets/icons/phone.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/packages/instant/src/assets/icons/powr.svg b/packages/instant/src/assets/icons/powr.svg deleted file mode 100644 index eb48342e18..0000000000 --- a/packages/instant/src/assets/icons/powr.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/packages/instant/src/assets/icons/ren.svg b/packages/instant/src/assets/icons/ren.svg deleted file mode 100644 index fe563dee23..0000000000 --- a/packages/instant/src/assets/icons/ren.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/packages/instant/src/assets/icons/rep.svg b/packages/instant/src/assets/icons/rep.svg deleted file mode 100644 index 1be1a6a881..0000000000 --- a/packages/instant/src/assets/icons/rep.svg +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/packages/instant/src/assets/icons/req.svg b/packages/instant/src/assets/icons/req.svg deleted file mode 100644 index d9eb896347..0000000000 --- a/packages/instant/src/assets/icons/req.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/packages/instant/src/assets/icons/salt.svg b/packages/instant/src/assets/icons/salt.svg deleted file mode 100644 index f2892c9817..0000000000 --- a/packages/instant/src/assets/icons/salt.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/packages/instant/src/assets/icons/snt.svg b/packages/instant/src/assets/icons/snt.svg deleted file mode 100644 index 34b2c432b4..0000000000 --- a/packages/instant/src/assets/icons/snt.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/packages/instant/src/assets/icons/spank.svg b/packages/instant/src/assets/icons/spank.svg deleted file mode 100644 index 1d73207706..0000000000 --- a/packages/instant/src/assets/icons/spank.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/packages/instant/src/assets/icons/usdc.svg b/packages/instant/src/assets/icons/usdc.svg deleted file mode 100644 index a9201efb65..0000000000 --- a/packages/instant/src/assets/icons/usdc.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/packages/instant/src/assets/icons/wax.svg b/packages/instant/src/assets/icons/wax.svg deleted file mode 100644 index 8bcb730155..0000000000 --- a/packages/instant/src/assets/icons/wax.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/packages/instant/src/assets/icons/zil.svg b/packages/instant/src/assets/icons/zil.svg deleted file mode 100644 index 1a9218201e..0000000000 --- a/packages/instant/src/assets/icons/zil.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/packages/instant/src/assets/icons/zrx.svg b/packages/instant/src/assets/icons/zrx.svg deleted file mode 100644 index da623710b3..0000000000 --- a/packages/instant/src/assets/icons/zrx.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/packages/instant/src/assets/powered_by_0x.svg b/packages/instant/src/assets/powered_by_0x.svg deleted file mode 100644 index e3d007d0ba..0000000000 --- a/packages/instant/src/assets/powered_by_0x.svg +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/packages/instant/src/components/amount_placeholder.tsx b/packages/instant/src/components/amount_placeholder.tsx deleted file mode 100644 index 290e34a070..0000000000 --- a/packages/instant/src/components/amount_placeholder.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import * as React from 'react'; - -import { ColorOption } from '../style/theme'; - -import { Pulse } from './animations/pulse'; - -import { Text } from './ui/text'; - -interface PlainPlaceholder { - color: ColorOption; -} -const PlainPlaceholder: React.StatelessComponent = props => ( - - — - -); - -export interface AmountPlaceholderProps { - color: ColorOption; - isPulsating: boolean; -} -export const AmountPlaceholder: React.StatelessComponent = props => { - if (props.isPulsating) { - return ( - - - - ); - } else { - return ; - } -}; - -AmountPlaceholder.displayName = 'AmountPlaceholder'; diff --git a/packages/instant/src/components/animations/full_rotation.tsx b/packages/instant/src/components/animations/full_rotation.tsx deleted file mode 100644 index 1dff1b1fc5..0000000000 --- a/packages/instant/src/components/animations/full_rotation.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import { keyframes, styled } from '../../style/theme'; - -interface FullRotationProps { - height: string; - width: string; -} -const rotatingKeyframes = keyframes` -from { - transform: rotate(0deg); -} - -to { - transform: rotate(360deg); -} -`; - -export const FullRotation = styled.div` - animation: ${rotatingKeyframes} 2s linear infinite; - height: ${props => props.height}; - width: ${props => props.width}; -`; diff --git a/packages/instant/src/components/animations/position_animation.tsx b/packages/instant/src/components/animations/position_animation.tsx deleted file mode 100644 index feb3e25949..0000000000 --- a/packages/instant/src/components/animations/position_animation.tsx +++ /dev/null @@ -1,107 +0,0 @@ -import { InterpolationValue } from 'styled-components'; - -import { media, OptionallyScreenSpecific, stylesForMedia } from '../../style/media'; -import { css, keyframes, styled } from '../../style/theme'; - -export interface TransitionInfo { - from: string; - to: string; -} - -const generateTransitionInfoCss = ( - key: keyof TransitionInfo, - top?: TransitionInfo, - bottom?: TransitionInfo, - left?: TransitionInfo, - right?: TransitionInfo, -): string => { - const topStringIfExists = top ? `top: ${top[key]};` : ''; - const bottomStringIfExists = bottom ? `bottom: ${bottom[key]};` : ''; - const leftStringIfExists = left ? `left: ${left[key]};` : ''; - const rightStringIfExists = right ? `right: ${right[key]};` : ''; - return ` - ${topStringIfExists} - ${bottomStringIfExists} - ${leftStringIfExists} - ${rightStringIfExists} - `; -}; - -const slideKeyframeGenerator = ( - position: string, - top?: TransitionInfo, - bottom?: TransitionInfo, - left?: TransitionInfo, - right?: TransitionInfo, -) => keyframes` - from { - position: ${position}; - ${generateTransitionInfoCss('from', top, bottom, left, right)} - } - - to { - position: ${position}; - ${generateTransitionInfoCss('to', top, bottom, left, right)} - } -`; - -export interface PositionAnimationSettings { - top?: TransitionInfo; - bottom?: TransitionInfo; - left?: TransitionInfo; - right?: TransitionInfo; - timingFunction: string; - duration?: string; - position?: string; -} - -const generatePositionAnimationCss = (positionSettings: PositionAnimationSettings) => { - return css` - animation-name: ${slideKeyframeGenerator( - positionSettings.position || 'relative', - positionSettings.top, - positionSettings.bottom, - positionSettings.left, - positionSettings.right, - )}; - animation-duration: ${positionSettings.duration || '0.3s'}; - animation-timing-function: ${positionSettings.timingFunction}; - animation-delay: 0s; - animation-iteration-count: 1; - animation-fill-mode: forwards; - position: ${positionSettings.position || 'relative'}; - width: 100%; - `; -}; - -export interface PositionAnimationProps { - positionSettings: OptionallyScreenSpecific; - zIndex?: OptionallyScreenSpecific; - height?: string; -} - -const defaultAnimation = (positionSettings: OptionallyScreenSpecific) => { - const bestDefault = 'default' in positionSettings ? positionSettings.default : positionSettings; - return generatePositionAnimationCss(bestDefault); -}; -const animationForSize = ( - positionSettings: OptionallyScreenSpecific, - sizeKey: 'sm' | 'md' | 'lg', - mediaFn: (...args: any[]) => InterpolationValue, -) => { - // checking default makes sure we have a PositionAnimationSettings object - // and then we check to see if we have a setting for the specific `sizeKey` - const animationSettingsForSize = 'default' in positionSettings && positionSettings[sizeKey]; - return animationSettingsForSize && mediaFn`${generatePositionAnimationCss(animationSettingsForSize)}`; -}; - -export const PositionAnimation = styled.div` - && { - ${props => props.zIndex && stylesForMedia('z-index', props.zIndex)} - ${props => defaultAnimation(props.positionSettings)} - ${props => animationForSize(props.positionSettings, 'sm', media.small)} - ${props => animationForSize(props.positionSettings, 'md', media.medium)} - ${props => animationForSize(props.positionSettings, 'lg', media.large)} - ${props => (props.height ? `height: ${props.height};` : '')} - } -`; diff --git a/packages/instant/src/components/animations/pulse.tsx b/packages/instant/src/components/animations/pulse.tsx deleted file mode 100644 index 01d6ea0706..0000000000 --- a/packages/instant/src/components/animations/pulse.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { keyframes, styled } from '../../style/theme'; - -const pulsingKeyframes = keyframes` - 0%, 100% { - opacity: 0.2; - } - 50% { - opacity: 100; - } -`; -export const Pulse = styled.div` - animation-name: ${pulsingKeyframes} - animation-duration: 2s; - animation-iteration-count: infinite; -`; diff --git a/packages/instant/src/components/animations/slide_animation.tsx b/packages/instant/src/components/animations/slide_animation.tsx deleted file mode 100644 index 6ac47e9a66..0000000000 --- a/packages/instant/src/components/animations/slide_animation.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import * as React from 'react'; - -import { OptionallyScreenSpecific } from '../../style/media'; -import { SlideAnimationState } from '../../types'; - -import { PositionAnimation, PositionAnimationSettings } from './position_animation'; - -export interface SlideAnimationProps { - animationState: SlideAnimationState; - slideInSettings: OptionallyScreenSpecific; - slideOutSettings: OptionallyScreenSpecific; - zIndex?: OptionallyScreenSpecific; - height?: string; - onAnimationEnd?: () => void; -} - -export const SlideAnimation: React.StatelessComponent = props => { - if (props.animationState === 'none') { - return {props.children}; - } - const positionSettings = props.animationState === 'slidIn' ? props.slideInSettings : props.slideOutSettings; - return ( - - {props.children} - - ); -}; - -SlideAnimation.displayName = 'SlideAnimation'; diff --git a/packages/instant/src/components/buy_button.tsx b/packages/instant/src/components/buy_button.tsx deleted file mode 100644 index a0298626aa..0000000000 --- a/packages/instant/src/components/buy_button.tsx +++ /dev/null @@ -1,162 +0,0 @@ -import { - affiliateFeeUtils, - ExtensionContractType, - MarketBuySwapQuote, - SwapQuoteConsumer, - SwapQuoteConsumerError, - SwapQuoter, -} from '@0x/asset-swapper'; -import { AssetProxyId } from '@0x/types'; -import { BigNumber } from '@0x/utils'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import * as _ from 'lodash'; -import * as React from 'react'; -import { oc } from 'ts-optchain'; - -import { DEFAULT_AFFILIATE_INFO, WEB_3_WRAPPER_TRANSACTION_FAILED_ERROR_MSG_PREFIX } from '../constants'; -import { ColorOption } from '../style/theme'; -import { AffiliateInfo, Asset, ZeroExInstantError } from '../types'; -import { analytics } from '../util/analytics'; -import { errorReporter } from '../util/error_reporter'; -import { gasPriceEstimator } from '../util/gas_price_estimator'; -import { util } from '../util/util'; - -import { Button } from './ui/button'; - -export interface BuyButtonProps { - accountAddress?: string; - accountEthBalanceInWei?: BigNumber; - swapQuote?: MarketBuySwapQuote; - swapQuoter: SwapQuoter; - swapQuoteConsumer: SwapQuoteConsumer; - web3Wrapper: Web3Wrapper; - affiliateInfo?: AffiliateInfo; - selectedAsset?: Asset; - onValidationPending: (swapQuote: MarketBuySwapQuote) => void; - onValidationFail: ( - swapQuote: MarketBuySwapQuote, - errorMessage: SwapQuoteConsumerError | ZeroExInstantError, - ) => void; - onSignatureDenied: (swapQuote: MarketBuySwapQuote) => void; - onBuyProcessing: ( - swapQuote: MarketBuySwapQuote, - txHash: string, - startTimeUnix: number, - expectedEndTimeUnix: number, - ) => void; - onBuySuccess: (swapQuote: MarketBuySwapQuote, txHash: string) => void; - onBuyFailure: (swapQuote: MarketBuySwapQuote, txHash: string) => void; -} - -export class BuyButton extends React.PureComponent { - public static defaultProps = { - onClick: util.boundNoop, - onBuySuccess: util.boundNoop, - onBuyFailure: util.boundNoop, - }; - public render(): React.ReactNode { - const { swapQuote, accountAddress, selectedAsset } = this.props; - const shouldDisableButton = swapQuote === undefined || accountAddress === undefined; - const buttonText = - selectedAsset !== undefined && selectedAsset.metaData.assetProxyId === AssetProxyId.ERC20 - ? `Buy ${selectedAsset.metaData.symbol.toUpperCase()}` - : 'Buy Now'; - return ( - - ); - } - private readonly _handleClick = async () => { - // The button is disabled when there is no buy quote anyway. - const { - swapQuote, - swapQuoteConsumer, - affiliateInfo = DEFAULT_AFFILIATE_INFO, - accountAddress, - accountEthBalanceInWei, - web3Wrapper, - } = this.props; - if (swapQuote === undefined || accountAddress === undefined) { - return; - } - this.props.onValidationPending(swapQuote); - const ethNeededForBuy = affiliateFeeUtils.getTotalEthAmountWithAffiliateFee(swapQuote.worstCaseQuoteInfo, 0); - // if we don't have a balance for the user, let the transaction through, it will be handled by the wallet - const hasSufficientEth = accountEthBalanceInWei === undefined || accountEthBalanceInWei.gte(ethNeededForBuy); - if (!hasSufficientEth) { - analytics.trackBuyNotEnoughEth(swapQuote); - this.props.onValidationFail(swapQuote, ZeroExInstantError.InsufficientETH); - return; - } - let txHash: string | undefined; - const gasInfo = await gasPriceEstimator.getGasInfoAsync(); - const feeRecipient = oc(affiliateInfo).feeRecipient(); - const feePercentage = oc(affiliateInfo).feePercentage(); - try { - analytics.trackBuyStarted(swapQuote); - txHash = await swapQuoteConsumer.executeSwapQuoteOrThrowAsync(swapQuote, { - useExtensionContract: ExtensionContractType.Forwarder, - extensionContractOpts: { - feeRecipient, - feePercentage, - }, - takerAddress: accountAddress, - }); - } catch (e) { - if (e instanceof Error) { - if (e.message === SwapQuoteConsumerError.TransactionValueTooLow) { - analytics.trackBuySimulationFailed(swapQuote); - this.props.onValidationFail(swapQuote, SwapQuoteConsumerError.TransactionValueTooLow); - return; - } else if (e.message === SwapQuoteConsumerError.SignatureRequestDenied) { - analytics.trackBuySignatureDenied(swapQuote); - this.props.onSignatureDenied(swapQuote); - return; - } else { - errorReporter.report(e); - analytics.trackBuyUnknownError(swapQuote, e.message); - this.props.onValidationFail(swapQuote, ZeroExInstantError.CouldNotSubmitTransaction); - return; - } - } - // HACK(dekz): Wrappers no longer include decorators which map errors - // like transaction deny - if (e.message && e.message.includes('User denied transaction signature')) { - analytics.trackBuySignatureDenied(swapQuote); - this.props.onSignatureDenied(swapQuote); - return; - } - // Fortmatic specific error handling - if (e.message && e.message.includes('Fortmatic:')) { - if (e.message.includes('User denied transaction.')) { - analytics.trackBuySignatureDenied(swapQuote); - this.props.onSignatureDenied(swapQuote); - return; - } - } - throw e; - } - const startTimeUnix = new Date().getTime(); - const expectedEndTimeUnix = startTimeUnix + gasInfo.estimatedTimeMs; - this.props.onBuyProcessing(swapQuote, txHash, startTimeUnix, expectedEndTimeUnix); - try { - analytics.trackBuyTxSubmitted(swapQuote, txHash, startTimeUnix, expectedEndTimeUnix); - await web3Wrapper.awaitTransactionSuccessAsync(txHash); - } catch (e) { - if (e instanceof Error && e.message.startsWith(WEB_3_WRAPPER_TRANSACTION_FAILED_ERROR_MSG_PREFIX)) { - analytics.trackBuyTxFailed(swapQuote, txHash, startTimeUnix, expectedEndTimeUnix); - this.props.onBuyFailure(swapQuote, txHash); - return; - } - throw e; - } - analytics.trackBuyTxSucceeded(swapQuote, txHash, startTimeUnix, expectedEndTimeUnix); - this.props.onBuySuccess(swapQuote, txHash); - }; -} diff --git a/packages/instant/src/components/buy_order_progress.tsx b/packages/instant/src/components/buy_order_progress.tsx deleted file mode 100644 index 1b64972eec..0000000000 --- a/packages/instant/src/components/buy_order_progress.tsx +++ /dev/null @@ -1,35 +0,0 @@ -import * as React from 'react'; - -import { TimedProgressBar } from '../components/timed_progress_bar'; - -import { TimeCounter } from '../components/time_counter'; -import { Container } from '../components/ui/container'; -import { OrderProcessState, OrderState } from '../types'; - -export interface BuyOrderProgressProps { - swapOrderState: OrderState; -} - -export const BuyOrderProgress: React.StatelessComponent = props => { - const { swapOrderState } = props; - if ( - swapOrderState.processState === OrderProcessState.Processing || - swapOrderState.processState === OrderProcessState.Success || - swapOrderState.processState === OrderProcessState.Failure - ) { - const progress = swapOrderState.progress; - const hasEnded = swapOrderState.processState !== OrderProcessState.Processing; - const expectedTimeMs = progress.expectedEndTimeUnix - progress.startTimeUnix; - return ( - - - - - - - ); - } - return null; -}; - -BuyOrderProgress.displayName = 'BuyOrderProgress'; diff --git a/packages/instant/src/components/buy_order_state_buttons.tsx b/packages/instant/src/components/buy_order_state_buttons.tsx deleted file mode 100644 index 017a5c45e6..0000000000 --- a/packages/instant/src/components/buy_order_state_buttons.tsx +++ /dev/null @@ -1,85 +0,0 @@ -import { MarketBuySwapQuote, SwapQuoteConsumer, SwapQuoteConsumerError, SwapQuoter } from '@0x/asset-swapper'; -import { BigNumber } from '@0x/utils'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import * as React from 'react'; - -import { ColorOption } from '../style/theme'; -import { AffiliateInfo, Asset, OrderProcessState, ZeroExInstantError } from '../types'; - -import { BuyButton } from './buy_button'; -import { PlacingOrderButton } from './placing_order_button'; -import { SecondaryButton } from './secondary_button'; - -import { Button } from './ui/button'; -import { Flex } from './ui/flex'; - -export interface BuyOrderStateButtonProps { - accountAddress?: string; - accountEthBalanceInWei?: BigNumber; - swapQuote?: MarketBuySwapQuote; - swapOrderProcessingState: OrderProcessState; - swapQuoter: SwapQuoter; - swapQuoteConsumer: SwapQuoteConsumer; - web3Wrapper: Web3Wrapper; - affiliateInfo?: AffiliateInfo; - selectedAsset?: Asset; - onViewTransaction: () => void; - onValidationPending: (swapQuote: MarketBuySwapQuote) => void; - onValidationFail: ( - swapQuote: MarketBuySwapQuote, - errorMessage: SwapQuoteConsumerError | ZeroExInstantError, - ) => void; - onSignatureDenied: (swapQuote: MarketBuySwapQuote) => void; - onBuyProcessing: ( - swapQuote: MarketBuySwapQuote, - txHash: string, - startTimeUnix: number, - expectedEndTimeUnix: number, - ) => void; - onBuySuccess: (swapQuote: MarketBuySwapQuote, txHash: string) => void; - onBuyFailure: (swapQuote: MarketBuySwapQuote, txHash: string) => void; - onRetry: () => void; -} - -export const BuyOrderStateButtons: React.StatelessComponent = props => { - if (props.swapOrderProcessingState === OrderProcessState.Failure) { - return ( - - - - Details - - - ); - } else if ( - props.swapOrderProcessingState === OrderProcessState.Success || - props.swapOrderProcessingState === OrderProcessState.Processing - ) { - return View Transaction; - } else if (props.swapOrderProcessingState === OrderProcessState.Validating) { - return ; - } - - return ( - - ); -}; - -BuyOrderStateButtons.displayName = 'BuyOrderStateButtons'; diff --git a/packages/instant/src/components/coinbase_wallet_logo.tsx b/packages/instant/src/components/coinbase_wallet_logo.tsx deleted file mode 100644 index 4040a03dfb..0000000000 --- a/packages/instant/src/components/coinbase_wallet_logo.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import * as React from 'react'; - -export interface CoinbaseWalletLogoProps { - width?: number; - height?: number; -} - -export const CoinbaseWalletLogo: React.StatelessComponent = ({ width, height }) => ( - - - - -); - -CoinbaseWalletLogo.displayName = 'CoinbaseWalletLogo'; - -CoinbaseWalletLogo.defaultProps = { - width: 164, - height: 164, -}; diff --git a/packages/instant/src/components/css_reset.tsx b/packages/instant/src/components/css_reset.tsx deleted file mode 100644 index cbb7ac5faf..0000000000 --- a/packages/instant/src/components/css_reset.tsx +++ /dev/null @@ -1,32 +0,0 @@ -import { INJECTED_DIV_CLASS } from '../constants'; -import { createGlobalStyle } from '../style/theme'; - -export interface CSSResetProps {} - -/* - * Derived from - * https://github.com/jtrost/Complete-CSS-Reset - */ -export const CSSReset = createGlobalStyle` - .${INJECTED_DIV_CLASS} { - a, abbr, area, article, aside, audio, b, bdo, blockquote, body, button, - canvas, caption, cite, code, col, colgroup, command, datalist, dd, del, - details, dialog, dfn, div, dl, dt, em, embed, fieldset, figure, form, - h1, h2, h3, h4, h5, h6, head, header, hgroup, hr, html, i, iframe, img, - input, ins, keygen, kbd, label, legend, li, map, mark, menu, meter, nav, - noscript, object, ol, optgroup, option, output, p, param, pre, progress, - q, rp, rt, ruby, samp, section, select, small, span, strong, sub, sup, - table, tbody, td, textarea, tfoot, th, thead, time, tr, ul, var, video, svg { - background: transparent; - border: 0; - font-size: 100%; - font: inherit; - margin: 0; - outline: none; - padding: 0; - text-align: left; - text-decoration: none; - vertical-align: baseline; - } - } -`; diff --git a/packages/instant/src/components/erc20_asset_amount_input.tsx b/packages/instant/src/components/erc20_asset_amount_input.tsx deleted file mode 100644 index ec65198af6..0000000000 --- a/packages/instant/src/components/erc20_asset_amount_input.tsx +++ /dev/null @@ -1,166 +0,0 @@ -import { BigNumber } from '@0x/utils'; -import * as _ from 'lodash'; -import * as React from 'react'; - -import { ColorOption, transparentWhite } from '../style/theme'; -import { ERC20Asset, SimpleHandler } from '../types'; -import { assetUtils } from '../util/asset'; -import { util } from '../util/util'; - -import { ScalingAmountInput } from './scaling_amount_input'; - -import { Container } from './ui/container'; -import { Flex } from './ui/flex'; -import { Icon } from './ui/icon'; -import { Text } from './ui/text'; - -// Asset amounts only apply to ERC20 assets -export interface ERC20AssetAmountInputProps { - asset?: ERC20Asset; - value?: BigNumber; - onChange: (value?: BigNumber, asset?: ERC20Asset) => void; - onSelectAssetClick?: (asset?: ERC20Asset) => void; - startingFontSizePx: number; - fontColor?: ColorOption; - isInputDisabled: boolean; - canSelectOtherAsset: boolean; - numberOfAssetsAvailable?: number; -} - -export interface ERC20AssetAmountInputState { - currentFontSizePx: number; -} - -export class ERC20AssetAmountInput extends React.PureComponent { - public static defaultProps = { - onChange: util.boundNoop, - isDisabled: false, - }; - constructor(props: ERC20AssetAmountInputProps) { - super(props); - this.state = { - currentFontSizePx: props.startingFontSizePx, - }; - } - public render(): React.ReactNode { - const { asset } = this.props; - return ( - - {asset === undefined ? this._renderTokenSelectionContent() : this._renderContentForAsset(asset)} - - ); - } - private readonly _renderContentForAsset = (asset: ERC20Asset): React.ReactNode => { - const { onChange, isInputDisabled, ...rest } = this.props; - const amountBorderBottom = isInputDisabled ? '' : `1px solid ${transparentWhite}`; - const onSymbolClick = this._generateSelectAssetClickHandler(); - return ( - - - - - - - - {assetUtils.formattedSymbolForAsset(asset)} - - {this.props.canSelectOtherAsset && this._renderChevronIcon()} - - - - ); - }; - private readonly _renderTokenSelectionContent = (): React.ReactNode => { - const { numberOfAssetsAvailable } = this.props; - let text = 'Select Token'; - if (numberOfAssetsAvailable === undefined) { - text = 'Loading...'; - } else if (numberOfAssetsAvailable === 0) { - text = 'Tokens Unavailable'; - } - return ( - - - {text} - - {this._renderChevronIcon()} - - ); - }; - private readonly _renderChevronIcon = (): React.ReactNode => { - if (!this._areAnyAssetsAvailable()) { - return null; - } - return ( - - - - ); - }; - private readonly _handleChange = (value?: BigNumber): void => { - this.props.onChange(value, this.props.asset); - }; - private readonly _handleFontSizeChange = (fontSizePx: number): void => { - this.setState({ - currentFontSizePx: fontSizePx, - }); - }; - private readonly _generateSelectAssetClickHandler = (): SimpleHandler | undefined => { - // We don't want to allow opening the token selection panel if there are no assets. - // Since styles are inferred from the presence of a click handler, we want to return undefined - // instead of providing a noop. - if (!this._areAnyAssetsAvailable() || this.props.onSelectAssetClick === undefined) { - return undefined; - } - return this._handleSelectAssetClick; - }; - private readonly _areAnyAssetsAvailable = (): boolean => { - const { numberOfAssetsAvailable } = this.props; - return numberOfAssetsAvailable !== undefined && numberOfAssetsAvailable > 0; - }; - private readonly _handleSelectAssetClick = (): void => { - if (this.props.onSelectAssetClick) { - this.props.onSelectAssetClick(); - } - }; - // For assets with symbols of different length, - // start scaling the input at different character lengths - private readonly _textLengthThresholdForAsset = (asset?: ERC20Asset): number => { - if (asset === undefined) { - return 3; - } - const symbol = asset.metaData.symbol; - if (symbol.length <= 3) { - return 5; - } - if (symbol.length === 5) { - return 3; - } - return 4; - }; -} diff --git a/packages/instant/src/components/erc20_token_selector.tsx b/packages/instant/src/components/erc20_token_selector.tsx deleted file mode 100644 index 91e4eb75e3..0000000000 --- a/packages/instant/src/components/erc20_token_selector.tsx +++ /dev/null @@ -1,176 +0,0 @@ -import * as _ from 'lodash'; -import * as React from 'react'; - -import { ColorOption } from '../style/theme'; -import { ERC20Asset } from '../types'; -import { analytics } from '../util/analytics'; -import { assetUtils } from '../util/asset'; - -import { SearchInput } from './search_input'; -import { Circle } from './ui/circle'; -import { Container } from './ui/container'; -import { Flex } from './ui/flex'; -import { Text } from './ui/text'; - -export interface ERC20TokenSelectorProps { - tokens: ERC20Asset[]; - onTokenSelect: (token: ERC20Asset) => void; -} - -export interface ERC20TokenSelectorState { - searchQuery: string; -} - -export class ERC20TokenSelector extends React.PureComponent { - public state: ERC20TokenSelectorState = { - searchQuery: '', - }; - public render(): React.ReactNode { - const { tokens } = this.props; - return ( - - - - Select Token - - - - - - - - ); - } - private readonly _handleSearchInputChange = (event: React.ChangeEvent): void => { - const searchQuery = event.target.value; - this.setState({ - searchQuery, - }); - analytics.trackTokenSelectorSearched(searchQuery); - }; - private readonly _handleTokenClick = (token: ERC20Asset): void => { - this.props.onTokenSelect(token); - }; -} - -interface TokenRowFilterProps { - tokens: ERC20Asset[]; - onClick: (token: ERC20Asset) => void; - searchQuery: string; -} - -class TokenRowFilter extends React.Component { - public render(): React.ReactNode { - return _.map(this.props.tokens, token => { - if (!this._isTokenQueryMatch(token)) { - return null; - } - return ; - }); - } - public shouldComponentUpdate(nextProps: TokenRowFilterProps): boolean { - const arePropsDeeplyEqual = _.isEqual(nextProps, this.props); - return !arePropsDeeplyEqual; - } - private readonly _isTokenQueryMatch = (token: ERC20Asset): boolean => { - const { searchQuery } = this.props; - const searchQueryLowerCase = searchQuery.toLowerCase().trim(); - if (searchQueryLowerCase === '') { - return true; - } - const tokenName = token.metaData.name.toLowerCase(); - const tokenSymbol = token.metaData.symbol.toLowerCase(); - return _.startsWith(tokenSymbol, searchQueryLowerCase) || _.startsWith(tokenName, searchQueryLowerCase); - }; -} - -interface TokenSelectorRowProps { - token: ERC20Asset; - onClick: (token: ERC20Asset) => void; -} - -class TokenSelectorRow extends React.PureComponent { - public render(): React.ReactNode { - const { token } = this.props; - const circleColor = token.metaData.primaryColor || 'black'; - const displaySymbol = assetUtils.bestNameForAsset(token); - return ( - - - - - - - - - - - - {displaySymbol} - - - - - - {token.metaData.name} - - - - ); - } - private readonly _handleClick = (): void => { - this.props.onClick(this.props.token); - }; -} - -interface TokenSelectorRowIconProps { - token: ERC20Asset; -} - -const getTokenIcon = (symbol: string): React.StatelessComponent | undefined => { - try { - return require(`../assets/icons/${symbol}.svg`).default as React.StatelessComponent; - } catch (e) { - // Can't find icon - return undefined; - } -}; - -class TokenSelectorRowIcon extends React.PureComponent { - public render(): React.ReactNode { - const { token } = this.props; - const iconUrlIfExists = token.metaData.iconUrl; - - const TokenIcon = getTokenIcon(token.metaData.symbol); - const displaySymbol = assetUtils.bestNameForAsset(token); - if (iconUrlIfExists !== undefined) { - return ; - } else if (TokenIcon !== undefined) { - return ; - } else { - return ( - - {displaySymbol} - - ); - } - } -} diff --git a/packages/instant/src/components/install_wallet_panel_content.tsx b/packages/instant/src/components/install_wallet_panel_content.tsx deleted file mode 100644 index 1af3dafbbc..0000000000 --- a/packages/instant/src/components/install_wallet_panel_content.tsx +++ /dev/null @@ -1,75 +0,0 @@ -import * as React from 'react'; - -import { - META_MASK_CHROME_STORE_URL, - META_MASK_FIREFOX_STORE_URL, - META_MASK_OPERA_STORE_URL, - META_MASK_SITE_URL, -} from '../constants'; -import { ColorOption } from '../style/theme'; -import { Browser } from '../types'; -import { analytics } from '../util/analytics'; -import { envUtil } from '../util/env'; -import { util } from '../util/util'; - -import { MetaMaskLogo } from './meta_mask_logo'; -import { StandardPanelContent, StandardPanelContentProps } from './standard_panel_content'; -import { Button } from './ui/button'; - -export interface InstallWalletPanelContentProps {} - -export class InstallWalletPanelContent extends React.PureComponent { - public render(): React.ReactNode { - const panelProps = this._getStandardPanelContentProps(); - return ; - } - private readonly _getStandardPanelContentProps = (): StandardPanelContentProps => { - const browser = envUtil.getBrowser(); - let description = 'Please install the MetaMask wallet browser extension.'; - let actionText = 'Learn More'; - let actionUrl = META_MASK_SITE_URL; - switch (browser) { - case Browser.Chrome: - description = 'Please install the MetaMask wallet browser extension from the Chrome Store.'; - actionText = 'Get Chrome Extension'; - actionUrl = META_MASK_CHROME_STORE_URL; - break; - case Browser.Firefox: - description = 'Please install the MetaMask wallet browser extension from the Firefox Store.'; - actionText = 'Get Firefox Extension'; - actionUrl = META_MASK_FIREFOX_STORE_URL; - break; - case Browser.Opera: - description = 'Please install the MetaMask wallet browser extension from the Opera Store.'; - actionText = 'Get Opera Add-on'; - actionUrl = META_MASK_OPERA_STORE_URL; - break; - default: - break; - } - const onActionClick = () => { - analytics.trackInstallWalletModalClickedGet(); - util.createOpenUrlInNewWindow(actionUrl)(); - }; - return { - image: , - title: 'Install MetaMask', - description, - moreInfoSettings: { - href: META_MASK_SITE_URL, - text: 'What is MetaMask?', - onClick: analytics.trackInstallWalletModalClickedExplanation, - }, - action: ( - - ), - }; - }; -} diff --git a/packages/instant/src/components/instant_heading.tsx b/packages/instant/src/components/instant_heading.tsx deleted file mode 100644 index 6ba9288d0d..0000000000 --- a/packages/instant/src/components/instant_heading.tsx +++ /dev/null @@ -1,201 +0,0 @@ -import { AssetProxyId } from '@0x/types'; -import { BigNumber } from '@0x/utils'; -import * as _ from 'lodash'; -import * as React from 'react'; - -import { SelectedERC20AssetAmountInput } from '../containers/selected_erc20_asset_amount_input'; -import { ColorOption } from '../style/theme'; -import { Asset, AsyncProcessState, ERC20Asset, ERC721Asset, OrderProcessState, OrderState } from '../types'; -import { format } from '../util/format'; - -import { AmountPlaceholder } from './amount_placeholder'; -import { Container } from './ui/container'; -import { Flex } from './ui/flex'; -import { Icon } from './ui/icon'; -import { Image } from './ui/image'; -import { Spinner } from './ui/spinner'; -import { Text } from './ui/text'; - -export interface InstantHeadingProps { - selectedAsset?: Asset; - selectedAssetUnitAmount?: BigNumber; - totalEthBaseUnitAmount?: BigNumber; - ethUsdPrice?: BigNumber; - quoteRequestState: AsyncProcessState; - swapOrderState: OrderState; - onSelectAssetClick?: (asset?: ERC20Asset) => void; -} - -const PLACEHOLDER_COLOR = ColorOption.white; -const ICON_WIDTH = 34; -const ICON_HEIGHT = 34; -const ICON_COLOR = ColorOption.white; - -export class InstantHeading extends React.PureComponent { - public render(): React.ReactNode { - return this._renderAssetHeadingContent(); - } - - private _renderAssetHeadingContent(): React.ReactNode { - const { selectedAsset } = this.props; - if (selectedAsset === undefined) { - // TODO: Only the ERC20 flow supports selecting assets. - return this._renderERC20AssetHeading(); - } - if (selectedAsset.metaData.assetProxyId === AssetProxyId.ERC20) { - return this._renderERC20AssetHeading(); - } else if (selectedAsset.metaData.assetProxyId === AssetProxyId.ERC721) { - return this._renderERC721AssetHeading(selectedAsset as ERC721Asset); - } - return null; - } - // tslint:disable-next-line:prefer-function-over-method - private _renderERC721AssetHeading(asset: ERC721Asset): React.ReactNode { - return ( - - - - {asset.metaData.name} - - - - - - - - - - - ); - } - - private _renderERC20AssetHeading(): React.ReactNode { - const iconOrAmounts = this._renderIcon() || this._renderAmountsSection(); - return ( - - - - {this._renderTopText()} - - - - - - - - {iconOrAmounts} - - - - ); - } - - private _renderAmountsSection(): React.ReactNode { - if ( - this.props.totalEthBaseUnitAmount === undefined && - this.props.quoteRequestState !== AsyncProcessState.Pending - ) { - return null; - } else { - return ( - - {this._renderPlaceholderOrAmount(this._renderEthAmount)} - {this._renderPlaceholderOrAmount(this._renderDollarAmount)} - - ); - } - } - - private _renderIcon(): React.ReactNode { - const processState = this.props.swapOrderState.processState; - - if (processState === OrderProcessState.Failure) { - return ; - } else if (processState === OrderProcessState.Processing) { - return ; - } else if (processState === OrderProcessState.Success) { - return ; - } - return undefined; - } - - private _renderTopText(): React.ReactNode { - const processState = this.props.swapOrderState.processState; - if (processState === OrderProcessState.Failure) { - return 'Order failed'; - } else if (processState === OrderProcessState.Processing) { - return 'Processing Order...'; - } else if (processState === OrderProcessState.Success) { - return 'Tokens received!'; - } - - return 'I want to buy'; - } - - private _renderPlaceholderOrAmount(amountFunction: () => React.ReactNode): React.ReactNode { - if (this.props.quoteRequestState === AsyncProcessState.Pending) { - return ; - } - if (this.props.selectedAssetUnitAmount === undefined) { - return ; - } - return amountFunction(); - } - - private readonly _renderEthAmount = (): React.ReactNode => { - const ethAmount = format.ethBaseUnitAmount( - this.props.totalEthBaseUnitAmount, - 4, - , - ); - - const fontSize = _.isString(ethAmount) && ethAmount.length >= 13 ? '14px' : '16px'; - return ( - - {ethAmount} - - ); - }; - - private readonly _renderDollarAmount = (): React.ReactNode => { - return ( - - {format.ethBaseUnitAmountInUsd( - this.props.totalEthBaseUnitAmount, - this.props.ethUsdPrice, - 2, - , - )} - - ); - }; -} diff --git a/packages/instant/src/components/meta_mask_logo.tsx b/packages/instant/src/components/meta_mask_logo.tsx deleted file mode 100644 index bfbc67270f..0000000000 --- a/packages/instant/src/components/meta_mask_logo.tsx +++ /dev/null @@ -1,80 +0,0 @@ -import * as React from 'react'; - -export interface MetaMaskLogoProps { - width?: number; - height?: number; -} - -export const MetaMaskLogo: React.StatelessComponent = ({ width, height }) => ( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -); - -MetaMaskLogo.displayName = 'MetaMaskLogo'; - -MetaMaskLogo.defaultProps = { - width: 85, - height: 80, -}; diff --git a/packages/instant/src/components/order_details.tsx b/packages/instant/src/components/order_details.tsx deleted file mode 100644 index b0df6297c9..0000000000 --- a/packages/instant/src/components/order_details.tsx +++ /dev/null @@ -1,243 +0,0 @@ -import { SwapQuoteInfo } from '@0x/asset-swapper'; -import { BigNumber } from '@0x/utils'; -import * as _ from 'lodash'; -import * as React from 'react'; -import { oc } from 'ts-optchain'; - -import { BIG_NUMBER_ZERO, DEFAULT_UNKOWN_ASSET_NAME } from '../constants'; -import { ColorOption } from '../style/theme'; -import { Account, AccountState, BaseCurrency } from '../types'; -import { format } from '../util/format'; - -import { AmountPlaceholder } from './amount_placeholder'; -import { SectionHeader } from './section_header'; - -import { Container } from './ui/container'; -import { Flex } from './ui/flex'; -import { Text, TextProps } from './ui/text'; - -export interface OrderDetailsProps { - swapQuoteInfo?: SwapQuoteInfo; - selectedAssetUnitAmount?: BigNumber; - ethUsdPrice?: BigNumber; - isLoading: boolean; - assetName?: string; - baseCurrency: BaseCurrency; - onBaseCurrencySwitchEth: () => void; - onBaseCurrencySwitchUsd: () => void; - account: Account; -} -export class OrderDetails extends React.PureComponent { - public render(): React.ReactNode { - const shouldShowUsdError = this.props.baseCurrency === BaseCurrency.USD && this._hadErrorFetchingUsdPrice(); - const { state } = this.props.account; - if (state !== AccountState.Ready) { - return null; - } else { - return ( - - {this._renderHeader()} - {shouldShowUsdError ? this._renderErrorFetchingUsdPrice() : this._renderRows()} - - ); - } - } - - private _renderRows(): React.ReactNode { - const { swapQuoteInfo } = this.props; - return ( - - - - - - ); - } - - private _renderErrorFetchingUsdPrice(): React.ReactNode { - return ( - - There was an error fetching the USD price. - - Click here - - {' to view ETH prices'} - - ); - } - - private _hadErrorFetchingUsdPrice(): boolean { - return this.props.ethUsdPrice ? this.props.ethUsdPrice.isEqualTo(BIG_NUMBER_ZERO) : false; - } - - private _totalCostSecondaryValue(): React.ReactNode { - const secondaryCurrency = this.props.baseCurrency === BaseCurrency.USD ? BaseCurrency.ETH : BaseCurrency.USD; - - const canDisplayCurrency = - secondaryCurrency === BaseCurrency.ETH || - (secondaryCurrency === BaseCurrency.USD && this.props.ethUsdPrice && !this._hadErrorFetchingUsdPrice()); - - if (this.props.swapQuoteInfo && canDisplayCurrency) { - return this._displayAmount( - secondaryCurrency, - this.props.swapQuoteInfo.totalTakerAssetAmount.plus(this.props.swapQuoteInfo.protocolFeeInWeiAmount), - ); - } else { - return undefined; - } - } - - private _displayAmountOrPlaceholder(weiAmount?: BigNumber): React.ReactNode { - const { baseCurrency, isLoading } = this.props; - - if (weiAmount === undefined) { - return ( - - - - ); - } - - return this._displayAmount(baseCurrency, weiAmount); - } - - private _displayAmount(currency: BaseCurrency, weiAmount: BigNumber): React.ReactNode { - switch (currency) { - case BaseCurrency.USD: - return format.ethBaseUnitAmountInUsd(weiAmount, this.props.ethUsdPrice, 2, ''); - case BaseCurrency.ETH: - return format.ethBaseUnitAmount(weiAmount, 4, ''); - } - } - - private _assetAmountLabel(): React.ReactNode { - const { assetName, baseCurrency } = this.props; - const numTokens = this.props.selectedAssetUnitAmount; - - // Display as 0 if we have a selected asset - const displayNumTokens = - assetName && assetName !== DEFAULT_UNKOWN_ASSET_NAME && numTokens === undefined - ? new BigNumber(0) - : numTokens; - if (displayNumTokens !== undefined) { - let numTokensWithSymbol: React.ReactNode = displayNumTokens.toString(); - if (assetName) { - numTokensWithSymbol += ` ${assetName}`; - } - const pricePerTokenWei = this._pricePerTokenWei(); - if (pricePerTokenWei) { - const atPriceDisplay = ( - - @ {this._displayAmount(baseCurrency, pricePerTokenWei)} - - ); - numTokensWithSymbol = ( - - {numTokensWithSymbol} {atPriceDisplay} - - ); - } - return numTokensWithSymbol; - } - return 'Token Amount'; - } - - private _pricePerTokenWei(): BigNumber | undefined { - const swapQuoteAccessor = oc(this.props.swapQuoteInfo); - const assetTotalInWei = swapQuoteAccessor.totalTakerAssetAmount(); - const selectedAssetUnitAmount = this.props.selectedAssetUnitAmount; - return assetTotalInWei !== undefined && - selectedAssetUnitAmount !== undefined && - !selectedAssetUnitAmount.eq(BIG_NUMBER_ZERO) - ? assetTotalInWei.div(selectedAssetUnitAmount).integerValue(BigNumber.ROUND_CEIL) - : undefined; - } - - private _baseCurrencyChoice(choice: BaseCurrency): React.ReactNode { - const onClick = - choice === BaseCurrency.ETH ? this.props.onBaseCurrencySwitchEth : this.props.onBaseCurrencySwitchUsd; - const isSelected = this.props.baseCurrency === choice; - - const textStyle: TextProps = { onClick, fontSize: '12px' }; - if (isSelected) { - textStyle.fontColor = ColorOption.primaryColor; - textStyle.fontWeight = 700; - } else { - textStyle.fontColor = ColorOption.lightGrey; - } - return {choice}; - } - - private _renderHeader(): React.ReactNode { - return ( - - Order Details - - {this._baseCurrencyChoice(BaseCurrency.ETH)} - - - / - - - {this._baseCurrencyChoice(BaseCurrency.USD)} - - - ); - } -} - -export interface OrderDetailsRowProps { - labelText: React.ReactNode; - isLabelBold?: boolean; - isPrimaryValueBold?: boolean; - primaryValue: React.ReactNode; - secondaryValue?: React.ReactNode; -} -export class OrderDetailsRow extends React.PureComponent { - public render(): React.ReactNode { - return ( - - - - {this.props.labelText} - - {this._renderValues()} - - - ); - } - - private _renderValues(): React.ReactNode { - const secondaryValueNode: React.ReactNode = this.props.secondaryValue && ( - - ({this.props.secondaryValue}) - - ); - return ( - - {secondaryValueNode} - {this.props.primaryValue} - - ); - } -} diff --git a/packages/instant/src/components/payment_method.tsx b/packages/instant/src/components/payment_method.tsx deleted file mode 100644 index 25e4f081ba..0000000000 --- a/packages/instant/src/components/payment_method.tsx +++ /dev/null @@ -1,143 +0,0 @@ -import * as React from 'react'; - -import PhoneIconSvg from '../assets/icons/phone.svg'; -import { ColorOption } from '../style/theme'; -import { Account, AccountState, Network, ProviderType } from '../types'; -import { envUtil } from '../util/env'; - -import { CoinbaseWalletLogo } from './coinbase_wallet_logo'; -import { MetaMaskLogo } from './meta_mask_logo'; -import { PaymentMethodDropdown } from './payment_method_dropdown'; -import { SectionHeader } from './section_header'; -import { Container } from './ui/container'; -import { Flex } from './ui/flex'; -import { WalletPrompt } from './wallet_prompt'; - -export interface PaymentMethodProps { - account: Account; - network: Network; - walletDisplayName: string; - onInstallWalletClick: () => void; - onUnlockWalletClick: (providerType: ProviderType) => void; -} - -export class PaymentMethod extends React.PureComponent { - public render(): React.ReactNode { - const marginBottom = this.props.account.state !== AccountState.Ready ? '77px' : null; - return ( - - - - {this._renderTitleText()} - - - {this._renderMainContent()} - - ); - } - private readonly _renderTitleText = (): string => { - const { account } = this.props; - switch (account.state) { - case AccountState.Loading: - return 'loading...'; - case AccountState.Locked: - case AccountState.None: - return 'connect your wallet'; - case AccountState.Ready: - return 'payment method'; - } - }; - private readonly _renderMainContent = (): React.ReactNode => { - const { account, network } = this.props; - const isMobile = envUtil.isMobileOperatingSystem(); - const metamaskLogo = ; - const logo = isMobile ? : metamaskLogo; - const primaryColor = ColorOption.grey; - const secondaryColor = ColorOption.whiteBackground; - const colors = { primaryColor, secondaryColor }; - const onUnlockGenericWallet = () => { - this.props.onUnlockWalletClick(ProviderType.MetaMask); - }; - const onUnlockFormatic = () => this.props.onUnlockWalletClick(ProviderType.Fortmatic); - switch (account.state) { - case AccountState.Loading: - return null; - case AccountState.Locked: - return ( - - - {logo} - - } - {...colors} - > - {isMobile ? 'Coinbase Wallet' : 'MetaMask'} - - - - - } - display="flex" - {...colors} - > - Use phone number - - - ); - case AccountState.None: - return ( - - - {isMobile ? 'Install Coinbase Wallet' : 'Install MetaMask'} - - - - - } - display="flex" - {...colors} - > - Use phone number - - - ); - case AccountState.Ready: - return ( - - ); - } - }; -} diff --git a/packages/instant/src/components/payment_method_dropdown.tsx b/packages/instant/src/components/payment_method_dropdown.tsx deleted file mode 100644 index e463e3eaef..0000000000 --- a/packages/instant/src/components/payment_method_dropdown.tsx +++ /dev/null @@ -1,60 +0,0 @@ -import { BigNumber } from '@0x/utils'; -import * as copy from 'copy-to-clipboard'; -import * as React from 'react'; - -import { Network } from '../types'; -import { analytics } from '../util/analytics'; -import { envUtil } from '../util/env'; -import { etherscanUtil } from '../util/etherscan'; -import { format } from '../util/format'; - -import { Dropdown, DropdownItemConfig } from './ui/dropdown'; - -export interface PaymentMethodDropdownProps { - accountAddress: string; - accountEthBalanceInWei?: BigNumber; - network: Network; -} - -export class PaymentMethodDropdown extends React.PureComponent { - public render(): React.ReactNode { - const { accountAddress, accountEthBalanceInWei } = this.props; - const value = format.ethAddress(accountAddress); - const label = format.ethBaseUnitAmount(accountEthBalanceInWei, 4, '') as string; - return ( - - ); - } - private readonly _getDropdownItemConfigs = (): DropdownItemConfig[] => { - if (envUtil.isMobileOperatingSystem()) { - return []; - } - const viewOnEtherscan = { - text: 'View on Etherscan', - onClick: this._handleEtherscanClick, - }; - const copyAddressToClipboard = { - text: 'Copy address to clipboard', - onClick: this._handleCopyToClipboardClick, - }; - return [viewOnEtherscan, copyAddressToClipboard]; - }; - private readonly _handleEtherscanClick = (): void => { - analytics.trackPaymentMethodOpenedEtherscan(); - - const { accountAddress, network } = this.props; - const etherscanUrl = etherscanUtil.getEtherScanEthAddressIfExists(accountAddress, network); - window.open(etherscanUrl, '_blank'); - }; - private readonly _handleCopyToClipboardClick = (): void => { - analytics.trackPaymentMethodCopiedAddress(); - - const { accountAddress } = this.props; - copy(accountAddress); - }; -} diff --git a/packages/instant/src/components/placing_order_button.tsx b/packages/instant/src/components/placing_order_button.tsx deleted file mode 100644 index 528a305dca..0000000000 --- a/packages/instant/src/components/placing_order_button.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import * as React from 'react'; - -import { ColorOption } from '../style/theme'; - -import { Button } from './ui/button'; -import { Container } from './ui/container'; -import { Spinner } from './ui/spinner'; - -export const PlacingOrderButton: React.StatelessComponent<{}> = props => ( - -); - -PlacingOrderButton.displayName = 'PlacingOrderButton'; diff --git a/packages/instant/src/components/scaling_amount_input.tsx b/packages/instant/src/components/scaling_amount_input.tsx deleted file mode 100644 index d8abfe5022..0000000000 --- a/packages/instant/src/components/scaling_amount_input.tsx +++ /dev/null @@ -1,92 +0,0 @@ -import { BigNumber } from '@0x/utils'; -import * as _ from 'lodash'; -import * as React from 'react'; - -import { Maybe } from '../types'; - -import { GIT_SHA, MAGIC_TRIGGER_ERROR_INPUT, MAGIC_TRIGGER_ERROR_MESSAGE, NPM_PACKAGE_VERSION } from '../constants'; -import { ColorOption } from '../style/theme'; -import { maybeBigNumberUtil } from '../util/maybe_big_number'; -import { util } from '../util/util'; - -import { ScalingInput } from './scaling_input'; - -export interface ScalingAmountInputProps { - isDisabled: boolean; - maxFontSizePx: number; - textLengthThreshold: number; - fontColor?: ColorOption; - value?: BigNumber; - onAmountChange: (value?: BigNumber) => void; - onFontSizeChange: (fontSizePx: number) => void; - hasAutofocus: boolean; -} -interface ScalingAmountInputState { - stringValue: string; -} - -const { stringToMaybeBigNumber, areMaybeBigNumbersEqual } = maybeBigNumberUtil; -export class ScalingAmountInput extends React.PureComponent { - public static defaultProps = { - onAmountChange: util.boundNoop, - onFontSizeChange: util.boundNoop, - isDisabled: false, - hasAutofocus: false, - }; - public constructor(props: ScalingAmountInputProps) { - super(props); - this.state = { - stringValue: props.value === undefined ? '' : props.value.toString(), - }; - } - public componentDidUpdate(): void { - const parsedStateValue = stringToMaybeBigNumber(this.state.stringValue); - const currentValue = this.props.value; - - if (!areMaybeBigNumbersEqual(parsedStateValue, currentValue)) { - // we somehow got into the state in which the value passed in and the string value - // in state have differed, reset state - // we dont expect to ever get into this state, but let's make sure - // we reset if we do since we're dealing with important numbers - this.setState({ - stringValue: currentValue === undefined ? '' : currentValue.toString(), - }); - } - } - - public render(): React.ReactNode { - const { textLengthThreshold, fontColor, maxFontSizePx, onFontSizeChange } = this.props; - return ( - - ); - } - private readonly _handleChange = (event: React.ChangeEvent): void => { - if (event.target.value === MAGIC_TRIGGER_ERROR_INPUT) { - throw new Error(`${MAGIC_TRIGGER_ERROR_MESSAGE} git: ${GIT_SHA}, npm: ${NPM_PACKAGE_VERSION}`); - } - - const sanitizedValue = event.target.value.replace(/[^0-9.]/g, ''); // only allow numbers and "." - this.setState({ - stringValue: sanitizedValue, - }); - - // Trigger onAmountChange with a valid BigNumber, or undefined if the sanitizedValue is invalid or empty - const bigNumberValue: Maybe = _.isEmpty(sanitizedValue) - ? undefined - : stringToMaybeBigNumber(sanitizedValue); - - this.props.onAmountChange(bigNumberValue); - }; -} diff --git a/packages/instant/src/components/scaling_input.tsx b/packages/instant/src/components/scaling_input.tsx deleted file mode 100644 index 560985609a..0000000000 --- a/packages/instant/src/components/scaling_input.tsx +++ /dev/null @@ -1,165 +0,0 @@ -import { ObjectMap } from '@0x/types'; -import * as _ from 'lodash'; -import * as React from 'react'; - -import { ColorOption } from '../style/theme'; -import { util } from '../util/util'; - -import { Input } from './ui/input'; - -export enum ScalingInputPhase { - FixedFontSize, - ScalingFontSize, -} - -export interface ScalingSettings { - percentageToReduceFontSizePerCharacter: number; - // 1ch = the width of the 0 chararacter. - // Allow to customize 'char' length for different characters. - characterWidthOverrides: ObjectMap; - // How much room to leave to the right of the scaling input. - additionalInputSpaceInCh: number; -} - -export interface ScalingInputProps { - type?: string; - textLengthThreshold: number; - maxFontSizePx: number; - value: string; - emptyInputWidthCh: number; - onChange: (event: React.ChangeEvent) => void; - onFontSizeChange: (fontSizePx: number) => void; - fontColor?: ColorOption; - placeholder?: string; - maxLength?: number; - scalingSettings: ScalingSettings; - isDisabled: boolean; - hasAutofocus: boolean; -} - -export interface ScalingInputSnapshot { - inputWidthPx: number; -} - -// These are magic numbers that were determined experimentally. -const defaultScalingSettings: ScalingSettings = { - percentageToReduceFontSizePerCharacter: 0.1, - characterWidthOverrides: { - '1': 0.7, - '.': 0.4, - }, - additionalInputSpaceInCh: 0.4, -}; - -export class ScalingInput extends React.PureComponent { - public static defaultProps = { - onChange: util.boundNoop, - onFontSizeChange: util.boundNoop, - maxLength: 9, - scalingSettings: defaultScalingSettings, - isDisabled: false, - hasAutofocus: false, - }; - private readonly _inputRef = React.createRef(); - public static getPhase(textLengthThreshold: number, value: string): ScalingInputPhase { - if (value.length <= textLengthThreshold) { - return ScalingInputPhase.FixedFontSize; - } - return ScalingInputPhase.ScalingFontSize; - } - public static getPhaseFromProps(props: ScalingInputProps): ScalingInputPhase { - const { value, textLengthThreshold } = props; - return ScalingInput.getPhase(textLengthThreshold, value); - } - public static calculateFontSize( - textLengthThreshold: number, - maxFontSizePx: number, - phase: ScalingInputPhase, - value: string, - percentageToReduceFontSizePerCharacter: number, - ): number { - if (phase !== ScalingInputPhase.ScalingFontSize) { - return maxFontSizePx; - } - const charactersOverMax = value.length - textLengthThreshold; - const scalingFactor = (1 - percentageToReduceFontSizePerCharacter) ** charactersOverMax; - const fontSize = scalingFactor * maxFontSizePx; - return fontSize; - } - public static calculateFontSizeFromProps(props: ScalingInputProps, phase: ScalingInputPhase): number { - const { textLengthThreshold, value, maxFontSizePx, scalingSettings } = props; - return ScalingInput.calculateFontSize( - textLengthThreshold, - maxFontSizePx, - phase, - value, - scalingSettings.percentageToReduceFontSizePerCharacter, - ); - } - public componentDidMount(): void { - // Trigger an initial notification of the calculated fontSize. - const currentPhase = ScalingInput.getPhaseFromProps(this.props); - const currentFontSize = ScalingInput.calculateFontSizeFromProps(this.props, currentPhase); - this.props.onFontSizeChange(currentFontSize); - } - public componentDidUpdate(prevProps: ScalingInputProps): void { - const prevPhase = ScalingInput.getPhaseFromProps(prevProps); - const curPhase = ScalingInput.getPhaseFromProps(this.props); - const prevFontSize = ScalingInput.calculateFontSizeFromProps(prevProps, prevPhase); - const curFontSize = ScalingInput.calculateFontSizeFromProps(this.props, curPhase); - // If font size has changed, notify. - if (prevFontSize !== curFontSize) { - this.props.onFontSizeChange(curFontSize); - } - } - public render(): React.ReactNode { - const { type, hasAutofocus, isDisabled, fontColor, placeholder, value, maxLength } = this.props; - const phase = ScalingInput.getPhaseFromProps(this.props); - return ( - - ); - } - private readonly _calculateWidth = (phase: ScalingInputPhase): string => { - const { value, scalingSettings } = this.props; - if (_.isEmpty(value)) { - return `${this.props.emptyInputWidthCh}ch`; - } - const lengthInCh = _.reduce( - value.split(''), - (sum, char) => { - const widthOverride = scalingSettings.characterWidthOverrides[char]; - if (widthOverride !== undefined) { - // tslint is confused - // tslint:disable-next-line:restrict-plus-operands - return sum + widthOverride; - } - return sum + 1; - }, - scalingSettings.additionalInputSpaceInCh, - ); - return `${lengthInCh}ch`; - }; - private readonly _calculateFontSize = (phase: ScalingInputPhase): number => { - return ScalingInput.calculateFontSizeFromProps(this.props, phase); - }; - private readonly _handleChange = (event: React.ChangeEvent): void => { - const value = event.target.value; - const { maxLength } = this.props; - if (value !== undefined && maxLength !== undefined && value.length > maxLength) { - return; - } - this.props.onChange(event); - }; -} diff --git a/packages/instant/src/components/search_input.tsx b/packages/instant/src/components/search_input.tsx deleted file mode 100644 index 71bc189153..0000000000 --- a/packages/instant/src/components/search_input.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import * as _ from 'lodash'; -import * as React from 'react'; - -import { ColorOption } from '../style/theme'; - -import { Container } from './ui/container'; -import { Flex } from './ui/flex'; -import { Icon } from './ui/icon'; -import { Input, InputProps } from './ui/input'; - -export interface SearchInputProps extends InputProps { - backgroundColor?: ColorOption; -} - -export const SearchInput: React.StatelessComponent = props => ( - - - - - - -); - -SearchInput.displayName = 'SearchInput'; - -SearchInput.defaultProps = { - backgroundColor: ColorOption.lightestGrey, - fontColor: ColorOption.grey, -}; diff --git a/packages/instant/src/components/secondary_button.tsx b/packages/instant/src/components/secondary_button.tsx deleted file mode 100644 index 0714ce2870..0000000000 --- a/packages/instant/src/components/secondary_button.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import * as _ from 'lodash'; -import * as React from 'react'; - -import { ColorOption } from '../style/theme'; - -import { Button, ButtonProps } from './ui/button'; - -export interface SecondaryButtonProps extends ButtonProps {} - -export const SecondaryButton: React.StatelessComponent = props => { - const buttonProps = _.omit(props, 'text'); - return ( - - ); -}; -SecondaryButton.defaultProps = { - width: '100%', -}; -SecondaryButton.displayName = 'SecondaryButton'; diff --git a/packages/instant/src/components/section_header.tsx b/packages/instant/src/components/section_header.tsx deleted file mode 100644 index 2185b67ba0..0000000000 --- a/packages/instant/src/components/section_header.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import * as React from 'react'; - -import { ColorOption } from '../style/theme'; - -import { Text } from './ui/text'; - -export interface SectionHeaderProps {} -export const SectionHeader: React.StatelessComponent = props => { - return ( - - {props.children} - - ); -}; -SectionHeader.displayName = 'SectionHeader'; diff --git a/packages/instant/src/components/sliding_error.tsx b/packages/instant/src/components/sliding_error.tsx deleted file mode 100644 index c7c6732cfc..0000000000 --- a/packages/instant/src/components/sliding_error.tsx +++ /dev/null @@ -1,100 +0,0 @@ -import * as React from 'react'; - -import { ScreenSpecification } from '../style/media'; -import { ColorOption } from '../style/theme'; -import { zIndex } from '../style/z_index'; -import { SlideAnimationState } from '../types'; - -import { PositionAnimationSettings } from './animations/position_animation'; -import { SlideAnimation } from './animations/slide_animation'; - -import { Container } from './ui/container'; -import { Flex } from './ui/flex'; -import { Text } from './ui/text'; - -export interface ErrorProps { - icon: string; - message: string; -} - -export const Error: React.StatelessComponent = props => ( - - - - {props.icon} - - - {props.message} - - - -); - -Error.displayName = 'Error'; - -export interface SlidingErrorProps extends ErrorProps { - animationState: SlideAnimationState; -} -export const SlidingError: React.StatelessComponent = props => { - const slideAmount = '120px'; - - const desktopSlideIn: PositionAnimationSettings = { - timingFunction: 'ease-in', - top: { - from: slideAmount, - to: '0px', - }, - position: 'relative', - }; - const desktopSlideOut: PositionAnimationSettings = { - timingFunction: 'cubic-bezier(0.25, 0.1, 0.25, 1)', - top: { - from: '0px', - to: slideAmount, - }, - position: 'relative', - }; - - const mobileSlideIn: PositionAnimationSettings = { - duration: '0.5s', - timingFunction: 'ease-in', - top: { from: '-120px', to: '0px' }, - position: 'fixed', - }; - const moblieSlideOut: PositionAnimationSettings = { - duration: '0.5s', - timingFunction: 'ease-in', - top: { from: '0px', to: '-120px' }, - position: 'fixed', - }; - - const slideUpSettings: ScreenSpecification = { - default: desktopSlideIn, - sm: mobileSlideIn, - }; - const slideOutSettings: ScreenSpecification = { - default: desktopSlideOut, - sm: moblieSlideOut, - }; - - return ( - - - - ); -}; - -SlidingError.displayName = 'SlidingError'; diff --git a/packages/instant/src/components/sliding_panel.tsx b/packages/instant/src/components/sliding_panel.tsx deleted file mode 100644 index 9b09a0d804..0000000000 --- a/packages/instant/src/components/sliding_panel.tsx +++ /dev/null @@ -1,73 +0,0 @@ -import * as React from 'react'; - -import { ColorOption } from '../style/theme'; -import { zIndex } from '../style/z_index'; -import { SlideAnimationState } from '../types'; - -import { PositionAnimationSettings } from './animations/position_animation'; -import { SlideAnimation } from './animations/slide_animation'; - -import { Container } from './ui/container'; -import { Flex } from './ui/flex'; -import { Icon } from './ui/icon'; - -export interface PanelProps { - onClose?: () => void; -} - -export const Panel: React.StatelessComponent = ({ children, onClose }) => ( - - - - - - {children} - - -); - -Panel.displayName = 'Panel'; - -export interface SlidingPanelProps extends PanelProps { - animationState: SlideAnimationState; - onAnimationEnd?: () => void; -} - -export class SlidingPanel extends React.PureComponent { - public render(): React.ReactNode { - if (this.props.animationState === 'none') { - return null; - } - const { animationState, onAnimationEnd, ...rest } = this.props; - const slideAmount = '100%'; - const slideUpSettings: PositionAnimationSettings = { - duration: '0.3s', - timingFunction: 'ease-in-out', - top: { - from: slideAmount, - to: '0px', - }, - position: 'absolute', - }; - const slideDownSettings: PositionAnimationSettings = { - duration: '0.3s', - timingFunction: 'ease-out', - top: { - from: '0px', - to: slideAmount, - }, - position: 'absolute', - }; - return ( - - - - ); - } -} diff --git a/packages/instant/src/components/standard_panel_content.tsx b/packages/instant/src/components/standard_panel_content.tsx deleted file mode 100644 index f2987df82f..0000000000 --- a/packages/instant/src/components/standard_panel_content.tsx +++ /dev/null @@ -1,75 +0,0 @@ -import * as React from 'react'; - -import { ColorOption } from '../style/theme'; -import { util } from '../util/util'; - -import { Container } from './ui/container'; -import { Flex } from './ui/flex'; -import { Text } from './ui/text'; - -export interface MoreInfoSettings { - text: string; - href: string; - onClick?: () => void; -} - -export interface StandardPanelContentProps { - image: React.ReactNode; - title?: string; - description: string; - moreInfoSettings?: MoreInfoSettings; - action: React.ReactNode; -} - -const SPACING_BETWEEN_PX = '20px'; - -const onMoreInfoClick = (href: string, onClick?: () => void) => { - return () => { - if (onClick) { - onClick(); - } - util.createOpenUrlInNewWindow(href)(); - }; -}; - -export const StandardPanelContent: React.StatelessComponent = ({ - image, - title, - description, - moreInfoSettings, - action, -}) => ( - - - {image} - {title && ( - - - {title} - - - )} - - - {description} - - - - {moreInfoSettings && ( - - {moreInfoSettings.text} - - )} - - - {action} - -); - -StandardPanelContent.displayName = 'StandardPanelContent'; diff --git a/packages/instant/src/components/standard_sliding_panel.tsx b/packages/instant/src/components/standard_sliding_panel.tsx deleted file mode 100644 index bcc9d3dcec..0000000000 --- a/packages/instant/src/components/standard_sliding_panel.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import * as React from 'react'; - -import { StandardSlidingPanelContent, StandardSlidingPanelSettings } from '../types'; - -import { InstallWalletPanelContent } from './install_wallet_panel_content'; -import { SlidingPanel } from './sliding_panel'; - -export interface StandardSlidingPanelProps extends StandardSlidingPanelSettings { - onClose: () => void; -} - -export class StandardSlidingPanel extends React.PureComponent { - public render(): React.ReactNode { - const { animationState, content, onClose } = this.props; - return ( - - {this._getNodeForContent(content)} - - ); - } - private readonly _getNodeForContent = (content: StandardSlidingPanelContent): React.ReactNode => { - switch (content) { - case StandardSlidingPanelContent.InstallWallet: - return ; - case StandardSlidingPanelContent.None: - return null; - } - }; -} diff --git a/packages/instant/src/components/time_counter.tsx b/packages/instant/src/components/time_counter.tsx deleted file mode 100644 index 93dc497d5e..0000000000 --- a/packages/instant/src/components/time_counter.tsx +++ /dev/null @@ -1,78 +0,0 @@ -import * as React from 'react'; - -import { ONE_SECOND_MS } from '../constants'; -import { ColorOption } from '../style/theme'; -import { timeUtil } from '../util/time'; - -import { Container } from './ui/container'; -import { Flex } from './ui/flex'; -import { Text } from './ui/text'; - -export interface TimeCounterProps { - estimatedTimeMs: number; - hasEnded: boolean; -} -interface TimeCounterState { - elapsedSeconds: number; -} - -export class TimeCounter extends React.PureComponent { - public state = { - elapsedSeconds: 0, - }; - private _timerId?: number; - - public componentDidMount(): void { - this._setupTimerBasedOnProps(); - } - - public componentWillUnmount(): void { - this._clearTimer(); - } - - public componentDidUpdate(prevProps: TimeCounterProps): void { - if (prevProps.hasEnded !== this.props.hasEnded) { - this._setupTimerBasedOnProps(); - } - } - - public render(): React.ReactNode { - const estimatedTimeSeconds = this.props.estimatedTimeMs / ONE_SECOND_MS; - return ( - - - - - Est. Time - - - - ({timeUtil.secondsToHumanDescription(estimatedTimeSeconds)}) - - - - Time: {timeUtil.secondsToStopwatchTime(this.state.elapsedSeconds)} - - - ); - } - - private _setupTimerBasedOnProps(): void { - this.props.hasEnded ? this._clearTimer() : this._newTimer(); - } - - private _newTimer(): void { - this._clearTimer(); - this._timerId = window.setInterval(() => { - this.setState({ - elapsedSeconds: this.state.elapsedSeconds + 1, - }); - }, ONE_SECOND_MS); - } - - private _clearTimer(): void { - if (this._timerId) { - window.clearInterval(this._timerId); - } - } -} diff --git a/packages/instant/src/components/timed_progress_bar.tsx b/packages/instant/src/components/timed_progress_bar.tsx deleted file mode 100644 index 287269af76..0000000000 --- a/packages/instant/src/components/timed_progress_bar.tsx +++ /dev/null @@ -1,106 +0,0 @@ -import * as _ from 'lodash'; -import { transparentize } from 'polished'; -import * as React from 'react'; - -import { PROGRESS_FINISH_ANIMATION_TIME_MS, PROGRESS_STALL_AT_WIDTH } from '../constants'; -import { ColorOption, css, keyframes, styled, ThemeConsumer } from '../style/theme'; - -import { Container } from './ui/container'; - -export interface TimedProgressBarProps { - expectedTimeMs: number; - hasEnded: boolean; -} - -/** - * Timed Progress Bar - * Goes from 0% -> PROGRESS_STALL_AT_WIDTH over time of expectedTimeMs - * When hasEnded set to true, goes to 100% through animation of PROGRESS_FINISH_ANIMATION_TIME_MS length of time - */ -export class TimedProgressBar extends React.PureComponent { - private readonly _barRef = React.createRef(); - - public render(): React.ReactNode { - const widthAnimationSettings = this._calculateWidthAnimationSettings(); - return ; - } - - private _calculateWidthAnimationSettings(): WidthAnimationSettings { - if (this.props.hasEnded) { - if (!this._barRef.current) { - throw new Error('ended but no reference'); - } - const fromWidth = `${this._barRef.current.offsetWidth}px`; - return { - timeMs: PROGRESS_FINISH_ANIMATION_TIME_MS, - fromWidth, - toWidth: '100%', - }; - } - - return { - timeMs: this.props.expectedTimeMs, - fromWidth: '0px', - toWidth: PROGRESS_STALL_AT_WIDTH, - }; - } -} - -const expandingWidthKeyframes = (fromWidth: string, toWidth: string) => { - return keyframes` - from { - width: ${fromWidth}; - } - to { - width: ${toWidth}; - } - `; -}; - -export interface WidthAnimationSettings { - timeMs: number; - fromWidth: string; - toWidth: string; -} - -interface ProgressProps { - width?: string; - animationSettings?: WidthAnimationSettings; -} - -export const Progress = styled.div` - && { - background-color: ${props => props.theme[ColorOption.primaryColor]}; - border-radius: 6px; - height: 6px; - ${props => (props.width ? `width: ${props.width};` : '')} - ${props => - props.animationSettings - ? css` - animation: ${expandingWidthKeyframes( - props.animationSettings.fromWidth, - props.animationSettings.toWidth, - )} - ${props.animationSettings.timeMs}ms linear 1 forwards; - ` - : ''} - } -`; - -export interface ProgressBarProps extends ProgressProps {} - -export const ProgressBar: React.ComponentType> = React.forwardRef( - (props, ref) => ( - - {theme => ( - - - - )} - - ), -); diff --git a/packages/instant/src/components/ui/button.tsx b/packages/instant/src/components/ui/button.tsx deleted file mode 100644 index e77b1b5d19..0000000000 --- a/packages/instant/src/components/ui/button.tsx +++ /dev/null @@ -1,87 +0,0 @@ -import { darken, saturate } from 'polished'; -import * as React from 'react'; - -import { ColorOption, styled } from '../../style/theme'; -import { util } from '../../util/util'; - -export type ButtonOnClickHandler = (event: React.MouseEvent) => void; - -export interface ButtonProps { - backgroundColor?: ColorOption; - borderColor?: ColorOption; - fontColor?: ColorOption; - fontSize?: string; - width?: string; - padding?: string; - type?: string; - isDisabled?: boolean; - href?: string; - onClick?: ButtonOnClickHandler; - className?: string; -} - -const PlainButton: React.StatelessComponent = ({ - children, - isDisabled, - onClick, - href, - type, - className, -}) => { - const computedOnClick = isDisabled ? undefined : href ? util.createOpenUrlInNewWindow(href) : onClick; - return ( - - ); -}; - -const darkenOnHoverAmount = 0.1; -const darkenOnActiveAmount = 0.2; -const saturateOnFocusAmount = 0.2; -export const Button = styled(PlainButton)` - && { - all: initial; - box-sizing: border-box; - font-size: ${props => props.fontSize}; - font-family: 'Inter UI', sans-serif; - font-weight: 500; - color: ${props => props.fontColor && props.theme[props.fontColor]}; - cursor: ${props => (props.isDisabled ? 'default' : 'pointer')}; - transition: background-color, opacity 0.5s ease; - padding: ${props => props.padding}; - border-radius: 3px; - text-align: center; - outline: none; - width: ${props => props.width}; - background-color: ${props => (props.backgroundColor ? props.theme[props.backgroundColor] : 'none')}; - border: ${props => (props.borderColor ? `1px solid ${props.theme[props.borderColor]}` : 'none')}; - &:hover { - background-color: ${props => - !props.isDisabled - ? darken(darkenOnHoverAmount, props.theme[props.backgroundColor || 'white']) - : ''} !important; - } - &:active { - background-color: ${props => - !props.isDisabled ? darken(darkenOnActiveAmount, props.theme[props.backgroundColor || 'white']) : ''}; - } - &:disabled { - opacity: 0.5; - } - &:focus { - background-color: ${props => - saturate(saturateOnFocusAmount, props.theme[props.backgroundColor || 'white'])}; - } - } -`; - -Button.defaultProps = { - backgroundColor: ColorOption.primaryColor, - width: 'auto', - isDisabled: false, - padding: '.82em 1.2em', - fontSize: '16px', -}; - -Button.displayName = 'Button'; diff --git a/packages/instant/src/components/ui/circle.tsx b/packages/instant/src/components/ui/circle.tsx deleted file mode 100644 index e4f2c52609..0000000000 --- a/packages/instant/src/components/ui/circle.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { ColorOption, styled, Theme, withTheme } from '../../style/theme'; - -export interface CircleProps { - diameter: number; - rawColor?: string; - color?: ColorOption; - theme: Theme; -} - -export const Circle = withTheme( - styled.div` - && { - width: ${props => props.diameter}px; - height: ${props => props.diameter}px; - background-color: ${props => - props.rawColor ? props.rawColor : props.theme[props.color || ColorOption.white]}; - border-radius: 50%; - } - `, -); - -Circle.displayName = 'Circle'; - -Circle.defaultProps = { - color: ColorOption.white, -}; diff --git a/packages/instant/src/components/ui/container.tsx b/packages/instant/src/components/ui/container.tsx deleted file mode 100644 index b9040cfccb..0000000000 --- a/packages/instant/src/components/ui/container.tsx +++ /dev/null @@ -1,105 +0,0 @@ -import { darken } from 'polished'; - -import { MediaChoice, stylesForMedia } from '../../style/media'; -import { ColorOption, styled } from '../../style/theme'; -import { cssRuleIfExists } from '../../style/util'; - -export interface ContainerProps { - display?: MediaChoice; - position?: string; - top?: string; - right?: string; - bottom?: string; - left?: string; - width?: MediaChoice; - height?: MediaChoice; - maxWidth?: string; - margin?: string; - marginTop?: string; - marginRight?: string; - marginBottom?: string; - marginLeft?: string; - padding?: string; - borderRadius?: MediaChoice; - border?: string; - borderColor?: ColorOption; - borderTop?: string; - borderBottom?: string; - className?: string; - backgroundColor?: ColorOption; - rawBackgroundColor?: string; - hasBoxShadow?: boolean; - isHidden?: boolean; - zIndex?: number; - whiteSpace?: string; - opacity?: number; - cursor?: string; - overflow?: string; - darkenOnHover?: boolean; - rawHoverColor?: string; - boxShadowOnHover?: boolean; - flexGrow?: string | number; -} - -const getBackgroundColor = (theme: any, backgroundColor?: ColorOption, rawBackgroundColor?: string): string => { - if (backgroundColor) { - return theme[backgroundColor] as string; - } - if (rawBackgroundColor) { - return rawBackgroundColor; - } - return 'none'; -}; - -export const Container = styled.div` - && { - box-sizing: border-box; - ${props => cssRuleIfExists(props, 'flex-grow')} - ${props => cssRuleIfExists(props, 'position')} - ${props => cssRuleIfExists(props, 'top')} - ${props => cssRuleIfExists(props, 'right')} - ${props => cssRuleIfExists(props, 'bottom')} - ${props => cssRuleIfExists(props, 'left')} - ${props => cssRuleIfExists(props, 'max-width')} - ${props => cssRuleIfExists(props, 'margin')} - ${props => cssRuleIfExists(props, 'margin-top')} - ${props => cssRuleIfExists(props, 'margin-right')} - ${props => cssRuleIfExists(props, 'margin-bottom')} - ${props => cssRuleIfExists(props, 'margin-left')} - ${props => cssRuleIfExists(props, 'padding')} - ${props => cssRuleIfExists(props, 'border')} - ${props => cssRuleIfExists(props, 'border-top')} - ${props => cssRuleIfExists(props, 'border-bottom')} - ${props => cssRuleIfExists(props, 'z-index')} - ${props => cssRuleIfExists(props, 'white-space')} - ${props => cssRuleIfExists(props, 'opacity')} - ${props => cssRuleIfExists(props, 'cursor')} - ${props => cssRuleIfExists(props, 'overflow')} - ${props => cssRuleIfExists(props, 'alignSelf')} - ${props => (props.overflow === 'scroll' ? `-webkit-overflow-scrolling: touch` : '')}; - ${props => (props.hasBoxShadow ? `box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.1)` : '')}; - ${props => props.display && stylesForMedia('display', props.display)} - ${props => props.width && stylesForMedia('width', props.width)} - ${props => props.height && stylesForMedia('height', props.height)} - ${props => props.borderRadius && stylesForMedia('border-radius', props.borderRadius)} - ${props => (props.isHidden ? 'visibility: hidden;' : '')} - background-color: ${props => getBackgroundColor(props.theme, props.backgroundColor, props.rawBackgroundColor)}; - border-color: ${props => (props.borderColor ? props.theme[props.borderColor] : 'none')}; - &:hover { - ${props => (props.rawHoverColor ? `background-color: ${props.rawHoverColor}` : '')} - ${props => - props.darkenOnHover - ? `background-color: ${ - props.backgroundColor ? darken(0.05, props.theme[props.backgroundColor]) : 'none' - }` - : ''}; - ${props => (props.boxShadowOnHover ? 'box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.1)' : '')}; - } - } -`; - -Container.defaultProps = { - display: 'block', -}; - -Container.displayName = 'Container'; diff --git a/packages/instant/src/components/ui/dropdown.tsx b/packages/instant/src/components/ui/dropdown.tsx deleted file mode 100644 index 8788d3d594..0000000000 --- a/packages/instant/src/components/ui/dropdown.tsx +++ /dev/null @@ -1,147 +0,0 @@ -import * as _ from 'lodash'; -import { transparentize } from 'polished'; -import * as React from 'react'; - -import { ColorOption, completelyTransparent, ThemeConsumer } from '../../style/theme'; -import { zIndex } from '../../style/z_index'; - -import { Container } from './container'; -import { Flex } from './flex'; -import { Icon } from './icon'; -import { Overlay } from './overlay'; -import { Text } from './text'; - -export interface DropdownItemConfig { - text: string; - onClick?: () => void; -} - -export interface DropdownProps { - value: string; - label?: string; - items: DropdownItemConfig[]; - onOpen?: () => void; -} - -export interface DropdownState { - isOpen: boolean; -} - -export class Dropdown extends React.PureComponent { - public static defaultProps = { - items: [], - }; - public state: DropdownState = { - isOpen: false, - }; - public render(): React.ReactNode { - const { value, label, items } = this.props; - const { isOpen } = this.state; - const hasItems = !_.isEmpty(items); - const borderRadius = isOpen ? '4px 4px 0px 0px' : '4px'; - return ( - - {isOpen && ( - - )} - - - - - {value} - - - {label && ( - - {label} - - )} - {hasItems && ( - - - - )} - - - - {isOpen && ( - - {_.map(items, (item, index) => ( - - ))} - - )} - - - ); - } - private readonly _handleDropdownClick = (): void => { - if (_.isEmpty(this.props.items)) { - return; - } - const isOpen = !this.state.isOpen; - this.setState({ - isOpen, - }); - - if (isOpen && this.props.onOpen) { - this.props.onOpen(); - } - }; - private readonly _closeDropdown = (): void => { - this.setState({ - isOpen: false, - }); - }; -} - -export interface DropdownItemProps extends DropdownItemConfig { - text: string; - onClick?: () => void; - isLast: boolean; -} - -export const DropdownItem: React.StatelessComponent = ({ text, onClick, isLast }) => ( - - {theme => ( - - - {text} - - - )} - -); - -DropdownItem.displayName = 'DropdownItem'; diff --git a/packages/instant/src/components/ui/flex.tsx b/packages/instant/src/components/ui/flex.tsx deleted file mode 100644 index 223b9e61fe..0000000000 --- a/packages/instant/src/components/ui/flex.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import { MediaChoice, stylesForMedia } from '../../style/media'; -import { ColorOption, styled } from '../../style/theme'; -import { cssRuleIfExists } from '../../style/util'; - -export interface FlexProps { - direction?: 'row' | 'column'; - flexWrap?: 'wrap' | 'nowrap'; - justify?: 'flex-start' | 'center' | 'space-around' | 'space-between' | 'space-evenly' | 'flex-end'; - align?: 'flex-start' | 'center' | 'space-around' | 'space-between' | 'space-evenly' | 'flex-end'; - width?: MediaChoice; - height?: MediaChoice; - overflow?: string; - backgroundColor?: ColorOption; - inline?: boolean; - flexGrow?: number | string; -} - -export const Flex = styled.div` - && { - display: ${props => (props.inline ? 'inline-flex' : 'flex')}; - flex-direction: ${props => props.direction}; - flex-wrap: ${props => props.flexWrap}; - ${props => cssRuleIfExists(props, 'flexGrow')} - justify-content: ${props => props.justify}; - align-items: ${props => props.align}; - background-color: ${props => (props.backgroundColor ? props.theme[props.backgroundColor] : 'none')}; - ${props => (props.width ? stylesForMedia('width', props.width) : '')} - ${props => (props.height ? stylesForMedia('height', props.height) : '')} - ${props => (props.overflow ? `overflow: ${props.overflow}` : '')}; - } -`; - -Flex.defaultProps = { - direction: 'row', - flexWrap: 'nowrap', - justify: 'center', - align: 'center', -}; - -Flex.displayName = 'Flex'; diff --git a/packages/instant/src/components/ui/icon.tsx b/packages/instant/src/components/ui/icon.tsx deleted file mode 100644 index c669db60f1..0000000000 --- a/packages/instant/src/components/ui/icon.tsx +++ /dev/null @@ -1,139 +0,0 @@ -import * as _ from 'lodash'; -import * as React from 'react'; - -import { ColorOption, styled, Theme, withTheme } from '../../style/theme'; - -type svgRule = 'evenodd' | 'nonzero' | 'inherit'; -interface IconInfo { - viewBox: string; - path: string; - fillRule?: svgRule; - clipRule?: svgRule; - strokeOpacity?: number; - strokeWidth?: number; - strokeLinecap?: 'butt' | 'round' | 'square' | 'inherit'; - strokeLinejoin?: 'miter' | 'round' | 'bevel' | 'inherit'; -} -interface IconInfoMapping { - closeX: IconInfo; - failed: IconInfo; - success: IconInfo; - chevron: IconInfo; - chevronRight: IconInfo; - search: IconInfo; - lock: IconInfo; -} -const ICONS: IconInfoMapping = { - closeX: { - viewBox: '0 0 11 11', - fillRule: 'evenodd', - clipRule: 'evenodd', - path: - 'M10.45 10.449C10.7539 10.1453 10.7539 9.65282 10.45 9.34909L6.60068 5.49999L10.45 1.65093C10.7538 1.3472 10.7538 0.854765 10.45 0.551038C10.1462 0.24731 9.65378 0.24731 9.34995 0.551038L5.50058 4.40006L1.65024 0.549939C1.34641 0.246212 0.853973 0.246212 0.550262 0.549939C0.246429 0.853667 0.246429 1.34611 0.550262 1.64983L4.40073 5.49995L0.55014 9.35019C0.246307 9.65392 0.246307 10.1464 0.55014 10.4501C0.853851 10.7538 1.34628 10.7538 1.65012 10.4501L5.5007 6.59987L9.35007 10.449C9.6539 10.7527 10.1463 10.7527 10.45 10.449Z', - }, - failed: { - viewBox: '0 0 34 34', - fillRule: 'evenodd', - clipRule: 'evenodd', - path: - 'M6.65771 26.4362C9.21777 29.2406 12.9033 31 17 31C24.7319 31 31 24.7319 31 17C31 14.4468 30.3164 12.0531 29.1226 9.99219L6.65771 26.4362ZM4.88281 24.0173C3.68555 21.9542 3 19.5571 3 17C3 9.26807 9.26807 3 17 3C21.1006 3 24.7891 4.76294 27.3496 7.57214L4.88281 24.0173ZM0 17C0 26.3888 7.61133 34 17 34C26.3887 34 34 26.3888 34 17C34 7.61121 26.3887 0 17 0C7.61133 0 0 7.61121 0 17Z', - }, - success: { - viewBox: '0 0 34 34', - fillRule: 'evenodd', - clipRule: 'evenodd', - path: - 'M17 34C26.3887 34 34 26.3888 34 17C34 7.61121 26.3887 0 17 0C7.61133 0 0 7.61121 0 17C0 26.3888 7.61133 34 17 34ZM25.7539 13.0977C26.2969 12.4718 26.2295 11.5244 25.6035 10.9817C24.9775 10.439 24.0303 10.5063 23.4878 11.1323L15.731 20.0771L12.3936 16.7438C11.8071 16.1583 10.8574 16.1589 10.272 16.7451C9.68652 17.3313 9.6875 18.281 10.2734 18.8665L14.75 23.3373L15.8887 24.4746L16.9434 23.2587L25.7539 13.0977Z', - }, - chevron: { - viewBox: '0 0 12 7', - path: 'M11 1L6 6L1 1', - strokeOpacity: 0.5, - strokeWidth: 1.5, - strokeLinecap: 'round', - strokeLinejoin: 'round', - }, - chevronRight: { - viewBox: '0 0 7 13', - path: 'M1 1.5L6 6.5L1 11.5', - strokeOpacity: 0.5, - strokeWidth: 1.5, - strokeLinecap: 'round', - strokeLinejoin: 'round', - }, - search: { - viewBox: '0 0 14 14', - fillRule: 'evenodd', - clipRule: 'evenodd', - path: - 'M8.39404 5.19727C8.39404 6.96289 6.96265 8.39453 5.19702 8.39453C3.4314 8.39453 2 6.96289 2 5.19727C2 3.43164 3.4314 2 5.19702 2C6.96265 2 8.39404 3.43164 8.39404 5.19727ZM8.09668 9.51074C7.26855 10.0684 6.27075 10.3945 5.19702 10.3945C2.3269 10.3945 0 8.06738 0 5.19727C0 2.32715 2.3269 0 5.19702 0C8.06738 0 10.394 2.32715 10.394 5.19727C10.394 6.27051 10.0686 7.26855 9.51074 8.09668L13.6997 12.2861L12.2854 13.7002L8.09668 9.51074Z', - }, - lock: { - viewBox: '0 0 13 16', - path: - 'M6.47619 0C3.79509 0 1.60489 2.21216 1.60489 4.92014V6.33135C0.717479 6.33135 0 7.05602 0 7.95232V14.379C0 15.2753 0.717479 16 1.60489 16H11.3475C12.2349 16 12.9524 15.2753 12.9524 14.379V7.95232C12.9524 7.05602 12.2349 6.33135 11.3475 6.33135V4.92014C11.3475 2.21216 9.1573 0 6.47619 0ZM9.6482 6.33135H3.30418V4.92014C3.30418 3.16567 4.72026 1.71633 6.47619 1.71633C8.23213 1.71633 9.6482 3.16567 9.6482 4.92014V6.33135Z', - }, -}; - -export interface IconProps { - className?: string; - width: number; - height?: number; - color?: ColorOption; - stroke?: ColorOption; - icon: keyof IconInfoMapping; - onClick?: (event: React.MouseEvent) => void; - padding?: string; - theme: Theme; -} -const PlainIcon: React.StatelessComponent = props => { - const iconInfo = ICONS[props.icon]; - const colorValue = props.color === undefined ? undefined : props.theme[props.color]; - const strokeValue = props.stroke === undefined ? undefined : props.theme[props.stroke]; - return ( -
- - - -
- ); -}; - -export const Icon = withTheme(styled(PlainIcon)` - && { - display: inline-block; - ${props => (props.onClick !== undefined ? 'cursor: pointer' : '')}; - transition: opacity 0.5s ease; - padding: ${props => props.padding}; - opacity: ${props => (props.onClick !== undefined ? 0.7 : 1)}; - &:hover { - opacity: 1; - } - &:active { - opacity: 1; - } - } -`); - -Icon.defaultProps = { - padding: '0em 0em', -}; - -Icon.displayName = 'Icon'; diff --git a/packages/instant/src/components/ui/image.tsx b/packages/instant/src/components/ui/image.tsx deleted file mode 100644 index d98ea44e62..0000000000 --- a/packages/instant/src/components/ui/image.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import * as React from 'react'; - -import { styled } from '../../style/theme'; - -export interface ImageProps extends React.HTMLAttributes { - height?: string; - width?: string; - objectFit?: string; -} - -export const Image = styled.img` - && { - ${props => (props.height ? `height: ${props.height}` : '')}; - ${props => (props.width ? `width: ${props.width}` : '')}; - ${props => (props.objectFit ? `object-fit: ${props.objectFit}` : '')}; - } -`; - -Image.defaultProps = {}; - -Image.displayName = 'Image'; diff --git a/packages/instant/src/components/ui/input.tsx b/packages/instant/src/components/ui/input.tsx deleted file mode 100644 index 3696fc65a7..0000000000 --- a/packages/instant/src/components/ui/input.tsx +++ /dev/null @@ -1,49 +0,0 @@ -import * as React from 'react'; - -import { ColorOption, styled } from '../../style/theme'; - -export interface InputProps extends React.HTMLAttributes { - tabIndex?: number; - className?: string; - value?: string; - width?: string; - fontSize?: string; - fontColor?: ColorOption; - placeholder?: string; - type?: string; - onChange?: (event: React.ChangeEvent) => void; -} - -export const Input = styled.input` - && { - all: initial; - font-size: ${props => props.fontSize}; - width: ${props => props.width}; - padding: 0.1em 0em; - font-family: 'Inter UI'; - color: ${props => props.theme[props.fontColor || 'white']}; - background: transparent; - outline: none; - border: none; - &[type='number'] { - -moz-appearance: textfield; - } - &::placeholder { - color: ${props => props.theme[props.fontColor || 'white']} !important; - opacity: 0.5 !important; - } - &::-webkit-outer-spin-button, - &::-webkit-inner-spin-button { - -webkit-appearance: none; - margin: 0; - } - } -`; - -Input.defaultProps = { - width: 'auto', - fontColor: ColorOption.white, - fontSize: '12px', -}; - -Input.displayName = 'Input'; diff --git a/packages/instant/src/components/ui/overlay.tsx b/packages/instant/src/components/ui/overlay.tsx deleted file mode 100644 index 0b1be6a650..0000000000 --- a/packages/instant/src/components/ui/overlay.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import * as _ from 'lodash'; - -import { generateMediaWrapper, ScreenWidths } from '../../style/media'; -import { generateOverlayBlack, styled } from '../../style/theme'; -import { zIndex } from '../../style/z_index'; - -export interface OverlayProps { - zIndex?: number; - backgroundColor?: string; - width?: string; - height?: string; - showMaxWidth?: ScreenWidths; -} - -export const Overlay = styled.div` - && { - position: fixed; - top: 0; - right: 0; - bottom: 0; - left: 0; - z-index: ${props => props.zIndex} - background-color: ${props => props.backgroundColor}; - ${props => props.width && `width: ${props.width};`} - ${props => props.height && `height: ${props.height};`} - display: ${props => (props.showMaxWidth ? 'none' : 'block')}; - ${props => props.showMaxWidth && generateMediaWrapper(props.showMaxWidth)`display: block;`} - } -`; - -Overlay.defaultProps = { - zIndex: zIndex.overlayDefault, - backgroundColor: generateOverlayBlack(0.7), -}; - -Overlay.displayName = 'Overlay'; diff --git a/packages/instant/src/components/ui/spinner.tsx b/packages/instant/src/components/ui/spinner.tsx deleted file mode 100644 index 28ebc2598b..0000000000 --- a/packages/instant/src/components/ui/spinner.tsx +++ /dev/null @@ -1,30 +0,0 @@ -import * as React from 'react'; - -import { FullRotation } from '../animations/full_rotation'; - -export interface SpinnerProps { - widthPx: number; - heightPx: number; -} -export const Spinner: React.StatelessComponent = props => { - return ( - - - - - - - ); -}; diff --git a/packages/instant/src/components/ui/text.tsx b/packages/instant/src/components/ui/text.tsx deleted file mode 100644 index ca120f3bd7..0000000000 --- a/packages/instant/src/components/ui/text.tsx +++ /dev/null @@ -1,71 +0,0 @@ -import * as React from 'react'; - -import { ColorOption, styled } from '../../style/theme'; -import { util } from '../../util/util'; - -export interface TextProps { - fontColor?: ColorOption; - fontFamily?: string; - fontStyle?: string; - fontSize?: string; - opacity?: number; - letterSpacing?: string; - textAlign?: string; - textTransform?: string; - lineHeight?: string; - className?: string; - minHeight?: string; - center?: boolean; - fontWeight?: number | string; - textDecorationLine?: string; - onClick?: (event: React.MouseEvent) => void; - noWrap?: boolean; - display?: string; - href?: string; - width?: string; -} - -export const Text: React.StatelessComponent = ({ href, onClick, ...rest }) => { - const computedOnClick = href ? util.createOpenUrlInNewWindow(href) : onClick; - return ; -}; - -const opacityOnHoverAmount = 0.5; -export const StyledText = styled.div` - && { - font-family: 'Inter UI', sans-serif; - font-style: ${props => props.fontStyle}; - font-weight: ${props => props.fontWeight}; - font-size: ${props => props.fontSize}; - opacity: ${props => props.opacity}; - text-decoration-line: ${props => props.textDecorationLine}; - ${props => (props.lineHeight ? `line-height: ${props.lineHeight}` : '')}; - ${props => (props.center ? 'text-align: center' : '')}; - color: ${props => props.fontColor && props.theme[props.fontColor]}; - ${props => (props.minHeight ? `min-height: ${props.minHeight}` : '')}; - ${props => (props.onClick ? 'cursor: pointer' : '')}; - transition: color 0.5s ease; - ${props => (props.noWrap ? 'white-space: nowrap' : '')}; - ${props => (props.display ? `display: ${props.display}` : '')}; - ${props => (props.letterSpacing ? `letter-spacing: ${props.letterSpacing}` : '')}; - ${props => (props.textTransform ? `text-transform: ${props.textTransform}` : '')}; - ${props => (props.textAlign ? `text-align: ${props.textAlign}` : '')}; - ${props => (props.width ? `width: ${props.width}` : '')}; - &:hover { - ${props => (props.onClick ? `opacity: ${opacityOnHoverAmount};` : '')}; - } - } -`; - -Text.defaultProps = { - fontFamily: 'Inter UI', - fontStyle: 'normal', - fontWeight: 400, - fontColor: ColorOption.black, - fontSize: '15px', - textDecorationLine: 'none', - noWrap: false, - display: 'inline-block', -}; - -Text.displayName = 'Text'; diff --git a/packages/instant/src/components/wallet_prompt.tsx b/packages/instant/src/components/wallet_prompt.tsx deleted file mode 100644 index 0df5f72e66..0000000000 --- a/packages/instant/src/components/wallet_prompt.tsx +++ /dev/null @@ -1,68 +0,0 @@ -import * as React from 'react'; - -import ChevronRightSvg from '../assets/icons/chevronRight.svg'; -import { ColorOption } from '../style/theme'; - -import { Container } from './ui/container'; -import { Flex } from './ui/flex'; -import { Text } from './ui/text'; - -export interface WalletPromptProps { - image?: React.ReactNode; - onClick?: () => void; - primaryColor: ColorOption; - secondaryColor: ColorOption; - marginTop?: string; - display?: string; - alignText?: string; - marginLeft?: string; - fontWeight?: string; - padding?: string; -} - -export const WalletPrompt: React.StatelessComponent = ({ - onClick, - image, - children, - secondaryColor, - primaryColor, - marginTop, - display, - alignText, - marginLeft = '10px', - fontWeight = '500', - padding = '10px', -}) => ( - - - {image} - - - {children} - - - - - - - -); - -WalletPrompt.defaultProps = { - primaryColor: ColorOption.darkOrange, - secondaryColor: ColorOption.lightOrange, -}; - -WalletPrompt.displayName = 'WalletPrompt'; diff --git a/packages/instant/src/components/zero_ex_instant.tsx b/packages/instant/src/components/zero_ex_instant.tsx deleted file mode 100644 index e9cb48e61a..0000000000 --- a/packages/instant/src/components/zero_ex_instant.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import * as React from 'react'; - -import { ZeroExInstantContainer } from '../components/zero_ex_instant_container'; - -import { INJECTED_DIV_CLASS } from '../constants'; - -import { ZeroExInstantProvider, ZeroExInstantProviderProps } from './zero_ex_instant_provider'; - -export type ZeroExInstantProps = ZeroExInstantProviderProps; - -export const ZeroExInstant: React.StatelessComponent = props => { - return ( -
- - - -
- ); -}; - -ZeroExInstant.displayName = 'ZeroExInstant'; diff --git a/packages/instant/src/components/zero_ex_instant_container.tsx b/packages/instant/src/components/zero_ex_instant_container.tsx deleted file mode 100644 index 752c78f4a8..0000000000 --- a/packages/instant/src/components/zero_ex_instant_container.tsx +++ /dev/null @@ -1,116 +0,0 @@ -import { AssetProxyId } from '@0x/types'; -import * as React from 'react'; - -import PoweredByLogo from '../assets/powered_by_0x.svg'; -import { ZERO_EX_SITE_URL } from '../constants'; -import { AvailableERC20TokenSelector } from '../containers/available_erc20_token_selector'; -import { ConnectedBuyOrderProgressOrPaymentMethod } from '../containers/connected_buy_order_progress_or_payment_method'; -import { CurrentStandardSlidingPanel } from '../containers/current_standard_sliding_panel'; -import { LatestBuyQuoteOrderDetails } from '../containers/latest_buy_quote_order_details'; -import { LatestError } from '../containers/latest_error'; -import { SelectedAssetBuyOrderStateButtons } from '../containers/selected_asset_buy_order_state_buttons'; -import { SelectedAssetInstantHeading } from '../containers/selected_asset_instant_heading'; -import { ColorOption } from '../style/theme'; -import { zIndex } from '../style/z_index'; -import { Asset, SlideAnimationState } from '../types'; -import { analytics, TokenSelectorClosedVia } from '../util/analytics'; - -import { CSSReset } from './css_reset'; -import { SlidingPanel } from './sliding_panel'; -import { Container } from './ui/container'; -import { Flex } from './ui/flex'; - -export interface ZeroExInstantContainerProps {} -export interface ZeroExInstantContainerState { - tokenSelectionPanelAnimationState: SlideAnimationState; -} - -export class ZeroExInstantContainer extends React.PureComponent< - ZeroExInstantContainerProps, - ZeroExInstantContainerState -> { - public state = { - tokenSelectionPanelAnimationState: 'none' as SlideAnimationState, - }; - public render(): React.ReactNode { - return ( - - - - - - - - - - - - - - - - - - - - - -
- - - - - - ); - } - private readonly _handleSymbolClick = (asset?: Asset): void => { - // TODO: If ERC721 link open sea or allow to choose another ERC721? - if (asset === undefined || asset.metaData.assetProxyId === AssetProxyId.ERC20) { - analytics.trackTokenSelectorOpened(); - this.setState({ - tokenSelectionPanelAnimationState: 'slidIn', - }); - } - }; - private readonly _handlePanelCloseClickedX = (): void => { - this._handlePanelClose(TokenSelectorClosedVia.ClickedX); - }; - private readonly _handlePanelCloseAfterChose = (): void => { - this._handlePanelClose(TokenSelectorClosedVia.TokenChose); - }; - private readonly _handlePanelClose = (closedVia: TokenSelectorClosedVia): void => { - analytics.trackTokenSelectorClosed(closedVia); - this.setState({ - tokenSelectionPanelAnimationState: 'slidOut', - }); - }; - private readonly _handleSlidingPanelAnimationEnd = (): void => { - if (this.state.tokenSelectionPanelAnimationState === 'slidOut') { - // When the slidOut animation completes, don't keep the panel mounted. - // Performance optimization - this.setState({ tokenSelectionPanelAnimationState: 'none' }); - } - }; -} diff --git a/packages/instant/src/components/zero_ex_instant_overlay.tsx b/packages/instant/src/components/zero_ex_instant_overlay.tsx deleted file mode 100644 index 2a3ee757c5..0000000000 --- a/packages/instant/src/components/zero_ex_instant_overlay.tsx +++ /dev/null @@ -1,53 +0,0 @@ -import * as React from 'react'; - -import { ZeroExInstantContainer } from '../components/zero_ex_instant_container'; -import { MAIN_CONTAINER_DIV_CLASS, OVERLAY_CLOSE_BUTTON_DIV_CLASS, OVERLAY_DIV_CLASS } from '../constants'; -import { ColorOption } from '../style/theme'; - -import { Container } from './ui/container'; -import { Flex } from './ui/flex'; -import { Icon } from './ui/icon'; -import { Overlay } from './ui/overlay'; -import { ZeroExInstantProvider, ZeroExInstantProviderProps } from './zero_ex_instant_provider'; - -export interface ZeroExInstantOverlayProps extends ZeroExInstantProviderProps { - onClose?: () => void; - zIndex?: number; -} - -export const ZeroExInstantOverlay: React.StatelessComponent = props => { - const { onClose, zIndex, ...rest } = props; - return ( - - - - - - - - - - - - - ); -}; - -ZeroExInstantOverlay.displayName = 'ZeroExInstantOverlay'; diff --git a/packages/instant/src/components/zero_ex_instant_provider.tsx b/packages/instant/src/components/zero_ex_instant_provider.tsx deleted file mode 100644 index 1c0c209cc2..0000000000 --- a/packages/instant/src/components/zero_ex_instant_provider.tsx +++ /dev/null @@ -1,178 +0,0 @@ -import { AssetProxyId } from '@0x/types'; -import { BigNumber } from '@0x/utils'; -import * as _ from 'lodash'; -import * as React from 'react'; -import { Provider as ReduxProvider } from 'react-redux'; - -import { ACCOUNT_UPDATE_INTERVAL_TIME_MS, SWAP_QUOTE_UPDATE_INTERVAL_TIME_MS } from '../constants'; -import { SelectedAssetThemeProvider } from '../containers/selected_asset_theme_provider'; -import { asyncData } from '../redux/async_data'; -import { DEFAULT_STATE, DefaultState, State } from '../redux/reducer'; -import { store, Store } from '../redux/store'; -import { fonts } from '../style/fonts'; -import { AccountState, Network, QuoteFetchOrigin, ZeroExInstantBaseConfig } from '../types'; -import { analytics, disableAnalytics } from '../util/analytics'; -import { assetUtils } from '../util/asset'; -import { errorFlasher } from '../util/error_flasher'; -import { setupRollbar } from '../util/error_reporter'; -import { gasPriceEstimator } from '../util/gas_price_estimator'; -import { Heartbeater } from '../util/heartbeater'; -import { generateAccountHeartbeater, generateSwapQuoteHeartbeater } from '../util/heartbeater_factory'; -import { providerStateFactory } from '../util/provider_state_factory'; - -export type ZeroExInstantProviderProps = ZeroExInstantBaseConfig; - -export class ZeroExInstantProvider extends React.PureComponent { - private readonly _store: Store; - private _accountUpdateHeartbeat?: Heartbeater; - private _swapQuoteHeartbeat?: Heartbeater; - - // TODO(fragosti): Write tests for this beast once we inject a provider. - private static _mergeDefaultStateWithProps( - props: ZeroExInstantProviderProps, - defaultState: DefaultState = DEFAULT_STATE, - ): State { - // use the networkId passed in with the props, otherwise default to that of the default state (1, mainnet) - const networkId = props.networkId || defaultState.network; - // construct the ProviderState - const providerState = providerStateFactory.getInitialProviderState( - props.orderSource, - networkId, - props.provider, - props.walletDisplayName, - ); - // merge the additional additionalAssetMetaDataMap with our default map - const completeAssetMetaDataMap = { - // Make sure the passed in assetDatas are lower case - ..._.mapKeys(props.additionalAssetMetaDataMap || {}, (value, key) => key.toLowerCase()), - ...defaultState.assetMetaDataMap, - }; - - const selectedAsset = - props.defaultSelectedAssetData === undefined - ? undefined - : assetUtils.createAssetFromAssetDataOrThrow( - props.defaultSelectedAssetData, - completeAssetMetaDataMap, - networkId, - ); - - let selectedAssetUnitAmount: BigNumber | undefined; - if (selectedAsset !== undefined) { - if (selectedAsset.metaData.assetProxyId === AssetProxyId.ERC20) { - selectedAssetUnitAmount = - props.defaultAssetBuyAmount === undefined ? undefined : new BigNumber(props.defaultAssetBuyAmount); - } else if (selectedAsset.metaData.assetProxyId === AssetProxyId.ERC721) { - selectedAssetUnitAmount = new BigNumber(1); - } - } - - // construct the final state - const storeStateFromProps: State = { - ...defaultState, - providerState, - network: networkId, - walletDisplayName: props.walletDisplayName, - selectedAsset, - selectedAssetUnitAmount, - availableAssets: - props.availableAssetDatas === undefined - ? undefined - : assetUtils.createAssetsFromAssetDatas( - props.availableAssetDatas, - completeAssetMetaDataMap, - networkId, - ), - assetMetaDataMap: completeAssetMetaDataMap, - onSuccess: props.onSuccess, - affiliateInfo: props.affiliateInfo, - }; - return storeStateFromProps; - } - constructor(props: ZeroExInstantProviderProps) { - super(props); - setupRollbar(); - fonts.include(); - const initialAppState = ZeroExInstantProvider._mergeDefaultStateWithProps(this.props); - this._store = store.create(initialAppState); - } - public componentDidMount(): void { - const state = this._store.getState(); - const dispatch = this._store.dispatch; - // tslint:disable-next-line:no-floating-promises - asyncData.fetchEthPriceAndDispatchToStore(dispatch); - // fetch available assets if none are specified - if (state.availableAssets === undefined) { - // tslint:disable-next-line:no-floating-promises - asyncData.fetchAvailableAssetDatasAndDispatchToStore(state, dispatch); - } - if (state.providerState.account.state !== AccountState.None) { - this._accountUpdateHeartbeat = generateAccountHeartbeater({ - store: this._store, - shouldPerformImmediatelyOnStart: true, - }); - this._accountUpdateHeartbeat.start(ACCOUNT_UPDATE_INTERVAL_TIME_MS); - } - - this._swapQuoteHeartbeat = generateSwapQuoteHeartbeater({ - store: this._store, - shouldPerformImmediatelyOnStart: false, - }); - this._swapQuoteHeartbeat.start(SWAP_QUOTE_UPDATE_INTERVAL_TIME_MS); - // Trigger first buyquote fetch - // tslint:disable-next-line:no-floating-promises - asyncData.fetchCurrentSwapQuoteAndDispatchToStore(state, dispatch, QuoteFetchOrigin.Manual, { - updateSilently: false, - }); - // warm up the gas price estimator cache just in case we can't - // grab the gas price estimate when submitting the transaction - // tslint:disable-next-line:no-floating-promises - gasPriceEstimator.getGasInfoAsync(); - // tslint:disable-next-line:no-floating-promises - this._flashErrorIfWrongNetwork(); - - // Analytics - disableAnalytics(this.props.shouldDisableAnalyticsTracking || false); - analytics.addEventProperties( - analytics.generateEventProperties( - state.network, - this.props.orderSource, - state.providerState, - window, - state.selectedAsset, - this.props.affiliateInfo, - state.baseCurrency, - ), - ); - analytics.trackInstantOpened(); - } - public componentWillUnmount(): void { - if (this._accountUpdateHeartbeat) { - this._accountUpdateHeartbeat.stop(); - } - if (this._swapQuoteHeartbeat) { - this._swapQuoteHeartbeat.stop(); - } - const state = this._store.getState(); - // tslint:disable-next-line: no-floating-promises - state.providerState.swapQuoter.destroyAsync(); - } - public render(): React.ReactNode { - return ( - - {this.props.children} - - ); - } - private readonly _flashErrorIfWrongNetwork = async (): Promise => { - const msToShowError = 30000; // 30 seconds - const state = this._store.getState(); - const network = state.network; - const web3Wrapper = state.providerState.web3Wrapper; - const networkOfProvider = await web3Wrapper.getNetworkIdAsync(); - if (network !== networkOfProvider) { - const errorMessage = `Wrong network detected. Try switching to ${Network[network]}.`; - errorFlasher.flashNewErrorMessage(this._store.dispatch, errorMessage, msToShowError); - } - }; -} diff --git a/packages/instant/src/constants.ts b/packages/instant/src/constants.ts deleted file mode 100644 index 1e6ae7b8ba..0000000000 --- a/packages/instant/src/constants.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { BigNumber } from '@0x/utils'; - -import { AccountNotReady, AccountState, AffiliateInfo, Network, ProviderType } from './types'; - -// TODO(dave4506) until we have /prices endpoint ready, we will use this whitelist for bridge order liquidity assets -export const SUPPORTED_TOKEN_ASSET_DATA_WITH_BRIDGE_ORDERS = [ - '0xf47261b0000000000000000000000000e41d2489571d322189246dafa5ebde1f4699f498', // ZRX - '0xf47261b0000000000000000000000000960b236a07cf122663c4303350609a66a7b288c0', // ANT - '0xf47261b00000000000000000000000000d8775f648430679a709e98d2b0cb6250d2887ef', // BAT - '0xf47261b0000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', // USDC - '0xf47261b00000000000000000000000006b175474e89094c44da98b954eedeac495271d0f', // DAI - '0xf47261b000000000000000000000000005f4a42e251f2d52b8ed15e9fedaacfcef1fad27', // ZIL - '0xf47261b000000000000000000000000058b6a8a3302369daec383334672404ee733ab239', // LPT - '0xf47261b00000000000000000000000009f8f72aa9304c8b593d555f12ef6589cc3a579a2', // MKR - '0xf47261b0000000000000000000000000d26114cd6ee289accf82350c8d8487fedb8a0c07', // OMG - '0xf47261b0000000000000000000000000514910771af9ca656af840dff83e8264ecf986ca', // LINK - '0xf47261b00000000000000000000000001985365e9f78359a9b6ad760e32412f4a445e862', // REP -]; -export const BIG_NUMBER_ZERO = new BigNumber(0); -export const ETH_DECIMALS = 18; -export const DEFAULT_ZERO_EX_CONTAINER_SELECTOR = '#zeroExInstantContainer'; -export const INJECTED_DIV_CLASS = 'zeroExInstantResetRoot'; -export const INJECTED_DIV_ID = 'zeroExInstant'; -export const OVERLAY_DIV_CLASS = 'zeroExInstantOverlay'; -export const OVERLAY_CLOSE_BUTTON_DIV_CLASS = 'zeroExInstantOverlayCloseButton'; -export const MAIN_CONTAINER_DIV_CLASS = 'zeroExInstantMainContainer'; -export const WEB_3_WRAPPER_TRANSACTION_FAILED_ERROR_MSG_PREFIX = 'Transaction failed'; -export const GWEI_IN_WEI = new BigNumber(1000000000); -export const ONE_SECOND_MS = 1000; -export const ONE_MINUTE_MS = ONE_SECOND_MS * 60; -export const GIT_SHA = process.env.GIT_SHA; -export const NODE_ENV = process.env.NODE_ENV; -export const NPM_PACKAGE_VERSION = process.env.NPM_PACKAGE_VERSION; -export const DEFAULT_UNKOWN_ASSET_NAME = '???'; -export const ACCOUNT_UPDATE_INTERVAL_TIME_MS = ONE_SECOND_MS * 5; -export const SWAP_QUOTE_UPDATE_INTERVAL_TIME_MS = ONE_SECOND_MS * 15; -export const DEFAULT_GAS_PRICE = GWEI_IN_WEI.multipliedBy(6); -export const DEFAULT_ESTIMATED_TRANSACTION_TIME_MS = ONE_MINUTE_MS * 2; -export const MAGIC_TRIGGER_ERROR_INPUT = '0€'; -export const MAGIC_TRIGGER_ERROR_MESSAGE = 'Triggered error'; -export const ETH_GAS_STATION_API_BASE_URL = 'https://ethgasstation.info'; -export const HEAP_ANALYTICS_ID = process.env.HEAP_ANALYTICS_ID; -export const HEAP_ENABLED = process.env.HEAP_ENABLED; -export const COINBASE_API_BASE_URL = 'https://api.coinbase.com/v2'; -export const PROGRESS_STALL_AT_WIDTH = '95%'; -export const PROGRESS_FINISH_ANIMATION_TIME_MS = 200; -export const HOST_DOMAINS_EXTERNAL = [ - '0x-instant-staging.s3-website-us-east-1.amazonaws.com', - '0x-instant-dogfood.s3-website-us-east-1.amazonaws.com', - 'instant.0xproject.com', - 'instant.0x.org', -]; -export const HOST_DOMAINS_LOCAL = ['localhost', '127.0.0.1', '0.0.0.0']; -export const ROLLBAR_CLIENT_TOKEN = process.env.ROLLBAR_CLIENT_TOKEN; -export const ROLLBAR_ENABLED = process.env.ROLLBAR_ENABLED; -export const INSTANT_DISCHARGE_TARGET = process.env.INSTANT_DISCHARGE_TARGET as - | 'production' - | 'dogfood' - | 'staging' - | undefined; -export const COINBASE_WALLET_IOS_APP_STORE_URL = 'https://itunes.apple.com/us/app/coinbase-wallet/id1278383455?mt=8'; -export const COINBASE_WALLET_ANDROID_APP_STORE_URL = 'https://play.google.com/store/apps/details?id=org.toshi&hl=en'; -export const COINBASE_WALLET_SITE_URL = 'https://wallet.coinbase.com/'; -export const META_MASK_FIREFOX_STORE_URL = 'https://addons.mozilla.org/en-US/firefox/addon/ether-metamask/'; -export const META_MASK_CHROME_STORE_URL = - 'https://chrome.google.com/webstore/detail/metamask/nkbihfbeogaeaoehlefnkodbefgpgknn?hl=en'; -export const META_MASK_OPERA_STORE_URL = 'https://addons.opera.com/en/extensions/details/metamask/'; -export const META_MASK_SITE_URL = 'https://metamask.io/'; -export const ETHEREUM_NODE_URL_BY_NETWORK = { - [Network.Mainnet]: `https://mainnet.infura.io/v3/${process.env.INSTANT_INFURA_PROJECT_ID}`, - [Network.Kovan]: `https://kovan.infura.io/v3/${process.env.INSTANT_INFURA_PROJECT_ID}`, -}; -export const ZERO_EX_SITE_URL = 'https://www.0x.org/'; -export const BLOCK_POLLING_INTERVAL_MS = 10000; // 10s -export const NO_ACCOUNT: AccountNotReady = { - state: AccountState.None, -}; -export const LOADING_ACCOUNT: AccountNotReady = { - state: AccountState.Loading, -}; -export const LOCKED_ACCOUNT: AccountNotReady = { - state: AccountState.Locked, -}; -export const PROVIDER_TYPE_TO_NAME: { [key in ProviderType]: string } = { - [ProviderType.Cipher]: 'Cipher', - [ProviderType.MetaMask]: 'MetaMask', - [ProviderType.Mist]: 'Mist', - [ProviderType.CoinbaseWallet]: 'Coinbase Wallet', - [ProviderType.Parity]: 'Parity', - [ProviderType.TrustWallet]: 'Trust Wallet', - [ProviderType.Opera]: 'Opera Wallet', - [ProviderType.Fortmatic]: 'Fortmatic', - [ProviderType.Fallback]: 'Fallback', -}; -export const NULL_ADDRESS = '0x0000000000000000000000000000000000000000'; -export const DEFAULT_AFFILIATE_INFO: AffiliateInfo = { - feeRecipient: NULL_ADDRESS, - feePercentage: 0, -}; - -export const FORTMATIC_API_KEY = process.env.INSTANT_FORTMATIC_API_KEY; diff --git a/packages/instant/src/containers/available_erc20_token_selector.ts b/packages/instant/src/containers/available_erc20_token_selector.ts deleted file mode 100644 index 4d4218d22d..0000000000 --- a/packages/instant/src/containers/available_erc20_token_selector.ts +++ /dev/null @@ -1,45 +0,0 @@ -import * as _ from 'lodash'; -import * as React from 'react'; -import { connect } from 'react-redux'; -import { Dispatch } from 'redux'; - -import { State } from '../redux/reducer'; -import { ERC20Asset } from '../types'; -import { assetUtils } from '../util/asset'; - -import { ERC20TokenSelector } from '../components/erc20_token_selector'; -import { Action, actions } from '../redux/actions'; - -export interface AvailableERC20TokenSelectorProps { - onTokenSelect?: (token: ERC20Asset) => void; -} - -interface ConnectedState { - tokens: ERC20Asset[]; -} - -interface ConnectedDispatch { - onTokenSelect: (token: ERC20Asset) => void; -} - -const mapStateToProps = (state: State, _ownProps: AvailableERC20TokenSelectorProps): ConnectedState => ({ - tokens: assetUtils.getERC20AssetsFromAssets(state.availableAssets || []), -}); - -const mapDispatchToProps = ( - dispatch: Dispatch, - ownProps: AvailableERC20TokenSelectorProps, -): ConnectedDispatch => ({ - onTokenSelect: (token: ERC20Asset) => { - dispatch(actions.updateSelectedAsset(token)); - dispatch(actions.resetAmount()); - if (ownProps.onTokenSelect) { - ownProps.onTokenSelect(token); - } - }, -}); - -export const AvailableERC20TokenSelector: React.ComponentClass = connect( - mapStateToProps, - mapDispatchToProps, -)(ERC20TokenSelector); diff --git a/packages/instant/src/containers/connected_account_payment_method.ts b/packages/instant/src/containers/connected_account_payment_method.ts deleted file mode 100644 index 479a164e35..0000000000 --- a/packages/instant/src/containers/connected_account_payment_method.ts +++ /dev/null @@ -1,111 +0,0 @@ -import * as React from 'react'; -import { connect } from 'react-redux'; -import { Dispatch } from 'redux'; - -import { PaymentMethod, PaymentMethodProps } from '../components/payment_method'; -import { - COINBASE_WALLET_ANDROID_APP_STORE_URL, - COINBASE_WALLET_IOS_APP_STORE_URL, - COINBASE_WALLET_SITE_URL, -} from '../constants'; -import { Action, actions } from '../redux/actions'; -import { asyncData } from '../redux/async_data'; -import { State } from '../redux/reducer'; -import { - Network, - Omit, - OperatingSystem, - ProviderState, - ProviderType, - StandardSlidingPanelContent, - WalletSuggestion, -} from '../types'; -import { analytics } from '../util/analytics'; -import { envUtil } from '../util/env'; -import { providerStateFactory } from '../util/provider_state_factory'; - -export interface ConnectedAccountPaymentMethodProps {} - -interface ConnectedState { - network: Network; - providerState: ProviderState; - walletDisplayName?: string; -} - -interface ConnectedDispatch { - openInstallWalletPanel: () => void; - unlockWalletAndDispatchToStore: (providerState: ProviderState, providerType: ProviderType) => void; -} - -type ConnectedProps = Omit; - -type FinalProps = ConnectedProps & ConnectedAccountPaymentMethodProps; - -const mapStateToProps = (state: State, _ownProps: ConnectedAccountPaymentMethodProps): ConnectedState => ({ - network: state.network, - providerState: state.providerState, - walletDisplayName: state.walletDisplayName, -}); - -const mapDispatchToProps = ( - dispatch: Dispatch, - ownProps: ConnectedAccountPaymentMethodProps, -): ConnectedDispatch => ({ - openInstallWalletPanel: () => dispatch(actions.openStandardSlidingPanel(StandardSlidingPanelContent.InstallWallet)), - unlockWalletAndDispatchToStore: (providerState: ProviderState, providerType: ProviderType) => { - const newProviderState: ProviderState = providerStateFactory.getProviderStateBasedOnProviderType( - providerState, - providerType, - ); - // Updates provider state - dispatch(actions.setProviderState(newProviderState)); - // Unlocks wallet - analytics.trackAccountUnlockRequested(); - // tslint:disable-next-line:no-floating-promises - asyncData.fetchAccountInfoAndDispatchToStore(newProviderState, dispatch, true); - }, -}); - -const mergeProps = ( - connectedState: ConnectedState, - connectedDispatch: ConnectedDispatch, - ownProps: ConnectedAccountPaymentMethodProps, -): FinalProps => ({ - ...ownProps, - network: connectedState.network, - account: connectedState.providerState.account, - walletDisplayName: connectedState.providerState.displayName, - onUnlockWalletClick: (providerType: ProviderType) => - connectedDispatch.unlockWalletAndDispatchToStore(connectedState.providerState, providerType), - onInstallWalletClick: () => { - const isMobile = envUtil.isMobileOperatingSystem(); - const walletSuggestion: WalletSuggestion = isMobile - ? WalletSuggestion.CoinbaseWallet - : WalletSuggestion.MetaMask; - - analytics.trackInstallWalletClicked(walletSuggestion); - if (walletSuggestion === WalletSuggestion.MetaMask) { - connectedDispatch.openInstallWalletPanel(); - } else { - const operatingSystem = envUtil.getOperatingSystem(); - let url = COINBASE_WALLET_SITE_URL; - switch (operatingSystem) { - case OperatingSystem.Android: - url = COINBASE_WALLET_ANDROID_APP_STORE_URL; - break; - case OperatingSystem.iOS: - url = COINBASE_WALLET_IOS_APP_STORE_URL; - break; - default: - break; - } - window.open(url, '_blank'); - } - }, -}); - -export const ConnectedAccountPaymentMethod: React.ComponentClass = connect( - mapStateToProps, - mapDispatchToProps, - mergeProps, -)(PaymentMethod); diff --git a/packages/instant/src/containers/connected_buy_order_progress_or_payment_method.tsx b/packages/instant/src/containers/connected_buy_order_progress_or_payment_method.tsx deleted file mode 100644 index 543edac925..0000000000 --- a/packages/instant/src/containers/connected_buy_order_progress_or_payment_method.tsx +++ /dev/null @@ -1,35 +0,0 @@ -import * as React from 'react'; -import { connect } from 'react-redux'; - -import { State } from '../redux/reducer'; -import { OrderProcessState } from '../types'; - -import { ConnectedAccountPaymentMethod } from './connected_account_payment_method'; -import { SelectedAssetBuyOrderProgress } from './selected_asset_buy_order_progress'; - -interface BuyOrderProgressOrPaymentMethodProps { - orderProcessState: OrderProcessState; -} -export const BuyOrderProgressOrPaymentMethod = (props: BuyOrderProgressOrPaymentMethodProps) => { - const { orderProcessState } = props; - if ( - orderProcessState === OrderProcessState.Processing || - orderProcessState === OrderProcessState.Success || - orderProcessState === OrderProcessState.Failure - ) { - return ; - } else { - return ; - } - return null; -}; - -interface ConnectedState extends BuyOrderProgressOrPaymentMethodProps {} - -export interface ConnectedBuyOrderProgressOrPaymentMethodProps {} -const mapStateToProps = (state: State, _ownProps: ConnectedBuyOrderProgressOrPaymentMethodProps): ConnectedState => ({ - orderProcessState: state.swapOrderState.processState, -}); -export const ConnectedBuyOrderProgressOrPaymentMethod: React.ComponentClass< - ConnectedBuyOrderProgressOrPaymentMethodProps -> = connect(mapStateToProps)(BuyOrderProgressOrPaymentMethod); diff --git a/packages/instant/src/containers/current_standard_sliding_panel.ts b/packages/instant/src/containers/current_standard_sliding_panel.ts deleted file mode 100644 index 82ac7fa1ba..0000000000 --- a/packages/instant/src/containers/current_standard_sliding_panel.ts +++ /dev/null @@ -1,31 +0,0 @@ -import * as React from 'react'; -import { connect } from 'react-redux'; -import { Dispatch } from 'redux'; - -import { StandardSlidingPanel } from '../components/standard_sliding_panel'; -import { Action, actions } from '../redux/actions'; -import { State } from '../redux/reducer'; -import { StandardSlidingPanelSettings } from '../types'; - -export interface CurrentStandardSlidingPanelProps {} - -interface ConnectedState extends StandardSlidingPanelSettings {} - -interface ConnectedDispatch { - onClose: () => void; -} - -const mapStateToProps = (state: State, _ownProps: CurrentStandardSlidingPanelProps): ConnectedState => - state.standardSlidingPanelSettings; - -const mapDispatchToProps = ( - dispatch: Dispatch, - ownProps: CurrentStandardSlidingPanelProps, -): ConnectedDispatch => ({ - onClose: () => dispatch(actions.closeStandardSlidingPanel()), -}); - -export const CurrentStandardSlidingPanel: React.ComponentClass = connect( - mapStateToProps, - mapDispatchToProps, -)(StandardSlidingPanel); diff --git a/packages/instant/src/containers/latest_buy_quote_order_details.ts b/packages/instant/src/containers/latest_buy_quote_order_details.ts deleted file mode 100644 index b6b7fb5f4b..0000000000 --- a/packages/instant/src/containers/latest_buy_quote_order_details.ts +++ /dev/null @@ -1,42 +0,0 @@ -import * as _ from 'lodash'; -import * as React from 'react'; -import { connect } from 'react-redux'; -import { Dispatch } from 'redux'; -import { oc } from 'ts-optchain'; - -import { Action, actions } from '../redux/actions'; -import { State } from '../redux/reducer'; - -import { OrderDetails, OrderDetailsProps } from '../components/order_details'; -import { AsyncProcessState, BaseCurrency, Omit } from '../types'; -import { assetUtils } from '../util/asset'; - -type DispatchProperties = 'onBaseCurrencySwitchEth' | 'onBaseCurrencySwitchUsd'; - -interface ConnectedState extends Omit {} -const mapStateToProps = (state: State, _ownProps: LatestBuyQuoteOrderDetailsProps): ConnectedState => ({ - // use the worst case quote info - swapQuoteInfo: oc(state).latestSwapQuote.worstCaseQuoteInfo(), - selectedAssetUnitAmount: state.selectedAssetUnitAmount, - ethUsdPrice: state.ethUsdPrice, - isLoading: state.quoteRequestState === AsyncProcessState.Pending, - assetName: assetUtils.bestNameForAsset(state.selectedAsset), - baseCurrency: state.baseCurrency, - account: state.providerState.account, -}); - -interface ConnectedDispatch extends Pick {} -const mapDispatchToProps = (dispatch: Dispatch): ConnectedDispatch => ({ - onBaseCurrencySwitchEth: () => { - dispatch(actions.updateBaseCurrency(BaseCurrency.ETH)); - }, - onBaseCurrencySwitchUsd: () => { - dispatch(actions.updateBaseCurrency(BaseCurrency.USD)); - }, -}); - -export interface LatestBuyQuoteOrderDetailsProps {} -export const LatestBuyQuoteOrderDetails: React.ComponentClass = connect( - mapStateToProps, - mapDispatchToProps, -)(OrderDetails); diff --git a/packages/instant/src/containers/latest_error.tsx b/packages/instant/src/containers/latest_error.tsx deleted file mode 100644 index 57a2dbdc20..0000000000 --- a/packages/instant/src/containers/latest_error.tsx +++ /dev/null @@ -1,68 +0,0 @@ -import * as React from 'react'; - -import { connect } from 'react-redux'; -import { Dispatch } from 'redux'; - -import { SlidingError } from '../components/sliding_error'; -import { Container } from '../components/ui/container'; -import { Overlay } from '../components/ui/overlay'; -import { Action } from '../redux/actions'; -import { State } from '../redux/reducer'; -import { ScreenWidths } from '../style/media'; -import { generateOverlayBlack } from '../style/theme'; -import { zIndex } from '../style/z_index'; -import { Asset, DisplayStatus, Omit, SlideAnimationState } from '../types'; -import { errorFlasher } from '../util/error_flasher'; - -interface LatestErrorComponentProps { - asset?: Asset; - latestErrorMessage?: string; - animationState: SlideAnimationState; - shouldRenderOverlay: boolean; - onOverlayClick: () => void; -} - -const LatestErrorComponent: React.StatelessComponent = props => { - if (!props.latestErrorMessage) { - // Render a hidden SlidingError such that instant does not move when a real error is rendered. - return ( - - - - ); - } - return ( - - - {props.shouldRenderOverlay && ( - - )} - - ); -}; - -export interface LatestErrorProps {} -interface ConnectedState extends Omit {} -const mapStateToProps = (state: State, _ownProps: LatestErrorProps): ConnectedState => ({ - asset: state.selectedAsset, - latestErrorMessage: state.latestErrorMessage, - animationState: state.latestErrorDisplayStatus === DisplayStatus.Present ? 'slidIn' : 'slidOut', - shouldRenderOverlay: state.latestErrorDisplayStatus === DisplayStatus.Present, -}); - -type ConnectedDispatch = Pick; -const mapDispatchToProps = (dispatch: Dispatch, _ownProps: LatestErrorProps): ConnectedDispatch => ({ - onOverlayClick: () => { - errorFlasher.clearError(dispatch); - }, -}); - -export const LatestError = connect( - mapStateToProps, - mapDispatchToProps, -)(LatestErrorComponent); diff --git a/packages/instant/src/containers/selected_asset_buy_order_progress.ts b/packages/instant/src/containers/selected_asset_buy_order_progress.ts deleted file mode 100644 index 7303f5a174..0000000000 --- a/packages/instant/src/containers/selected_asset_buy_order_progress.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { connect } from 'react-redux'; - -import { BuyOrderProgress } from '../components/buy_order_progress'; -import { State } from '../redux/reducer'; -import { OrderState } from '../types'; - -interface ConnectedState { - swapOrderState: OrderState; -} -const mapStateToProps = (state: State, _ownProps: {}): ConnectedState => ({ - swapOrderState: state.swapOrderState, -}); -export const SelectedAssetBuyOrderProgress = connect(mapStateToProps)(BuyOrderProgress); diff --git a/packages/instant/src/containers/selected_asset_buy_order_state_buttons.ts b/packages/instant/src/containers/selected_asset_buy_order_state_buttons.ts deleted file mode 100644 index fcf21e86bb..0000000000 --- a/packages/instant/src/containers/selected_asset_buy_order_state_buttons.ts +++ /dev/null @@ -1,148 +0,0 @@ -import { MarketBuySwapQuote, SwapQuoteConsumer, SwapQuoteConsumerError, SwapQuoter } from '@0x/asset-swapper'; -import { BigNumber } from '@0x/utils'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import * as _ from 'lodash'; -import { connect } from 'react-redux'; -import { Dispatch } from 'redux'; - -import { BuyOrderStateButtons } from '../components/buy_order_state_buttons'; -import { Action, actions } from '../redux/actions'; -import { State } from '../redux/reducer'; -import { AccountState, AffiliateInfo, Asset, OrderProcessState, ZeroExInstantError } from '../types'; -import { analytics } from '../util/analytics'; -import { errorFlasher } from '../util/error_flasher'; -import { etherscanUtil } from '../util/etherscan'; - -interface ConnectedState { - accountAddress?: string; - accountEthBalanceInWei?: BigNumber; - swapQuote?: MarketBuySwapQuote; - swapOrderProcessingState: OrderProcessState; - swapQuoter: SwapQuoter; - swapQuoteConsumer: SwapQuoteConsumer; - web3Wrapper: Web3Wrapper; - affiliateInfo?: AffiliateInfo; - selectedAsset?: Asset; - onViewTransaction: () => void; - onSuccess?: (txHash: string) => void; -} - -// TODO(dave4506) expand errors and failures to be richer + other errors introducted in v3 of the protocol -interface ConnectedDispatch { - onValidationPending: (swapQuote: MarketBuySwapQuote) => void; - onSignatureDenied: (swapQuote: MarketBuySwapQuote) => void; - onBuyProcessing: ( - swapQuote: MarketBuySwapQuote, - txHash: string, - startTimeUnix: number, - expectedEndTimeUnix: number, - ) => void; - onBuySuccess: (swapQuote: MarketBuySwapQuote, txHash: string) => void; - onBuyFailure: (swapQuote: MarketBuySwapQuote, txHash: string) => void; - onRetry: () => void; - onValidationFail: ( - swapQuote: MarketBuySwapQuote, - errorMessage: SwapQuoteConsumerError | ZeroExInstantError, - ) => void; -} -export interface SelectedAssetBuyOrderStateButtons {} -const mapStateToProps = (state: State, _ownProps: SelectedAssetBuyOrderStateButtons): ConnectedState => { - const swapQuoter = state.providerState.swapQuoter; - const swapQuoteConsumer = state.providerState.swapQuoteConsumer; - const chainId = swapQuoteConsumer.chainId; - const web3Wrapper = state.providerState.web3Wrapper; - const account = state.providerState.account; - const accountAddress = account.state === AccountState.Ready ? account.address : undefined; - const accountEthBalanceInWei = account.state === AccountState.Ready ? account.ethBalanceInWei : undefined; - const selectedAsset = state.selectedAsset; - return { - accountAddress, - accountEthBalanceInWei, - swapOrderProcessingState: state.swapOrderState.processState, - swapQuoter, - swapQuoteConsumer, - web3Wrapper, - swapQuote: state.latestSwapQuote, - affiliateInfo: state.affiliateInfo, - selectedAsset, - onSuccess: state.onSuccess, - onViewTransaction: () => { - if ( - state.swapOrderState.processState === OrderProcessState.Processing || - state.swapOrderState.processState === OrderProcessState.Success || - state.swapOrderState.processState === OrderProcessState.Failure - ) { - const etherscanUrl = etherscanUtil.getEtherScanTxnAddressIfExists(state.swapOrderState.txHash, chainId); - if (etherscanUrl) { - analytics.trackTransactionViewed(state.swapOrderState.processState); - - window.open(etherscanUrl, '_blank'); - return; - } - } - }, - }; -}; - -const mapDispatchToProps = ( - dispatch: Dispatch, - ownProps: SelectedAssetBuyOrderStateButtons, -): ConnectedDispatch => ({ - onValidationPending: (swapQuote: MarketBuySwapQuote) => { - dispatch(actions.setSwapOrderStateValidating()); - }, - onBuyProcessing: ( - swapQuote: MarketBuySwapQuote, - txHash: string, - startTimeUnix: number, - expectedEndTimeUnix: number, - ) => { - dispatch(actions.setSwapOrderStateProcessing(txHash, startTimeUnix, expectedEndTimeUnix)); - }, - onBuySuccess: (swapQuote: MarketBuySwapQuote, txHash: string) => dispatch(actions.setSwapOrderStateSuccess(txHash)), - onBuyFailure: (swapQuote: MarketBuySwapQuote, txHash: string) => dispatch(actions.setSwapOrderStateFailure(txHash)), - onSignatureDenied: () => { - dispatch(actions.resetAmount()); - const errorMessage = 'You denied this transaction'; - errorFlasher.flashNewErrorMessage(dispatch, errorMessage); - }, - onValidationFail: (swapQuote, error) => { - dispatch(actions.setSwapOrderStateNone()); - if (error === ZeroExInstantError.InsufficientETH) { - const errorMessage = "You don't have enough ETH"; - errorFlasher.flashNewErrorMessage(dispatch, errorMessage); - } else if (error === ZeroExInstantError.CouldNotSubmitTransaction) { - const errorMessage = 'Could not submit transaction'; - errorFlasher.flashNewErrorMessage(dispatch, errorMessage); - } else { - errorFlasher.flashNewErrorMessage(dispatch); - } - }, - onRetry: () => { - dispatch(actions.resetAmount()); - }, -}); - -const mergeProps = ( - connectedState: ConnectedState, - connectedDispatch: ConnectedDispatch, - ownProps: SelectedAssetBuyOrderStateButtons, -) => { - return { - ...ownProps, - ...connectedState, - ...connectedDispatch, - onBuySuccess: (swapQuote: MarketBuySwapQuote, txHash: string) => { - connectedDispatch.onBuySuccess(swapQuote, txHash); - if (connectedState.onSuccess) { - connectedState.onSuccess(txHash); - } - }, - }; -}; - -export const SelectedAssetBuyOrderStateButtons = connect( - mapStateToProps, - mapDispatchToProps, - mergeProps, -)(BuyOrderStateButtons); diff --git a/packages/instant/src/containers/selected_asset_instant_heading.ts b/packages/instant/src/containers/selected_asset_instant_heading.ts deleted file mode 100644 index 5cf6925bfb..0000000000 --- a/packages/instant/src/containers/selected_asset_instant_heading.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { BigNumber } from '@0x/utils'; -import * as _ from 'lodash'; -import * as React from 'react'; -import { connect } from 'react-redux'; -import { oc } from 'ts-optchain'; - -import { State } from '../redux/reducer'; -import { Asset, AsyncProcessState, OrderState } from '../types'; - -import { InstantHeading } from '../components/instant_heading'; - -export interface InstantHeadingProps { - onSelectAssetClick?: (asset?: Asset) => void; -} - -interface ConnectedState { - selectedAsset?: Asset; - selectedAssetUnitAmount?: BigNumber; - totalEthBaseUnitAmount?: BigNumber; - ethUsdPrice?: BigNumber; - quoteRequestState: AsyncProcessState; - swapOrderState: OrderState; -} - -const mapStateToProps = (state: State, _ownProps: InstantHeadingProps): ConnectedState => ({ - selectedAsset: state.selectedAsset, - selectedAssetUnitAmount: state.selectedAssetUnitAmount, - totalEthBaseUnitAmount: oc(state).latestSwapQuote.worstCaseQuoteInfo.totalTakerAssetAmount(), - ethUsdPrice: state.ethUsdPrice, - quoteRequestState: state.quoteRequestState, - swapOrderState: state.swapOrderState, -}); - -export const SelectedAssetInstantHeading: React.ComponentClass = connect(mapStateToProps)( - InstantHeading, -); diff --git a/packages/instant/src/containers/selected_asset_theme_provider.ts b/packages/instant/src/containers/selected_asset_theme_provider.ts deleted file mode 100644 index cb69e3ba9c..0000000000 --- a/packages/instant/src/containers/selected_asset_theme_provider.ts +++ /dev/null @@ -1,32 +0,0 @@ -import * as _ from 'lodash'; -import * as React from 'react'; -import { connect } from 'react-redux'; - -import { State } from '../redux/reducer'; -import { Theme, theme as defaultTheme, ThemeProvider } from '../style/theme'; -import { Asset } from '../types'; - -export interface SelectedAssetThemeProviderProps {} - -interface ConnectedState { - theme: Theme; -} - -const getTheme = (asset?: Asset): Theme => { - if (asset !== undefined && asset.metaData.primaryColor !== undefined) { - return { - ...defaultTheme, - primaryColor: asset.metaData.primaryColor, - }; - } - return defaultTheme; -}; - -const mapStateToProps = (state: State, _ownProps: SelectedAssetThemeProviderProps): ConnectedState => { - const theme = getTheme(state.selectedAsset); - return { theme }; -}; - -export const SelectedAssetThemeProvider: React.ComponentClass = connect( - mapStateToProps, -)(ThemeProvider); diff --git a/packages/instant/src/containers/selected_erc20_asset_amount_input.ts b/packages/instant/src/containers/selected_erc20_asset_amount_input.ts deleted file mode 100644 index 191da44bb3..0000000000 --- a/packages/instant/src/containers/selected_erc20_asset_amount_input.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { SwapQuoter } from '@0x/asset-swapper'; -import { AssetProxyId } from '@0x/types'; -import { BigNumber } from '@0x/utils'; -import * as _ from 'lodash'; -import * as React from 'react'; -import { connect } from 'react-redux'; -import { Dispatch } from 'redux'; - -import { ERC20AssetAmountInput, ERC20AssetAmountInputProps } from '../components/erc20_asset_amount_input'; -import { Action, actions } from '../redux/actions'; -import { State } from '../redux/reducer'; -import { ColorOption } from '../style/theme'; -import { ERC20Asset, Omit, OrderProcessState, QuoteFetchOrigin } from '../types'; -import { swapQuoteUpdater } from '../util/swap_quote_updater'; - -export interface SelectedERC20AssetAmountInputProps { - fontColor?: ColorOption; - startingFontSizePx: number; - onSelectAssetClick?: (asset?: ERC20Asset) => void; -} - -interface ConnectedState { - swapQuoter: SwapQuoter; - value?: BigNumber; - asset?: ERC20Asset; - isInputDisabled: boolean; - numberOfAssetsAvailable?: number; - canSelectOtherAsset: boolean; -} - -interface ConnectedDispatch { - updateSwapQuote: (swapQuoter: SwapQuoter, value?: BigNumber, asset?: ERC20Asset) => void; -} - -type ConnectedProps = Omit; - -type FinalProps = ConnectedProps & SelectedERC20AssetAmountInputProps; - -const mapStateToProps = (state: State, _ownProps: SelectedERC20AssetAmountInputProps): ConnectedState => { - const processState = state.swapOrderState.processState; - const isInputEnabled = processState === OrderProcessState.None || processState === OrderProcessState.Failure; - const isInputDisabled = !isInputEnabled; - const selectedAsset = - state.selectedAsset !== undefined && state.selectedAsset.metaData.assetProxyId === AssetProxyId.ERC20 - ? (state.selectedAsset as ERC20Asset) - : undefined; - const numberOfAssetsAvailable = state.availableAssets === undefined ? undefined : state.availableAssets.length; - const canSelectOtherAsset = - numberOfAssetsAvailable && numberOfAssetsAvailable > 1 - ? isInputEnabled || processState === OrderProcessState.Success - : false; - - const swapQuoter = state.providerState.swapQuoter; - return { - swapQuoter, - value: state.selectedAssetUnitAmount, - asset: selectedAsset, - isInputDisabled, - numberOfAssetsAvailable, - canSelectOtherAsset, - }; -}; - -const debouncedUpdateSwapQuoteAsync = _.debounce(swapQuoteUpdater.updateSwapQuoteAsync.bind(swapQuoteUpdater), 200, { - trailing: true, -}) as typeof swapQuoteUpdater.updateSwapQuoteAsync; - -const mapDispatchToProps = ( - dispatch: Dispatch, - _ownProps: SelectedERC20AssetAmountInputProps, -): ConnectedDispatch => ({ - updateSwapQuote: (swapQuoter, value, asset) => { - // Update the input - dispatch(actions.updateSelectedAssetAmount(value)); - // invalidate the last swap quote. - dispatch(actions.updateLatestSwapQuote(undefined)); - // reset our swap state - dispatch(actions.setSwapOrderStateNone()); - - if (value !== undefined && value.isGreaterThan(0) && asset !== undefined) { - // even if it's debounced, give them the illusion it's loading - dispatch(actions.setQuoteRequestStatePending()); - // tslint:disable-next-line:no-floating-promises - debouncedUpdateSwapQuoteAsync(swapQuoter, dispatch, asset, value, QuoteFetchOrigin.Manual, { - setPending: true, - dispatchErrors: true, - }); - } - }, -}); - -const mergeProps = ( - connectedState: ConnectedState, - connectedDispatch: ConnectedDispatch, - ownProps: SelectedERC20AssetAmountInputProps, -): FinalProps => { - return { - ...ownProps, - asset: connectedState.asset, - value: connectedState.value, - onChange: (value, asset) => { - connectedDispatch.updateSwapQuote(connectedState.swapQuoter, value, asset); - }, - isInputDisabled: connectedState.isInputDisabled, - numberOfAssetsAvailable: connectedState.numberOfAssetsAvailable, - canSelectOtherAsset: connectedState.canSelectOtherAsset, - }; -}; - -export const SelectedERC20AssetAmountInput: React.ComponentClass = connect( - mapStateToProps, - mapDispatchToProps, - mergeProps, -)(ERC20AssetAmountInput); diff --git a/packages/instant/src/data/asset_data_network_mapping.ts b/packages/instant/src/data/asset_data_network_mapping.ts deleted file mode 100644 index 77fe75adc9..0000000000 --- a/packages/instant/src/data/asset_data_network_mapping.ts +++ /dev/null @@ -1,71 +0,0 @@ -import * as _ from 'lodash'; - -import { Network } from '../types'; - -interface AssetDataByNetwork { - [Network.Kovan]?: string; - [Network.Mainnet]?: string; -} - -export const assetDataNetworkMapping: AssetDataByNetwork[] = [ - // ZRX - { - [Network.Mainnet]: '0xf47261b0000000000000000000000000e41d2489571d322189246dafa5ebde1f4699f498', - [Network.Kovan]: '0xf47261b00000000000000000000000002002d3812f58e35f0ea1ffbf80a75a38c32175fa', - }, - // SPANK - { - [Network.Mainnet]: '0xf47261b000000000000000000000000042d6622dece394b54999fbd73d108123806f6a18', - [Network.Kovan]: '0xf47261b00000000000000000000000007c9eee8448f3a7d1193389652d863b27e543272d', - }, - // OMG - { - [Network.Mainnet]: '0xf47261b0000000000000000000000000d26114cd6ee289accf82350c8d8487fedb8a0c07', - [Network.Kovan]: '0xf47261b000000000000000000000000046096d8ec059dbaae2950b30e01634ff0dc652ec', - }, - // MKR - { - [Network.Mainnet]: '0xf47261b00000000000000000000000009f8f72aa9304c8b593d555f12ef6589cc3a579a2', - // 0x Kovan MKR - [Network.Kovan]: '0xf47261b00000000000000000000000007b6b10caa9e8e9552ba72638ea5b47c25afea1f3', - }, - // BAT - { - [Network.Mainnet]: '0xf47261b00000000000000000000000000d8775f648430679a709e98d2b0cb6250d2887ef', - [Network.Kovan]: '0xf47261b0000000000000000000000000c87faa7a58f0adf306bad9e7d892fb045a20e5af', - }, - // SNT - { - [Network.Mainnet]: '0xf47261b0000000000000000000000000744d70fdbe2ba4cf95131626614a1763df805b9e', - [Network.Kovan]: '0xf47261b00000000000000000000000009cfe76a718ea75e3e8ce4fc7ad0fef84be70919b', - }, - // MANA - { - [Network.Mainnet]: '0xf47261b00000000000000000000000000f5d2fb29fb7d3cfee444a200298f468908cc942', - [Network.Kovan]: '0xf47261b0000000000000000000000000c64edfc78321673435fbeebdaaa7f9d755963542', - }, - // GNT - { - [Network.Mainnet]: '0xf47261b0000000000000000000000000a74476443119a942de498590fe1f2454d7d4ac0d', - // 0x Kovan GNT - [Network.Kovan]: '0xf47261b000000000000000000000000031fb614e223706f15d0d3c5f4b08bdf0d5c78623', - }, - // SUB - { - [Network.Mainnet]: '0xf47261b000000000000000000000000012480e24eb5bec1a9d4369cab6a80cad3c0a377a', - }, - // Dentacoin - { - [Network.Mainnet]: '0xf47261b000000000000000000000000008d32b0da63e2C3bcF8019c9c5d849d7a9d791e6', - }, - // REP - { - [Network.Kovan]: '0xf47261b00000000000000000000000008cb3971b8eb709c14616bd556ff6683019e90d9c', - [Network.Mainnet]: '0xf47261b00000000000000000000000001985365e9f78359a9b6ad760e32412f4a445e862', - }, - // USDC - { - [Network.Kovan]: '', - [Network.Mainnet]: '0xf47261b0000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', - }, -]; diff --git a/packages/instant/src/data/asset_meta_data_map.ts b/packages/instant/src/data/asset_meta_data_map.ts deleted file mode 100644 index 1a59b97a5e..0000000000 --- a/packages/instant/src/data/asset_meta_data_map.ts +++ /dev/null @@ -1,209 +0,0 @@ -import { AssetProxyId, ObjectMap } from '@0x/types'; - -import { AssetMetaData } from '../types'; - -export const assetMetaDataMap: ObjectMap = { - '0xf47261b0000000000000000000000000e41d2489571d322189246dafa5ebde1f4699f498': { - assetProxyId: AssetProxyId.ERC20, - decimals: 18, - primaryColor: '#333333', - symbol: 'zrx', - name: '0x', - }, - '0xf47261b000000000000000000000000042d6622dece394b54999fbd73d108123806f6a18': { - assetProxyId: AssetProxyId.ERC20, - decimals: 18, - primaryColor: '#EC4F81', - symbol: 'spank', - name: 'Spank', - }, - '0xf47261b0000000000000000000000000d26114cd6ee289accf82350c8d8487fedb8a0c07': { - assetProxyId: AssetProxyId.ERC20, - decimals: 18, - primaryColor: '#2458E7', - symbol: 'omg', - name: 'OmiseGo', - }, - '0xf47261b00000000000000000000000009f8f72aa9304c8b593d555f12ef6589cc3a579a2': { - assetProxyId: AssetProxyId.ERC20, - decimals: 18, - primaryColor: '#68CCBB', - symbol: 'mkr', - name: 'Maker', - }, - '0xf47261b00000000000000000000000000d8775f648430679a709e98d2b0cb6250d2887ef': { - assetProxyId: AssetProxyId.ERC20, - decimals: 18, - primaryColor: '#FF5000', - symbol: 'bat', - name: 'Basic Attention Token', - }, - '0xf47261b0000000000000000000000000744d70fdbe2ba4cf95131626614a1763df805b9e': { - assetProxyId: AssetProxyId.ERC20, - decimals: 18, - primaryColor: '#4763D7', - symbol: 'snt', - name: 'Status', - }, - '0xf47261b00000000000000000000000000f5d2fb29fb7d3cfee444a200298f468908cc942': { - assetProxyId: AssetProxyId.ERC20, - decimals: 18, - primaryColor: '#f08839', - symbol: 'mana', - name: 'Decentraland', - }, - '0xf47261b00000000000000000000000001985365e9f78359a9b6ad760e32412f4a445e862': { - assetProxyId: AssetProxyId.ERC20, - decimals: 18, - primaryColor: '#512D80', - symbol: 'rep', - name: 'Augur', - }, - '0xf47261b00000000000000000000000000abdace70d3790235af448c88547603b945604ea': { - assetProxyId: AssetProxyId.ERC20, - decimals: 18, - primaryColor: '#2c3c8c', - symbol: 'dnt', - name: 'district0x', - }, - '0xf47261b000000000000000000000000005f4a42e251f2d52b8ed15e9fedaacfcef1fad27': { - assetProxyId: AssetProxyId.ERC20, - decimals: 12, - primaryColor: '#048998', - symbol: 'zil', - name: 'Zilliqa', - }, - '0xf47261b00000000000000000000000008f8221afbb33998d8584a2b05749ba73c37a938a': { - assetProxyId: AssetProxyId.ERC20, - decimals: 18, - primaryColor: '#58BFD6', - symbol: 'req', - name: 'Request Network', - }, - '0xf47261b0000000000000000000000000e0b7927c4af23765cb51314a0e0521a9645f0e2a': { - assetProxyId: AssetProxyId.ERC20, - decimals: 9, - primaryColor: '#E1AA3E', - symbol: 'dgd', - name: 'DigixDao', - }, - '0xf47261b00000000000000000000000004f3afec4e5a3f2a6a1a411def7d7dfe50ee057bf': { - assetProxyId: AssetProxyId.ERC20, - decimals: 9, - primaryColor: '#E1AA3E', - symbol: 'dgx', - name: 'Digix Gold Token', - }, - '0xf47261b0000000000000000000000000419d0d8bdd9af5e606ae2232ed285aff190e711b': { - assetProxyId: AssetProxyId.ERC20, - decimals: 8, - primaryColor: '#E40057', - symbol: 'fun', - name: 'FunFair', - }, - '0xf47261b000000000000000000000000041e5560054824ea6b0732e656e3ad64e20e94e45': { - assetProxyId: AssetProxyId.ERC20, - decimals: 8, - primaryColor: '#04bc24', - symbol: 'cvc', - name: 'Civic', - }, - '0xf47261b00000000000000000000000005ca9a71b1d01849c0a95490cc00559717fcf0d1d': { - assetProxyId: AssetProxyId.ERC20, - decimals: 18, - primaryColor: '#F7296E', - symbol: 'ae', - name: 'Aeternity', - }, - '0xf47261b0000000000000000000000000408e41876cccdc0f92210600ef50372656052a38': { - assetProxyId: AssetProxyId.ERC20, - decimals: 18, - primaryColor: '#233C5A', - symbol: 'ren', - name: 'Republic Protocol', - }, - '0xf47261b0000000000000000000000000514910771af9ca656af840dff83e8264ecf986ca': { - assetProxyId: AssetProxyId.ERC20, - decimals: 18, - primaryColor: '#325CD2', - symbol: 'link', - name: 'ChainLink', - }, - '0xf47261b00000000000000000000000006810e776880c02933d47db1b9fc05908e5386b96': { - assetProxyId: AssetProxyId.ERC20, - decimals: 18, - primaryColor: '#48A4C0', - symbol: 'gno', - name: 'Gnosis', - }, - '0xf47261b0000000000000000000000000960b236a07cf122663c4303350609a66a7b288c0': { - assetProxyId: AssetProxyId.ERC20, - decimals: 18, - primaryColor: '#04a29e', - symbol: 'ant', - name: 'Aragon', - }, - '0xf47261b00000000000000000000000004156d3342d5c385a87d264f90653733592000581': { - assetProxyId: AssetProxyId.ERC20, - decimals: 8, - primaryColor: '#4CABA7', - symbol: 'salt', - name: 'Salt', - }, - '0xf47261b0000000000000000000000000595832f8fc6bf59c85c527fec3740a1b7a361269': { - assetProxyId: AssetProxyId.ERC20, - decimals: 6, - primaryColor: '#5BC9D4', - symbol: 'powr', - name: 'PowerLedger', - }, - '0xf47261b00000000000000000000000008eb24319393716668d768dcec29356ae9cffe285': { - assetProxyId: AssetProxyId.ERC20, - decimals: 8, - primaryColor: '#523CE8', - symbol: 'agi', - name: 'SingularityNET', - }, - '0xf47261b000000000000000000000000039bb259f66e1c59d5abef88375979b4d20d98022': { - assetProxyId: AssetProxyId.ERC20, - decimals: 8, - primaryColor: '#EDB740', - symbol: 'wax', - name: 'WAX', - }, - '0xf47261b0000000000000000000000000beb9ef514a379b997e0798fdcc901ee474b6d9a1': { - assetProxyId: AssetProxyId.ERC20, - decimals: 18, - primaryColor: '#333333', - symbol: 'mln', - name: 'Melon', - }, - '0xf47261b000000000000000000000000058b6a8a3302369daec383334672404ee733ab239': { - assetProxyId: AssetProxyId.ERC20, - decimals: 18, - primaryColor: '#232D37', - symbol: 'lpt', - name: 'Livepeer', - }, - '0xf47261b000000000000000000000000027054b13b1b798b345b591a4d22e6562d47ea75a': { - assetProxyId: AssetProxyId.ERC20, - decimals: 4, - primaryColor: '#3A74F6', - symbol: 'ast', - name: 'AirSwap', - }, - '0xf47261b00000000000000000000000006b175474e89094c44da98b954eedeac495271d0f': { - assetProxyId: AssetProxyId.ERC20, - decimals: 18, - primaryColor: '#DEA349', - symbol: 'dai', - name: 'Dai Stablecoin', - }, - '0xf47261b0000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48': { - assetProxyId: AssetProxyId.ERC20, - decimals: 6, - primaryColor: '#2775CA', - symbol: 'usdc', - name: 'USD Coin', - }, -}; diff --git a/packages/instant/src/globals.d.ts b/packages/instant/src/globals.d.ts deleted file mode 100644 index b2cb51bc65..0000000000 --- a/packages/instant/src/globals.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -declare module '*.svg' { - const content: any; - /* tslint:disable */ - export default content; - /* tslint:enable */ -} -declare module '*.json' { - const json: any; - /* tslint:disable */ - export default json; - /* tslint:enable */ -} -declare module 'fortmatic'; diff --git a/packages/instant/src/index.ts b/packages/instant/src/index.ts deleted file mode 100644 index 6e611dae87..0000000000 --- a/packages/instant/src/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { ZeroExInstant, ZeroExInstantProps } from './components/zero_ex_instant'; -export { ZeroExInstantOverlay, ZeroExInstantOverlayProps } from './components/zero_ex_instant_overlay'; diff --git a/packages/instant/src/index.umd.ts b/packages/instant/src/index.umd.ts deleted file mode 100644 index e5a89451ae..0000000000 --- a/packages/instant/src/index.umd.ts +++ /dev/null @@ -1,204 +0,0 @@ -import { BigNumber, SwapQuoter } from '@0x/asset-swapper'; -import { AssetProxyId } from '@0x/types'; -import { providerUtils } from '@0x/utils'; -import { SupportedProvider, ZeroExProvider } from 'ethereum-types'; -import * as _ from 'lodash'; -import * as React from 'react'; -import * as ReactDOM from 'react-dom'; - -import { - DEFAULT_ZERO_EX_CONTAINER_SELECTOR, - GIT_SHA as GIT_SHA_FROM_CONSTANT, - INJECTED_DIV_CLASS, - INJECTED_DIV_ID, - NPM_PACKAGE_VERSION, -} from './constants'; -import { assetMetaDataMap } from './data/asset_meta_data_map'; -import { ZeroExInstantOverlay, ZeroExInstantOverlayProps } from './index'; -import { Network, OrderSource } from './types'; -import { analytics } from './util/analytics'; -import { assert } from './util/assert'; -import { assetDataEncoder } from './util/asset_data_encoder'; -import { orderCoercionUtil } from './util/order_coercion'; -import { providerFactory } from './util/provider_factory'; -import { util } from './util/util'; - -const isInstantRendered = (): boolean => !!document.getElementById(INJECTED_DIV_ID); - -const validateInstantRenderConfig = (config: ZeroExInstantConfig, selector: string) => { - assert.isValidOrderSource('orderSource', config.orderSource); - if (config.defaultSelectedAssetData !== undefined) { - assert.isHexString('defaultSelectedAssetData', config.defaultSelectedAssetData); - } - if (config.additionalAssetMetaDataMap !== undefined) { - assert.isValidAssetMetaDataMap('additionalAssetMetaDataMap', config.additionalAssetMetaDataMap); - } - if (config.defaultAssetBuyAmount !== undefined) { - assert.isNumber('defaultAssetBuyAmount', config.defaultAssetBuyAmount); - } - if (config.networkId !== undefined) { - assert.isNumber('networkId', config.networkId); - } - if (config.availableAssetDatas !== undefined) { - assert.areValidAssetDatas('availableAssetDatas', config.availableAssetDatas); - } - if (config.onClose !== undefined) { - assert.isFunction('onClose', config.onClose); - } - if (config.zIndex !== undefined) { - assert.isNumber('zIndex', config.zIndex); - } - if (config.affiliateInfo !== undefined) { - assert.isValidAffiliateInfo('affiliateInfo', config.affiliateInfo); - } - if (config.provider !== undefined) { - providerUtils.standardizeOrThrow(config.provider); - } - if (config.walletDisplayName !== undefined) { - assert.isString('walletDisplayName', config.walletDisplayName); - } - if (config.shouldDisablePushToHistory !== undefined) { - assert.isBoolean('shouldDisablePushToHistory', config.shouldDisablePushToHistory); - } - if (config.shouldDisableAnalyticsTracking !== undefined) { - assert.isBoolean('shouldDisableAnalyticsTracking', config.shouldDisableAnalyticsTracking); - } - assert.isString('selector', selector); -}; - -let injectedDiv: HTMLDivElement | undefined; -let parentElement: Element | undefined; -export const unrender = () => { - if (!injectedDiv) { - return; - } - - ReactDOM.unmountComponentAtNode(injectedDiv); - if (parentElement && parentElement.contains(injectedDiv)) { - parentElement.removeChild(injectedDiv); - } -}; - -// Render instant and return a callback that allows you to remove it from the DOM. -const renderInstant = (config: ZeroExInstantConfig, selector: string) => { - const appendToIfExists = document.querySelector(selector); - assert.assert(appendToIfExists !== null, `Could not find div with selector: ${selector}`); - parentElement = appendToIfExists as Element; - injectedDiv = document.createElement('div'); - injectedDiv.setAttribute('id', INJECTED_DIV_ID); - injectedDiv.setAttribute('class', INJECTED_DIV_CLASS); - parentElement.appendChild(injectedDiv); - const closeInstant = () => { - analytics.trackInstantClosed(); - if (config.onClose !== undefined) { - config.onClose(); - } - unrender(); - }; - const instantOverlayProps = { - ...config, - // If we are using the history API, just go back to close - onClose: () => (config.shouldDisablePushToHistory ? closeInstant() : window.history.back()), - }; - ReactDOM.render(React.createElement(ZeroExInstantOverlay, instantOverlayProps), injectedDiv); - return closeInstant; -}; - -export interface ZeroExInstantConfig extends ZeroExInstantOverlayProps { - shouldDisablePushToHistory?: boolean; -} - -export const render = (config: ZeroExInstantConfig, selector: string = DEFAULT_ZERO_EX_CONTAINER_SELECTOR) => { - // Coerces BigNumber provided in config to version utilized by 0x packages - const coercedConfig = _.assign({}, config, { - orderSource: _.isArray(config.orderSource) - ? orderCoercionUtil.coerceOrderArrayFieldsToBigNumber(config.orderSource) - : config.orderSource, - }); - - validateInstantRenderConfig(coercedConfig, selector); - - if (coercedConfig.shouldDisablePushToHistory) { - if (!isInstantRendered()) { - renderInstant(coercedConfig, selector); - } - return; - } - // Before we render, push to history saying that instant is showing for this part of the history. - window.history.pushState({ zeroExInstantShowing: true }, '0x Instant'); - let removeInstant = renderInstant(coercedConfig, selector); - // If the integrator defined a popstate handler, save it to __zeroExInstantIntegratorsPopStateHandler - // unless we have already done so on a previous render. - const anyWindow = window as any; - const popStateExistsAndNotSetPreviously = window.onpopstate && !anyWindow.__zeroExInstantIntegratorsPopStateHandler; - anyWindow.__zeroExInstantIntegratorsPopStateHandler = popStateExistsAndNotSetPreviously - ? anyWindow.onpopstate.bind(window) - : util.boundNoop; - const onPopStateHandler = (e: PopStateEvent) => { - anyWindow.__zeroExInstantIntegratorsPopStateHandler(e); - const newState = e.state; - if (newState && newState.zeroExInstantShowing) { - // We have returned to a history state that expects instant to be rendered. - if (!isInstantRendered()) { - removeInstant = renderInstant(coercedConfig, selector); - } - } else { - // History has changed to a different state. - if (isInstantRendered()) { - removeInstant(); - } - } - }; - window.onpopstate = onPopStateHandler; -}; - -export const ERC721_PROXY_ID = AssetProxyId.ERC721; - -export const ERC20_PROXY_ID = AssetProxyId.ERC20; - -export const assetDataForERC20TokenAddress = (tokenAddress: string): string => { - assert.isETHAddressHex('tokenAddress', tokenAddress); - return assetDataEncoder.ERC20Token(tokenAddress).getABIEncodedTransactionData(); -}; - -export const assetDataForERC721TokenAddress = (tokenAddress: string, tokenId: string | number): string => { - assert.isETHAddressHex('tokenAddress', tokenAddress); - return assetDataEncoder.ERC721Token(tokenAddress, new BigNumber(tokenId)).getABIEncodedTransactionData(); -}; - -export const hasMetaDataForAssetData = (assetData: string): boolean => { - assert.isHexString('assetData', assetData); - return assetMetaDataMap[assetData] !== undefined; -}; - -export const hasLiquidityForAssetDataAsync = async ( - takerAssetData: string, - orderSource: OrderSource, - chainId: Network = Network.Mainnet, - supportedProvider?: SupportedProvider, -): Promise => { - assert.isHexString('takerAssetData', takerAssetData); - assert.isValidOrderSource('orderSource', orderSource); - assert.isNumber('chainId', chainId); - - let provider = supportedProvider; - if (provider !== undefined) { - provider = providerUtils.standardizeOrThrow(provider); - } - - const bestProvider: ZeroExProvider = provider || providerFactory.getFallbackNoSigningProvider(chainId); - - const swapQuoterOptions = { chainId }; - - const swapQuoter = _.isString(orderSource) - ? SwapQuoter.getSwapQuoterForStandardRelayerAPIUrl(bestProvider, orderSource, swapQuoterOptions) - : SwapQuoter.getSwapQuoterForProvidedOrders(bestProvider, orderSource, swapQuoterOptions); - - const wethAssetData = await swapQuoter.getEtherTokenAssetDataOrThrowAsync(); - const liquidity = await swapQuoter.getLiquidityForMakerTakerAssetDataPairAsync(wethAssetData, takerAssetData); - return liquidity.makerAssetAvailableInBaseUnits.gt(new BigNumber(0)); -}; - -// Write version info to the exported object for debugging -export const GIT_SHA = GIT_SHA_FROM_CONSTANT; -export const NPM_VERSION = NPM_PACKAGE_VERSION; diff --git a/packages/instant/src/redux/actions.ts b/packages/instant/src/redux/actions.ts deleted file mode 100644 index a854fe2afc..0000000000 --- a/packages/instant/src/redux/actions.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { MarketBuySwapQuote } from '@0x/asset-swapper'; -import { BigNumber } from '@0x/utils'; - -import { - ActionsUnion, - AddressAndEthBalanceInWei, - Asset, - BaseCurrency, - ProviderState, - StandardSlidingPanelContent, -} from '../types'; - -export interface PlainAction { - type: T; -} - -export interface ActionWithPayload extends PlainAction { - data: P; -} - -export type Action = ActionsUnion; - -function createAction(type: T): PlainAction; -function createAction(type: T, data: P): ActionWithPayload; -function createAction(type: T, data?: P): PlainAction | ActionWithPayload { - return data === undefined ? { type } : { type, data }; -} - -export enum ActionTypes { - SetAccountStateLoading = 'SET_ACCOUNT_STATE_LOADING', - SetAccountStateLocked = 'SET_ACCOUNT_STATE_LOCKED', - SetAccountStateReady = 'SET_ACCOUNT_STATE_READY', - SetAccountStateNone = 'SET_ACCOUNT_STATE_NONE', - UpdateAccountEthBalance = 'UPDATE_ACCOUNT_ETH_BALANCE', - UpdateEthUsdPrice = 'UPDATE_ETH_USD_PRICE', - UpdateSelectedAssetUnitAmount = 'UPDATE_SELECTED_ASSET_UNIT_AMOUNT', - SetSwapOrderStateNone = 'SET_SWAP_ORDER_STATE_NONE', - SetSwapOrderStateValidating = 'SET_SWAP_ORDER_STATE_VALIDATING', - SetSwapOrderStateProcessing = 'SET_SWAP_ORDER_STATE_PROCESSING', - SetSwapOrderStateFailure = 'SET_SWAP_ORDER_STATE_FAILURE', - SetSwapOrderStateSuccess = 'SET_SWAP_ORDER_STATE_SUCCESS', - UpdateLatestSwapQuote = 'UPDATE_LATEST_SWAP_QUOTE', - UpdateSelectedAsset = 'UPDATE_SELECTED_ASSET', - SetAvailableAssets = 'SET_AVAILABLE_ASSETS', - SetQuoteRequestStatePending = 'SET_QUOTE_REQUEST_STATE_PENDING', - SetQuoteRequestStateFailure = 'SET_QUOTE_REQUEST_STATE_FAILURE', - SetErrorMessage = 'SET_ERROR_MESSAGE', - HideError = 'HIDE_ERROR', - ClearError = 'CLEAR_ERROR', - ResetAmount = 'RESET_AMOUNT', - OpenStandardSlidingPanel = 'OPEN_STANDARD_SLIDING_PANEL', - CloseStandardSlidingPanel = 'CLOSE_STANDARD_SLIDING_PANEL', - UpdateBaseCurrency = 'UPDATE_BASE_CURRENCY', - SetProviderState = 'SET_PROVIDER_STATE', -} - -export const actions = { - setAccountStateLoading: () => createAction(ActionTypes.SetAccountStateLoading), - setAccountStateLocked: () => createAction(ActionTypes.SetAccountStateLocked), - setAccountStateNone: () => createAction(ActionTypes.SetAccountStateNone), - setAccountStateReady: (address: string) => createAction(ActionTypes.SetAccountStateReady, address), - updateAccountEthBalance: (addressAndBalance: AddressAndEthBalanceInWei) => - createAction(ActionTypes.UpdateAccountEthBalance, addressAndBalance), - updateEthUsdPrice: (price?: BigNumber) => createAction(ActionTypes.UpdateEthUsdPrice, price), - updateSelectedAssetAmount: (amount?: BigNumber) => createAction(ActionTypes.UpdateSelectedAssetUnitAmount, amount), - setSwapOrderStateNone: () => createAction(ActionTypes.SetSwapOrderStateNone), - setSwapOrderStateValidating: () => createAction(ActionTypes.SetSwapOrderStateValidating), - setSwapOrderStateProcessing: (txHash: string, startTimeUnix: number, expectedEndTimeUnix: number) => - createAction(ActionTypes.SetSwapOrderStateProcessing, { txHash, startTimeUnix, expectedEndTimeUnix }), - setSwapOrderStateFailure: (txHash: string) => createAction(ActionTypes.SetSwapOrderStateFailure, txHash), - setSwapOrderStateSuccess: (txHash: string) => createAction(ActionTypes.SetSwapOrderStateSuccess, txHash), - updateLatestSwapQuote: (swapQuote?: MarketBuySwapQuote) => - createAction(ActionTypes.UpdateLatestSwapQuote, swapQuote), - updateSelectedAsset: (asset: Asset) => createAction(ActionTypes.UpdateSelectedAsset, asset), - setAvailableAssets: (availableAssets: Asset[]) => createAction(ActionTypes.SetAvailableAssets, availableAssets), - setQuoteRequestStatePending: () => createAction(ActionTypes.SetQuoteRequestStatePending), - setQuoteRequestStateFailure: () => createAction(ActionTypes.SetQuoteRequestStateFailure), - setErrorMessage: (errorMessage: string) => createAction(ActionTypes.SetErrorMessage, errorMessage), - hideError: () => createAction(ActionTypes.HideError), - clearError: () => createAction(ActionTypes.ClearError), - resetAmount: () => createAction(ActionTypes.ResetAmount), - openStandardSlidingPanel: (content: StandardSlidingPanelContent) => - createAction(ActionTypes.OpenStandardSlidingPanel, content), - closeStandardSlidingPanel: () => createAction(ActionTypes.CloseStandardSlidingPanel), - updateBaseCurrency: (baseCurrency: BaseCurrency) => createAction(ActionTypes.UpdateBaseCurrency, baseCurrency), - setProviderState: (providerState: ProviderState) => createAction(ActionTypes.SetProviderState, providerState), -}; diff --git a/packages/instant/src/redux/analytics_middleware.ts b/packages/instant/src/redux/analytics_middleware.ts deleted file mode 100644 index 4b4d30213f..0000000000 --- a/packages/instant/src/redux/analytics_middleware.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { AssetProxyId } from '@0x/types'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import * as _ from 'lodash'; -import { Middleware } from 'redux'; - -import { ETH_DECIMALS } from '../constants'; -import { AccountState, StandardSlidingPanelContent } from '../types'; -import { analytics, AnalyticsEventOptions } from '../util/analytics'; - -import { Action, ActionTypes } from './actions'; - -import { State } from './reducer'; - -export const analyticsMiddleware: Middleware = store => next => middlewareAction => { - const prevState = store.getState() as State; - const prevAccount = prevState.providerState.account; - - const nextAction = next(middlewareAction) as Action; - - const curState = store.getState() as State; - const curAccount = curState.providerState.account; - - switch (nextAction.type) { - case ActionTypes.SetAccountStateReady: - if (curAccount.state === AccountState.Ready) { - const didJustTurnReady = prevAccount.state !== AccountState.Ready; - const didJustUpdateAddress = - prevAccount.state === AccountState.Ready && prevAccount.address !== curAccount.address; - const ethAddress = curAccount.address; - if (didJustTurnReady) { - analytics.trackAccountReady(ethAddress); - analytics.addUserProperties({ lastKnownEthAddress: ethAddress }); - analytics.addEventProperties({ ethAddress }); - } else if (didJustUpdateAddress) { - analytics.trackAccountAddressChanged(ethAddress); - analytics.addUserProperties({ lastKnownEthAddress: ethAddress }); - analytics.addEventProperties({ ethAddress }); - } - } - break; - case ActionTypes.SetAccountStateLocked: - if (prevAccount.state !== AccountState.Locked && curAccount.state === AccountState.Locked) { - // if we are moving from account not locked to account locked, track `Account - Locked` - analytics.trackAccountLocked(); - } - break; - case ActionTypes.UpdateAccountEthBalance: - if ( - curAccount.state === AccountState.Ready && - curAccount.ethBalanceInWei && - !_.isEqual(curAccount, prevAccount) - ) { - const ethBalanceInUnitAmount = Web3Wrapper.toUnitAmount( - curAccount.ethBalanceInWei, - ETH_DECIMALS, - ).toString(); - analytics.addUserProperties({ lastEthBalanceInUnitAmount: ethBalanceInUnitAmount }); - analytics.addEventProperties({ ethBalanceInUnitAmount }); - } - break; - case ActionTypes.UpdateSelectedAsset: - const selectedAsset = curState.selectedAsset; - if (selectedAsset) { - const assetName = selectedAsset.metaData.name; - const assetData = selectedAsset.assetData; - analytics.trackTokenSelectorChose({ - assetName, - assetData, - }); - - const selectedAssetEventProperties: AnalyticsEventOptions = { - selectedAssetName: assetName, - selectedAssetData: assetData, - }; - if (selectedAsset.metaData.assetProxyId === AssetProxyId.ERC20) { - selectedAssetEventProperties.selectedAssetDecimals = selectedAsset.metaData.decimals; - selectedAssetEventProperties.selectedAssetSymbol = selectedAsset.metaData.symbol; - } - analytics.addEventProperties(selectedAssetEventProperties); - } - break; - case ActionTypes.SetAvailableAssets: - const availableAssets = curState.availableAssets; - if (availableAssets) { - analytics.addEventProperties({ - numberAvailableAssets: availableAssets.length, - }); - } - break; - case ActionTypes.OpenStandardSlidingPanel: - const openSlidingContent = curState.standardSlidingPanelSettings.content; - if (openSlidingContent === StandardSlidingPanelContent.InstallWallet) { - analytics.trackInstallWalletModalOpened(); - } - break; - case ActionTypes.CloseStandardSlidingPanel: - const closeSlidingContent = curState.standardSlidingPanelSettings.content; - if (closeSlidingContent === StandardSlidingPanelContent.InstallWallet) { - analytics.trackInstallWalletModalClosed(); - } - break; - case ActionTypes.UpdateBaseCurrency: - analytics.trackBaseCurrencyChanged(curState.baseCurrency); - analytics.addEventProperties({ baseCurrency: curState.baseCurrency }); - } - - return nextAction; -}; diff --git a/packages/instant/src/redux/async_data.ts b/packages/instant/src/redux/async_data.ts deleted file mode 100644 index 70ee768ae2..0000000000 --- a/packages/instant/src/redux/async_data.ts +++ /dev/null @@ -1,144 +0,0 @@ -import { Web3Wrapper } from '@0x/web3-wrapper'; -import * as _ from 'lodash'; -import { Dispatch } from 'redux'; - -import { BIG_NUMBER_ZERO, SUPPORTED_TOKEN_ASSET_DATA_WITH_BRIDGE_ORDERS } from '../constants'; -import { AccountState, BaseCurrency, OrderProcessState, ProviderState, QuoteFetchOrigin } from '../types'; -import { analytics } from '../util/analytics'; -import { assetUtils } from '../util/asset'; -import { coinbaseApi } from '../util/coinbase_api'; -import { errorFlasher } from '../util/error_flasher'; -import { errorReporter } from '../util/error_reporter'; -import { providerStateFactory } from '../util/provider_state_factory'; -import { swapQuoteUpdater } from '../util/swap_quote_updater'; - -import { actions } from './actions'; -import { State } from './reducer'; - -export const asyncData = { - fetchEthPriceAndDispatchToStore: async (dispatch: Dispatch) => { - try { - const ethUsdPrice = await coinbaseApi.getEthUsdPrice(); - dispatch(actions.updateEthUsdPrice(ethUsdPrice)); - } catch (e) { - const errorMessage = 'Error fetching ETH/USD price'; - errorFlasher.flashNewErrorMessage(dispatch, errorMessage); - dispatch(actions.updateEthUsdPrice(BIG_NUMBER_ZERO)); - dispatch(actions.updateBaseCurrency(BaseCurrency.ETH)); - errorReporter.report(e); - analytics.trackUsdPriceFailed(); - } - }, - fetchAvailableAssetDatasAndDispatchToStore: async (state: State, dispatch: Dispatch) => { - const { providerState, assetMetaDataMap, network } = state; - const swapQuoter = providerState.swapQuoter; - try { - const wethAssetData = await swapQuoter.getEtherTokenAssetDataOrThrowAsync(); - const assetDatas = await swapQuoter.getAvailableMakerAssetDatasAsync(wethAssetData); - const deduplicatedAssetDatas = _.uniq(assetDatas); - const assetsWithNativeOrders = assetUtils.createAssetsFromAssetDatas( - deduplicatedAssetDatas, - assetMetaDataMap, - network, - ); - const assetsWithBridgeOrders = assetUtils.createAssetsFromAssetDatas( - SUPPORTED_TOKEN_ASSET_DATA_WITH_BRIDGE_ORDERS, - assetMetaDataMap, - network, - ); - const assets = _.uniqBy(_.concat(assetsWithNativeOrders, assetsWithBridgeOrders), asset => asset.assetData); - dispatch(actions.setAvailableAssets(assets)); - } catch (e) { - const errorMessage = 'Could not find any assets'; - errorFlasher.flashNewErrorMessage(dispatch, errorMessage); - // On error, just specify that none are available - dispatch(actions.setAvailableAssets([])); - errorReporter.report(e); - } - }, - fetchAccountInfoAndDispatchToStore: async ( - providerState: ProviderState, - dispatch: Dispatch, - shouldAttemptUnlock: boolean = false, - ) => { - const web3Wrapper = providerState.web3Wrapper; - const provider = providerState.provider; - let availableAddresses: string[] = []; - if (shouldAttemptUnlock && providerState.account.state !== AccountState.Loading) { - dispatch(actions.setAccountStateLoading()); - } - try { - // HACK: Fortmatic's getAvailableAddressesAsync behaves in ways that default wallet behavior can't handle - if ((provider as any).isFortmatic) { - availableAddresses = - (provider as any).isLoggedIn || shouldAttemptUnlock - ? await web3Wrapper.getAvailableAddressesAsync() - : []; - } else { - // TODO(bmillman): Add support at the web3Wrapper level for calling `eth_requestAccounts` instead of calling enable here - const isPrivacyModeEnabled = (provider as any).enable !== undefined; - availableAddresses = - isPrivacyModeEnabled && shouldAttemptUnlock - ? await (provider as any).enable() - : await web3Wrapper.getAvailableAddressesAsync(); - } - } catch (e) { - analytics.trackAccountUnlockDenied(); - if (e.message.includes('Fortmatic: User denied account access.')) { - // If Fortmatic is not used, revert to injected provider - const initialProviderState = providerStateFactory.getInitialProviderStateWithCurrentProviderState( - providerState, - ); - dispatch(actions.setProviderState(initialProviderState)); - } else { - dispatch(actions.setAccountStateLocked()); - } - return; - } - if (!_.isEmpty(availableAddresses)) { - const activeAddress = availableAddresses[0]; - dispatch(actions.setAccountStateReady(activeAddress)); - // tslint:disable-next-line:no-floating-promises - asyncData.fetchAccountBalanceAndDispatchToStore(activeAddress, providerState.web3Wrapper, dispatch); - } else if (providerState.account.state !== AccountState.Loading) { - dispatch(actions.setAccountStateLocked()); - } - }, - fetchAccountBalanceAndDispatchToStore: async (address: string, web3Wrapper: Web3Wrapper, dispatch: Dispatch) => { - try { - const ethBalanceInWei = await web3Wrapper.getBalanceInWeiAsync(address); - dispatch(actions.updateAccountEthBalance({ address, ethBalanceInWei })); - } catch (e) { - errorReporter.report(e); - // leave balance as is - return; - } - }, - fetchCurrentSwapQuoteAndDispatchToStore: async ( - state: State, - dispatch: Dispatch, - fetchOrigin: QuoteFetchOrigin, - options: { updateSilently: boolean }, - ) => { - const { swapOrderState, providerState, selectedAsset, selectedAssetUnitAmount } = state; - const swapQuoter = providerState.swapQuoter; - if ( - selectedAssetUnitAmount !== undefined && - selectedAsset !== undefined && - selectedAssetUnitAmount.isGreaterThan(BIG_NUMBER_ZERO) && - swapOrderState.processState === OrderProcessState.None - ) { - await swapQuoteUpdater.updateSwapQuoteAsync( - swapQuoter, - dispatch, - selectedAsset, - selectedAssetUnitAmount, - fetchOrigin, - { - setPending: !options.updateSilently, - dispatchErrors: !options.updateSilently, - }, - ); - } - }, -}; diff --git a/packages/instant/src/redux/reducer.ts b/packages/instant/src/redux/reducer.ts deleted file mode 100644 index 343c4e6707..0000000000 --- a/packages/instant/src/redux/reducer.ts +++ /dev/null @@ -1,305 +0,0 @@ -import { MarketBuySwapQuote } from '@0x/asset-swapper'; -import { AssetProxyId, ObjectMap } from '@0x/types'; -import { BigNumber } from '@0x/utils'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import * as _ from 'lodash'; - -import { LOADING_ACCOUNT, LOCKED_ACCOUNT, NO_ACCOUNT } from '../constants'; -import { assetMetaDataMap } from '../data/asset_meta_data_map'; -import { - Account, - AccountReady, - AccountState, - AffiliateInfo, - Asset, - AssetMetaData, - AsyncProcessState, - BaseCurrency, - DisplayStatus, - Network, - OrderProcessState, - OrderState, - ProviderState, - StandardSlidingPanelContent, - StandardSlidingPanelSettings, -} from '../types'; - -import { Action, ActionTypes } from './actions'; - -// State that is required and we have defaults for, before props are passed in -export interface DefaultState { - network: Network; - assetMetaDataMap: ObjectMap; - swapOrderState: OrderState; - latestErrorDisplayStatus: DisplayStatus; - quoteRequestState: AsyncProcessState; - standardSlidingPanelSettings: StandardSlidingPanelSettings; - baseCurrency: BaseCurrency; -} - -// State that is required but needs to be derived from the props -interface PropsDerivedState { - providerState: ProviderState; -} - -// State that is optional -interface OptionalState { - selectedAsset: Asset; - availableAssets: Asset[]; - selectedAssetUnitAmount: BigNumber; - ethUsdPrice: BigNumber; - latestSwapQuote: MarketBuySwapQuote; - latestErrorMessage: string; - affiliateInfo: AffiliateInfo; - walletDisplayName: string; - onSuccess: (txHash: string) => void; -} - -export type State = DefaultState & PropsDerivedState & Partial; - -export const DEFAULT_STATE: DefaultState = { - network: Network.Mainnet, - assetMetaDataMap, - swapOrderState: { processState: OrderProcessState.None }, - latestErrorDisplayStatus: DisplayStatus.Hidden, - quoteRequestState: AsyncProcessState.None, - standardSlidingPanelSettings: { - animationState: 'none', - content: StandardSlidingPanelContent.None, - }, - baseCurrency: BaseCurrency.USD, -}; - -export const createReducer = (initialState: State) => { - const reducer = (state: State = initialState, action: Action): State => { - switch (action.type) { - case ActionTypes.SetAccountStateLoading: - return reduceStateWithAccount(state, LOADING_ACCOUNT); - case ActionTypes.SetAccountStateLocked: - return reduceStateWithAccount(state, LOCKED_ACCOUNT); - case ActionTypes.SetAccountStateNone: - return reduceStateWithAccount(state, NO_ACCOUNT); - case ActionTypes.SetAccountStateReady: { - const address = action.data; - let newAccount: AccountReady = { - state: AccountState.Ready, - address, - }; - const currentAccount = state.providerState.account; - if (currentAccount.state === AccountState.Ready && currentAccount.address === address) { - newAccount = { - ...newAccount, - ethBalanceInWei: currentAccount.ethBalanceInWei, - }; - } - return reduceStateWithAccount(state, newAccount); - } - case ActionTypes.UpdateAccountEthBalance: { - const { address, ethBalanceInWei } = action.data; - const currentAccount = state.providerState.account; - if (currentAccount.state !== AccountState.Ready || currentAccount.address !== address) { - return state; - } else { - const newAccount: AccountReady = { - ...currentAccount, - ethBalanceInWei, - }; - return reduceStateWithAccount(state, newAccount); - } - } - case ActionTypes.UpdateEthUsdPrice: - return { - ...state, - ethUsdPrice: action.data, - }; - case ActionTypes.UpdateSelectedAssetUnitAmount: - return { - ...state, - selectedAssetUnitAmount: action.data, - }; - case ActionTypes.UpdateLatestSwapQuote: - const newSwapQuoteIfExists = action.data; - const shouldUpdate = - newSwapQuoteIfExists === undefined || doesSwapQuoteMatchState(newSwapQuoteIfExists, state); - if (shouldUpdate) { - return { - ...state, - latestSwapQuote: newSwapQuoteIfExists, - quoteRequestState: AsyncProcessState.Success, - }; - } else { - return state; - } - case ActionTypes.SetQuoteRequestStatePending: - return { - ...state, - latestSwapQuote: undefined, - quoteRequestState: AsyncProcessState.Pending, - }; - case ActionTypes.SetQuoteRequestStateFailure: - return { - ...state, - latestSwapQuote: undefined, - quoteRequestState: AsyncProcessState.Failure, - }; - case ActionTypes.SetSwapOrderStateNone: - return { - ...state, - swapOrderState: { processState: OrderProcessState.None }, - }; - case ActionTypes.SetSwapOrderStateValidating: - return { - ...state, - swapOrderState: { processState: OrderProcessState.Validating }, - }; - case ActionTypes.SetSwapOrderStateProcessing: - const processingData = action.data; - const { startTimeUnix, expectedEndTimeUnix } = processingData; - return { - ...state, - swapOrderState: { - processState: OrderProcessState.Processing, - txHash: processingData.txHash, - progress: { - startTimeUnix, - expectedEndTimeUnix, - }, - }, - }; - case ActionTypes.SetSwapOrderStateFailure: - const failureTxHash = action.data; - if ('txHash' in state.swapOrderState) { - if (state.swapOrderState.txHash === failureTxHash) { - const { txHash, progress } = state.swapOrderState; - return { - ...state, - swapOrderState: { - processState: OrderProcessState.Failure, - txHash, - progress, - }, - }; - } - } - return state; - case ActionTypes.SetSwapOrderStateSuccess: - const successTxHash = action.data; - if ('txHash' in state.swapOrderState) { - if (state.swapOrderState.txHash === successTxHash) { - const { txHash, progress } = state.swapOrderState; - return { - ...state, - swapOrderState: { - processState: OrderProcessState.Success, - txHash, - progress, - }, - }; - } - } - return state; - case ActionTypes.SetErrorMessage: - return { - ...state, - latestErrorMessage: action.data, - latestErrorDisplayStatus: DisplayStatus.Present, - }; - case ActionTypes.HideError: - return { - ...state, - latestErrorDisplayStatus: DisplayStatus.Hidden, - }; - case ActionTypes.ClearError: - return { - ...state, - latestErrorMessage: undefined, - latestErrorDisplayStatus: DisplayStatus.Hidden, - }; - case ActionTypes.UpdateSelectedAsset: - return { - ...state, - selectedAsset: action.data, - }; - case ActionTypes.ResetAmount: - return { - ...state, - latestSwapQuote: undefined, - quoteRequestState: AsyncProcessState.None, - swapOrderState: { processState: OrderProcessState.None }, - selectedAssetUnitAmount: undefined, - }; - case ActionTypes.SetAvailableAssets: - return { - ...state, - availableAssets: action.data, - }; - case ActionTypes.OpenStandardSlidingPanel: - return { - ...state, - standardSlidingPanelSettings: { - content: action.data, - animationState: 'slidIn', - }, - }; - case ActionTypes.CloseStandardSlidingPanel: - return { - ...state, - standardSlidingPanelSettings: { - content: state.standardSlidingPanelSettings.content, - animationState: 'slidOut', - }, - }; - case ActionTypes.UpdateBaseCurrency: - return { - ...state, - baseCurrency: action.data, - }; - case ActionTypes.SetProviderState: - return { - ...state, - providerState: action.data, - }; - default: - return state; - } - }; - return reducer; -}; - -const reduceStateWithAccount = (state: State, account: Account) => { - const oldProviderState = state.providerState; - const newProviderState: ProviderState = { - ...oldProviderState, - account, - }; - return { - ...state, - providerState: newProviderState, - }; -}; - -const doesSwapQuoteMatchState = (swapQuote: MarketBuySwapQuote, state: State): boolean => { - const selectedAssetIfExists = state.selectedAsset; - const selectedAssetUnitAmountIfExists = state.selectedAssetUnitAmount; - // if no selectedAsset or selectedAssetAmount exists on the current state, return false - if (selectedAssetIfExists === undefined || selectedAssetUnitAmountIfExists === undefined) { - return false; - } - // if swapQuote's assetData does not match that of the current selected asset, return false - if (selectedAssetIfExists.assetData !== swapQuote.makerAssetData) { - return false; - } - // if ERC20 and swapQuote's makerAssetFillAmount does not match selectedAssetAmount, return false - // if ERC721, return true - const selectedAssetMetaData = selectedAssetIfExists.metaData; - if (selectedAssetMetaData.assetProxyId === AssetProxyId.ERC20) { - const selectedAssetAmountBaseUnits = Web3Wrapper.toBaseUnitAmount( - selectedAssetUnitAmountIfExists, - selectedAssetMetaData.decimals, - ); - const doesAssetAmountMatch = selectedAssetAmountBaseUnits.eq(swapQuote.makerAssetFillAmount); - return doesAssetAmountMatch; - } else { - return true; - } -}; diff --git a/packages/instant/src/redux/store.ts b/packages/instant/src/redux/store.ts deleted file mode 100644 index 11bba3876e..0000000000 --- a/packages/instant/src/redux/store.ts +++ /dev/null @@ -1,15 +0,0 @@ -import * as _ from 'lodash'; -import { applyMiddleware, createStore, Store as ReduxStore } from 'redux'; -import { composeWithDevTools } from 'redux-devtools-extension/developmentOnly'; - -import { analyticsMiddleware } from './analytics_middleware'; -import { createReducer, State } from './reducer'; - -export type Store = ReduxStore; - -export const store = { - create: (initialState: State): Store => { - const reducer = createReducer(initialState); - return createStore(reducer, initialState, composeWithDevTools(applyMiddleware(analyticsMiddleware))); - }, -}; diff --git a/packages/instant/src/style/fonts.ts b/packages/instant/src/style/fonts.ts deleted file mode 100644 index 92450502d2..0000000000 --- a/packages/instant/src/style/fonts.ts +++ /dev/null @@ -1,10 +0,0 @@ -export const fonts = { - include: () => { - // Inject the inter-ui font into the page - const appendTo = document.head || document.getElementsByTagName('head')[0] || document.body; - const style = document.createElement('style'); - style.type = 'text/css'; - style.appendChild(document.createTextNode(`@import url('https://rsms.me/inter/inter-ui.css')`)); - appendTo.appendChild(style); - }, -}; diff --git a/packages/instant/src/style/media.ts b/packages/instant/src/style/media.ts deleted file mode 100644 index 450de28faa..0000000000 --- a/packages/instant/src/style/media.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { InterpolationValue } from 'styled-components'; - -import { css } from './theme'; - -export enum ScreenWidths { - Sm = 40, - Md = 52, - Lg = 64, -} - -export const generateMediaWrapper = (screenWidth: ScreenWidths) => (...args: any[]) => css` - @media (max-width: ${screenWidth}em) { - ${css.apply(css, args)}; - } -`; - -export const media = { - small: generateMediaWrapper(ScreenWidths.Sm), - medium: generateMediaWrapper(ScreenWidths.Md), - large: generateMediaWrapper(ScreenWidths.Lg), -}; - -export interface ScreenSpecification { - default: T; - sm?: T; - md?: T; - lg?: T; -} -export type OptionallyScreenSpecific = T | ScreenSpecification; -export type MediaChoice = OptionallyScreenSpecific; -/** - * Given a css property name and a OptionallyScreenSpecific value, - * generates css properties with screen-specific viewport styling - */ -export function stylesForMedia( - cssPropertyName: string, - choice: OptionallyScreenSpecific, -): InterpolationValue { - if (typeof choice === 'object') { - return ` - ${cssPropertyName}: ${choice.default}; - ${choice.lg && media.large`${cssPropertyName}: ${choice.lg}`} - ${choice.md && media.medium`${cssPropertyName}: ${choice.md}`} - ${choice.sm && media.small`${cssPropertyName}: ${choice.sm}`} - `; - } else { - return ` - ${cssPropertyName}: ${choice}; - `; - } -} diff --git a/packages/instant/src/style/theme.ts b/packages/instant/src/style/theme.ts deleted file mode 100644 index 04043f3596..0000000000 --- a/packages/instant/src/style/theme.ts +++ /dev/null @@ -1,58 +0,0 @@ -import * as styledComponents from 'styled-components'; - -const { - default: styled, - css, - keyframes, - withTheme, - createGlobalStyle, - ThemeConsumer, - ThemeProvider, -} = styledComponents; - -export type Theme = { [key in ColorOption]: string }; -// tslint:disable:enum-naming -export enum ColorOption { - primaryColor = 'primaryColor', - black = 'black', - lightGrey = 'lightGrey', - grey = 'grey', - feintGrey = 'feintGrey', - lightestGrey = 'lightestGrey', - darkGrey = 'darkGrey', - white = 'white', - lightOrange = 'lightOrange', - darkOrange = 'darkOrange', - green = 'green', - red = 'red', - darkBlue = 'darkBlue', - lightBlue = 'lightBlue', - whiteBackground = 'whiteBackground', -} - -export const theme: Theme = { - primaryColor: '#333', - black: 'black', - lightGrey: '#999999', - grey: '#666666', - feintGrey: '#DEDEDE', - lightestGrey: '#EEEEEE', - darkGrey: '#333333', - white: 'white', - lightOrange: '#FFF8F2', - darkOrange: '#F7A24F', - green: '#3CB34F', - red: '#D00000', - darkBlue: '#135df6', - lightBlue: '#F2F7FF', - whiteBackground: '#FFFFFF', -}; - -export const transparentWhite = 'rgba(255,255,255,0.3)'; -export const completelyTransparent = 'rga(0, 0, 0, 0)'; - -export const generateOverlayBlack = (opacity = 0.6) => { - return `rgba(0, 0, 0, ${opacity})`; -}; - -export { styled, css, keyframes, withTheme, createGlobalStyle, ThemeConsumer, ThemeProvider }; diff --git a/packages/instant/src/style/util.ts b/packages/instant/src/style/util.ts deleted file mode 100644 index ed03d73246..0000000000 --- a/packages/instant/src/style/util.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { ObjectMap } from '@0x/types'; -import * as _ from 'lodash'; - -export const cssRuleIfExists = (props: ObjectMap, rule: string): string => { - const camelCaseRule = _.camelCase(rule); - const ruleValueIfExists = props[camelCaseRule]; - if (ruleValueIfExists !== undefined) { - return `${rule}: ${ruleValueIfExists};`; - } - return ''; -}; diff --git a/packages/instant/src/style/z_index.ts b/packages/instant/src/style/z_index.ts deleted file mode 100644 index ba2d27a17b..0000000000 --- a/packages/instant/src/style/z_index.ts +++ /dev/null @@ -1,9 +0,0 @@ -export const zIndex = { - errorPopBehind: 10, - mainContainer: 20, - dropdownItems: 30, - panel: 40, - containerOverlay: 45, - errorPopup: 50, - overlayDefault: 100, -}; diff --git a/packages/instant/src/types.ts b/packages/instant/src/types.ts deleted file mode 100644 index e1a9361a3e..0000000000 --- a/packages/instant/src/types.ts +++ /dev/null @@ -1,216 +0,0 @@ -import { BigNumber, SwapQuoteConsumer, SwapQuoter } from '@0x/asset-swapper'; -import { AssetProxyId, ObjectMap, SignedOrder } from '@0x/types'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import { SupportedProvider, ZeroExProvider } from 'ethereum-types'; - -// Reusable -export type Omit = Pick>; -export type Maybe = T | undefined; -export enum AsyncProcessState { - None = 'NONE', - Pending = 'PENDING', - Success = 'SUCCESS', - Failure = 'FAILURE', -} - -export enum OrderProcessState { - None = 'NONE', - Validating = 'VALIDATING', - Processing = 'PROCESSING', - Success = 'SUCCESS', - Failure = 'FAILURE', -} - -export enum QuoteFetchOrigin { - Manual = 'Manual', - Heartbeat = 'Heartbeat', -} - -export enum BaseCurrency { - USD = 'USD', // tslint:disable-line:enum-naming - ETH = 'ETH', // tslint:disable-line:enum-naming -} - -export interface SimulatedProgress { - startTimeUnix: number; - expectedEndTimeUnix: number; -} - -interface OrderStatePreTx { - processState: OrderProcessState.None | OrderProcessState.Validating; -} -interface OrderStatePostTx { - processState: OrderProcessState.Processing | OrderProcessState.Success | OrderProcessState.Failure; - txHash: string; - progress: SimulatedProgress; -} -export type OrderState = OrderStatePreTx | OrderStatePostTx; - -export enum DisplayStatus { - Present, - Hidden, -} - -export type FunctionType = (...args: any[]) => any; -export type ActionCreatorsMapObject = ObjectMap; -export type ActionsUnion = ReturnType; - -export interface ERC20AssetMetaData { - assetProxyId: AssetProxyId.ERC20; - decimals: number; - primaryColor?: string; - symbol: string; - name: string; - iconUrl?: string; -} - -export interface ERC721AssetMetaData { - assetProxyId: AssetProxyId.ERC721; - name: string; - imageUrl?: string; - primaryColor?: string; -} - -export type AssetMetaData = ERC20AssetMetaData | ERC721AssetMetaData; - -export interface ERC20Asset { - assetData: string; - metaData: ERC20AssetMetaData; -} - -export interface ERC721Asset { - assetData: string; - metaData: ERC721AssetMetaData; -} - -export interface Asset { - assetData: string; - metaData: AssetMetaData; -} - -export enum Network { - Kovan = 42, - Mainnet = 1, -} - -export enum ZeroExInstantError { - AssetMetaDataNotAvailable = 'ASSET_META_DATA_NOT_AVAILABLE', - InsufficientETH = 'INSUFFICIENT_ETH', // tslint:disable-line:enum-naming - CouldNotSubmitTransaction = 'COULD_NOT_SUBMIT_TRANSACTION', -} - -export type SimpleHandler = () => void; - -export interface AffiliateInfo { - feeRecipient: string; - feePercentage: number; -} - -export interface ProviderState { - name: string; - displayName: string; - provider: ZeroExProvider; - swapQuoter: SwapQuoter; - swapQuoteConsumer: SwapQuoteConsumer; - web3Wrapper: Web3Wrapper; - account: Account; - orderSource: OrderSource; - isProviderInjected: boolean; -} - -export enum AccountState { - None = 'NONE', - Loading = 'LOADING', - Ready = 'READY', - Locked = 'LOCKED', -} - -export interface AccountReady { - state: AccountState.Ready; - address: string; - ethBalanceInWei?: BigNumber; -} -export interface AccountNotReady { - state: AccountState.None | AccountState.Loading | AccountState.Locked; -} - -export type Account = AccountReady | AccountNotReady; - -export type OrderSource = string | SignedOrder[]; - -export interface AddressAndEthBalanceInWei { - address: string; - ethBalanceInWei: BigNumber; -} - -export type SlideAnimationState = 'slidIn' | 'slidOut' | 'none'; - -export enum StandardSlidingPanelContent { - None = 'NONE', - InstallWallet = 'INSTALL_WALLET', -} - -export interface StandardSlidingPanelSettings { - animationState: SlideAnimationState; - content: StandardSlidingPanelContent; -} - -export enum Browser { - Chrome = 'CHROME', - Firefox = 'FIREFOX', - Opera = 'OPERA', - Safari = 'SAFARI', - Edge = 'EDGE', - Other = 'OTHER', -} - -export enum WalletSuggestion { - CoinbaseWallet = 'Coinbase Wallet', - MetaMask = 'MetaMask', -} - -export enum OperatingSystem { - Android = 'ANDROID', - iOS = 'IOS', // tslint:disable-line:enum-naming - Mac = 'MAC', - Windows = 'WINDOWS', - WindowsPhone = 'WINDOWS_PHONE', - Linux = 'LINUX', - Other = 'OTHER', -} - -export enum ProviderType { - Parity = 'PARITY', - MetaMask = 'META_MASK', - Mist = 'MIST', - CoinbaseWallet = 'COINBASE_WALLET', - Cipher = 'CIPHER', - TrustWallet = 'TRUST_WALLET', - Opera = 'OPERA', - Fortmatic = 'Fortmatic', - Fallback = 'FALLBACK', -} - -export interface ZeroExInstantRequiredBaseConfig { - orderSource: OrderSource; -} - -export interface AffiliateInfo { - feeRecipient: string; - feePercentage: number; -} - -export interface ZeroExInstantOptionalBaseConfig { - provider: SupportedProvider; - walletDisplayName: string; - availableAssetDatas: string[]; - defaultAssetBuyAmount: number; - defaultSelectedAssetData: string; - additionalAssetMetaDataMap: ObjectMap; - networkId: Network; - affiliateInfo: AffiliateInfo; - shouldDisableAnalyticsTracking: boolean; - onSuccess?: (txHash: string) => void; -} - -export type ZeroExInstantBaseConfig = ZeroExInstantRequiredBaseConfig & Partial; diff --git a/packages/instant/src/util/address.ts b/packages/instant/src/util/address.ts deleted file mode 100644 index b21863a8e0..0000000000 --- a/packages/instant/src/util/address.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { Web3Wrapper } from '@0x/web3-wrapper'; - -export const getBestAddress = async (web3Wrapper: Web3Wrapper): Promise => { - const addresses = await web3Wrapper.getAvailableAddressesAsync(); - return addresses[0]; -}; diff --git a/packages/instant/src/util/analytics.ts b/packages/instant/src/util/analytics.ts deleted file mode 100644 index c0fb1e70b4..0000000000 --- a/packages/instant/src/util/analytics.ts +++ /dev/null @@ -1,264 +0,0 @@ -import { MarketBuySwapQuote } from '@0x/asset-swapper'; -import { BigNumber } from '@0x/utils'; -import * as _ from 'lodash'; - -import { GIT_SHA, HEAP_ENABLED, INSTANT_DISCHARGE_TARGET, NODE_ENV, NPM_PACKAGE_VERSION } from '../constants'; -import { - AffiliateInfo, - Asset, - BaseCurrency, - Network, - OrderProcessState, - OrderSource, - ProviderState, - QuoteFetchOrigin, - WalletSuggestion, -} from '../types'; - -import { EventProperties, heapUtil } from './heap'; - -let isDisabledViaConfig = false; -export const disableAnalytics = (shouldDisableAnalytics: boolean) => { - isDisabledViaConfig = shouldDisableAnalytics; -}; -export const evaluateIfEnabled = (fnCall: () => void) => { - if (isDisabledViaConfig) { - return; - } - if (HEAP_ENABLED) { - fnCall(); - } -}; - -enum EventNames { - InstantOpened = 'Instant - Opened', - InstantClosed = 'Instant - Closed', - AccountLocked = 'Account - Locked', - AccountReady = 'Account - Ready', - AccountUnlockRequested = 'Account - Unlock Requested', - AccountUnlockDenied = 'Account - Unlock Denied', - AccountAddressChanged = 'Account - Address Changed', - BaseCurrencyChanged = 'Base Currency - Changed', - PaymentMethodDropdownOpened = 'Payment Method - Dropdown Opened', - PaymentMethodOpenedEtherscan = 'Payment Method - Opened Etherscan', - PaymentMethodCopiedAddress = 'Payment Method - Copied Address', - BuyNotEnoughEth = 'Buy - Not Enough Eth', - BuyStarted = 'Buy - Started', - BuySignatureDenied = 'Buy - Signature Denied', - BuySimulationFailed = 'Buy - Simulation Failed', - BuyUnknownError = 'Buy - Unknown Error', - BuyTxSubmitted = 'Buy - Tx Submitted', - BuyTxSucceeded = 'Buy - Tx Succeeded', - BuyTxFailed = 'Buy - Tx Failed', - UsdPriceFetchFailed = 'USD Price - Fetch Failed', - InstallWalletClicked = 'Install Wallet - Clicked', - InstallWalletModalOpened = 'Install Wallet - Modal - Opened', - InstallWalletModalClickedExplanation = 'Install Wallet - Modal - Clicked Explanation', - InstallWalletModalClickedGet = 'Install Wallet - Modal - Clicked Get', - InstallWalletModalClosed = 'Install Wallet - Modal - Closed', - TokenSelectorOpened = 'Token Selector - Opened', - TokenSelectorClosed = 'Token Selector - Closed', - TokenSelectorChose = 'Token Selector - Chose', - TokenSelectorSearched = 'Token Selector - Searched', - TransactionViewed = 'Transaction - Viewed', - QuoteFetched = 'Quote - Fetched', - QuoteError = 'Quote - Error', -} - -const track = (eventName: EventNames, eventProperties: EventProperties = {}): void => { - evaluateIfEnabled(() => { - heapUtil.evaluateHeapCall(heap => heap.track(eventName, eventProperties)); - }); -}; -function trackingEventFnWithoutPayload(eventName: EventNames): () => void { - return () => { - track(eventName); - }; -} -// tslint:disable-next-line:no-unused-variable -function trackingEventFnWithPayload(eventName: EventNames): (eventProperties: EventProperties) => void { - return (eventProperties: EventProperties) => { - track(eventName, eventProperties); - }; -} - -const swapQuoteEventProperties = (swapQuote: MarketBuySwapQuote) => { - const makerAssetFillAmount = swapQuote.makerAssetFillAmount.toString(); - const assetEthAmount = swapQuote.worstCaseQuoteInfo.takerAssetAmount.toString(); - const feeEthAmount = swapQuote.worstCaseQuoteInfo.protocolFeeInWeiAmount - .plus(swapQuote.worstCaseQuoteInfo.feeTakerAssetAmount) - .toString(); - const totalEthAmount = swapQuote.worstCaseQuoteInfo.totalTakerAssetAmount - .plus(swapQuote.worstCaseQuoteInfo.protocolFeeInWeiAmount) - .toString(); - return { - makerAssetFillAmount, - assetEthAmount, - feeEthAmount, - totalEthAmount, - gasPrice: swapQuote.gasPrice.toString(), - }; -}; - -export interface AnalyticsUserOptions { - lastKnownEthAddress?: string; - lastEthBalanceInUnitAmount?: string; -} -export interface AnalyticsEventOptions { - embeddedHost?: string; - embeddedUrl?: string; - ethBalanceInUnitAmount?: string; - ethAddress?: string; - networkId?: number; - providerName?: string; - providerDisplayName?: string; - gitSha?: string; - npmVersion?: string; - instantEnvironment?: string; - orderSource?: string; - affiliateAddress?: string; - affiliateFeePercent?: number; - numberAvailableAssets?: number; - selectedAssetName?: string; - selectedAssetSymbol?: string; - selectedAssetData?: string; - selectedAssetDecimals?: number; - baseCurrency?: string; -} -export enum TokenSelectorClosedVia { - ClickedX = 'Clicked X', // tslint:disable-line:enum-naming - TokenChose = 'Token Chose', -} -export const analytics = { - addUserProperties: (properties: AnalyticsUserOptions): void => { - evaluateIfEnabled(() => { - heapUtil.evaluateHeapCall(heap => heap.addUserProperties(properties)); - }); - }, - addEventProperties: (properties: AnalyticsEventOptions): void => { - evaluateIfEnabled(() => { - heapUtil.evaluateHeapCall(heap => heap.addEventProperties(properties)); - }); - }, - generateEventProperties: ( - network: Network, - orderSource: OrderSource, - providerState: ProviderState, - window: Window, - selectedAsset?: Asset, - affiliateInfo?: AffiliateInfo, - baseCurrency?: BaseCurrency, - ): AnalyticsEventOptions => { - const affiliateAddress = affiliateInfo ? affiliateInfo.feeRecipient : 'none'; - const affiliateFeePercent = affiliateInfo ? parseFloat(affiliateInfo.feePercentage.toFixed(4)) : 0; - const orderSourceName = typeof orderSource === 'string' ? orderSource : 'provided'; - const eventOptions: AnalyticsEventOptions = { - embeddedHost: window.location.host, - embeddedUrl: window.location.href, - networkId: network, - providerName: providerState.name, - providerDisplayName: providerState.displayName, - gitSha: GIT_SHA, - npmVersion: NPM_PACKAGE_VERSION, - orderSource: orderSourceName, - affiliateAddress, - affiliateFeePercent, - selectedAssetName: selectedAsset ? selectedAsset.metaData.name : 'none', - selectedAssetData: selectedAsset ? selectedAsset.assetData : 'none', - instantEnvironment: INSTANT_DISCHARGE_TARGET || `Local ${NODE_ENV}`, - baseCurrency, - }; - return eventOptions; - }, - trackInstantOpened: trackingEventFnWithoutPayload(EventNames.InstantOpened), - trackInstantClosed: trackingEventFnWithoutPayload(EventNames.InstantClosed), - trackAccountLocked: trackingEventFnWithoutPayload(EventNames.AccountLocked), - trackAccountReady: (address: string) => trackingEventFnWithPayload(EventNames.AccountReady)({ address }), - trackAccountUnlockRequested: trackingEventFnWithoutPayload(EventNames.AccountUnlockRequested), - trackAccountUnlockDenied: trackingEventFnWithoutPayload(EventNames.AccountUnlockDenied), - trackAccountAddressChanged: (address: string) => - trackingEventFnWithPayload(EventNames.AccountAddressChanged)({ address }), - trackBaseCurrencyChanged: (currencyChangedTo: BaseCurrency) => - trackingEventFnWithPayload(EventNames.BaseCurrencyChanged)({ currencyChangedTo }), - trackPaymentMethodDropdownOpened: trackingEventFnWithoutPayload(EventNames.PaymentMethodDropdownOpened), - trackPaymentMethodOpenedEtherscan: trackingEventFnWithoutPayload(EventNames.PaymentMethodOpenedEtherscan), - trackPaymentMethodCopiedAddress: trackingEventFnWithoutPayload(EventNames.PaymentMethodCopiedAddress), - trackBuyNotEnoughEth: (swapQuote: MarketBuySwapQuote) => - trackingEventFnWithPayload(EventNames.BuyNotEnoughEth)(swapQuoteEventProperties(swapQuote)), - trackBuyStarted: (swapQuote: MarketBuySwapQuote) => - trackingEventFnWithPayload(EventNames.BuyStarted)(swapQuoteEventProperties(swapQuote)), - trackBuySignatureDenied: (swapQuote: MarketBuySwapQuote) => - trackingEventFnWithPayload(EventNames.BuySignatureDenied)(swapQuoteEventProperties(swapQuote)), - trackBuySimulationFailed: (swapQuote: MarketBuySwapQuote) => - trackingEventFnWithPayload(EventNames.BuySimulationFailed)(swapQuoteEventProperties(swapQuote)), - trackBuyUnknownError: (swapQuote: MarketBuySwapQuote, errorMessage: string) => - trackingEventFnWithPayload(EventNames.BuyUnknownError)({ - ...swapQuoteEventProperties(swapQuote), - errorMessage, - }), - trackBuyTxSubmitted: ( - swapQuote: MarketBuySwapQuote, - txHash: string, - startTimeUnix: number, - expectedEndTimeUnix: number, - ) => - trackingEventFnWithPayload(EventNames.BuyTxSubmitted)({ - ...swapQuoteEventProperties(swapQuote), - txHash, - expectedTxTimeMs: expectedEndTimeUnix - startTimeUnix, - }), - trackBuyTxSucceeded: ( - swapQuote: MarketBuySwapQuote, - txHash: string, - startTimeUnix: number, - expectedEndTimeUnix: number, - ) => - trackingEventFnWithPayload(EventNames.BuyTxSucceeded)({ - ...swapQuoteEventProperties(swapQuote), - txHash, - expectedTxTimeMs: expectedEndTimeUnix - startTimeUnix, - actualTxTimeMs: new Date().getTime() - startTimeUnix, - }), - trackBuyTxFailed: ( - swapQuote: MarketBuySwapQuote, - txHash: string, - startTimeUnix: number, - expectedEndTimeUnix: number, - ) => - trackingEventFnWithPayload(EventNames.BuyTxFailed)({ - ...swapQuoteEventProperties(swapQuote), - txHash, - expectedTxTimeMs: expectedEndTimeUnix - startTimeUnix, - actualTxTimeMs: new Date().getTime() - startTimeUnix, - }), - trackInstallWalletClicked: (walletSuggestion: WalletSuggestion) => - trackingEventFnWithPayload(EventNames.InstallWalletClicked)({ walletSuggestion }), - trackInstallWalletModalClickedExplanation: trackingEventFnWithoutPayload( - EventNames.InstallWalletModalClickedExplanation, - ), - trackInstallWalletModalClickedGet: trackingEventFnWithoutPayload(EventNames.InstallWalletModalClickedGet), - trackInstallWalletModalOpened: trackingEventFnWithoutPayload(EventNames.InstallWalletModalOpened), - trackInstallWalletModalClosed: trackingEventFnWithoutPayload(EventNames.InstallWalletModalClosed), - trackTokenSelectorOpened: trackingEventFnWithoutPayload(EventNames.TokenSelectorOpened), - trackTokenSelectorClosed: (closedVia: TokenSelectorClosedVia) => - trackingEventFnWithPayload(EventNames.TokenSelectorClosed)({ closedVia }), - trackTokenSelectorChose: (payload: { assetName: string; assetData: string }) => - trackingEventFnWithPayload(EventNames.TokenSelectorChose)(payload), - trackTokenSelectorSearched: (searchText: string) => - trackingEventFnWithPayload(EventNames.TokenSelectorSearched)({ searchText }), - trackTransactionViewed: (orderProcesState: OrderProcessState) => - trackingEventFnWithPayload(EventNames.TransactionViewed)({ orderState: orderProcesState }), - trackQuoteFetched: (swapQuote: MarketBuySwapQuote, fetchOrigin: QuoteFetchOrigin) => - trackingEventFnWithPayload(EventNames.QuoteFetched)({ - ...swapQuoteEventProperties(swapQuote), - fetchOrigin, - }), - trackQuoteError: (errorMessage: string, makerAssetFillAmount: BigNumber, fetchOrigin: QuoteFetchOrigin) => { - trackingEventFnWithPayload(EventNames.QuoteError)({ - errorMessage, - makerAssetFillAmount: makerAssetFillAmount.toString(), - fetchOrigin, - }); - }, - trackUsdPriceFailed: trackingEventFnWithoutPayload(EventNames.UsdPriceFetchFailed), -}; diff --git a/packages/instant/src/util/assert.ts b/packages/instant/src/util/assert.ts deleted file mode 100644 index f9ba7aa767..0000000000 --- a/packages/instant/src/util/assert.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { assert as sharedAssert } from '@0x/assert'; -import { schemas } from '@0x/json-schemas'; -import { AssetProxyId, ObjectMap, SignedOrder } from '@0x/types'; -import * as _ from 'lodash'; - -import { AffiliateInfo, AssetMetaData } from '../types'; - -import { decodeAssetProxyId } from './asset_data_encoder'; - -export const assert = { - ...sharedAssert, - isValidOrderSource(variableName: string, orderSource: string | SignedOrder[]): void { - if (_.isString(orderSource)) { - sharedAssert.isUri(variableName, orderSource); - return; - } - sharedAssert.doesConformToSchema(variableName, orderSource, schemas.signedOrdersSchema); - }, - areValidAssetDatas(variableName: string, assetDatas: string[]): void { - _.forEach(assetDatas, (assetData, index) => assert.isHexString(`${variableName}[${index}]`, assetData)); - }, - isValidAssetMetaDataMap(variableName: string, metaDataMap: ObjectMap): void { - _.forEach(metaDataMap, (metaData, assetData) => { - assert.isHexString(`key ${assetData} of ${variableName}`, assetData); - assert.isValidAssetMetaData(`${variableName}.${assetData}`, metaData); - const assetDataProxyId = decodeAssetProxyId(assetData); - assert.assert( - metaData.assetProxyId === assetDataProxyId, - `Expected meta data for assetData ${assetData} to have asset proxy id of ${assetDataProxyId}, but instead got ${ - metaData.assetProxyId - }`, - ); - }); - }, - isValidAssetMetaData(variableName: string, metaData: AssetMetaData): void { - assert.isHexString(`${variableName}.assetProxyId`, metaData.assetProxyId); - if (metaData.primaryColor !== undefined) { - assert.isString(`${variableName}.primaryColor`, metaData.primaryColor); - } - if (metaData.assetProxyId === AssetProxyId.ERC20) { - assert.isNumber(`${variableName}.decimals`, metaData.decimals); - assert.isString(`${variableName}.symbol`, metaData.symbol); - } else if (metaData.assetProxyId === AssetProxyId.ERC721) { - assert.isString(`${variableName}.name`, metaData.name); - assert.isUri(`${variableName}.imageUrl`, metaData.imageUrl); - } - }, - isValidAffiliateInfo(variableName: string, affiliateInfo: AffiliateInfo): void { - assert.isETHAddressHex(`${variableName}.recipientAddress`, affiliateInfo.feeRecipient); - assert.isNumber(`${variableName}.percentage`, affiliateInfo.feePercentage); - assert.assert( - affiliateInfo.feePercentage >= 0 && affiliateInfo.feePercentage <= 0.05, - `Expected ${variableName}.percentage to be between 0 and 0.05, but is ${affiliateInfo.feePercentage}`, - ); - }, -}; diff --git a/packages/instant/src/util/asset.ts b/packages/instant/src/util/asset.ts deleted file mode 100644 index 954723bcee..0000000000 --- a/packages/instant/src/util/asset.ts +++ /dev/null @@ -1,144 +0,0 @@ -import { InsufficientAssetLiquidityError, SwapQuoterError } from '@0x/asset-swapper'; -import { AssetProxyId, ObjectMap } from '@0x/types'; -import { BigNumber } from '@0x/utils'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import * as _ from 'lodash'; - -import { BIG_NUMBER_ZERO, DEFAULT_UNKOWN_ASSET_NAME } from '../constants'; -import { assetDataNetworkMapping } from '../data/asset_data_network_mapping'; -import { Asset, AssetMetaData, ERC20Asset, Network, ZeroExInstantError } from '../types'; - -export const assetUtils = { - createAssetsFromAssetDatas: ( - assetDatas: string[], - assetMetaDataMap: ObjectMap, - network: Network, - ): Asset[] => { - const arrayOfAssetOrUndefined = _.map(assetDatas, assetData => - assetUtils.createAssetFromAssetDataIfExists(assetData, assetMetaDataMap, network), - ); - return _.compact(arrayOfAssetOrUndefined); - }, - createAssetFromAssetDataIfExists: ( - assetData: string, - assetMetaDataMap: ObjectMap, - network: Network, - ): Asset | undefined => { - const metaData = assetUtils.getMetaDataIfExists(assetData, assetMetaDataMap, network); - if (metaData === undefined) { - return; - } - return { - assetData: assetData.toLowerCase(), - metaData, - }; - }, - createAssetFromAssetDataOrThrow: ( - assetData: string, - assetMetaDataMap: ObjectMap, - network: Network, - ): Asset => { - return { - assetData: assetData.toLowerCase(), - metaData: assetUtils.getMetaDataOrThrow(assetData, assetMetaDataMap, network), - }; - }, - getMetaDataOrThrow: (assetData: string, metaDataMap: ObjectMap, network: Network): AssetMetaData => { - const metaDataIfExists = assetUtils.getMetaDataIfExists(assetData, metaDataMap, network); - if (metaDataIfExists === undefined) { - throw new Error(ZeroExInstantError.AssetMetaDataNotAvailable); - } - return metaDataIfExists; - }, - getMetaDataIfExists: ( - assetData: string, - metaDataMap: ObjectMap, - network: Network, - ): AssetMetaData | undefined => { - let mainnetAssetData: string | undefined = assetData; - if (network !== Network.Mainnet) { - const mainnetAssetDataIfExists = assetUtils.getAssociatedAssetDataIfExists( - assetData.toLowerCase(), - network, - ); - // Just so we don't fail in the case where we are on a non-mainnet network, - // but pass in a valid mainnet assetData. - mainnetAssetData = mainnetAssetDataIfExists || assetData; - } - if (mainnetAssetData === undefined) { - return; - } - const metaData = metaDataMap[mainnetAssetData.toLowerCase()]; - if (metaData === undefined) { - return; - } - return metaData; - }, - bestNameForAsset: (asset?: Asset, defaultName: string = DEFAULT_UNKOWN_ASSET_NAME): string => { - if (asset === undefined) { - return defaultName; - } - const metaData = asset.metaData; - switch (metaData.assetProxyId) { - case AssetProxyId.ERC20: - return metaData.symbol.toUpperCase(); - case AssetProxyId.ERC721: - return metaData.name; - } - }, - formattedSymbolForAsset: (asset?: ERC20Asset, defaultName: string = '???'): string => { - if (asset === undefined) { - return defaultName; - } - const symbol = asset.metaData.symbol; - if (symbol.length <= 5) { - return symbol; - } - return `${symbol.slice(0, 3)}…`; - }, - getAssociatedAssetDataIfExists: (assetData: string, network: Network): string | undefined => { - const assetDataGroupIfExists = _.find(assetDataNetworkMapping, value => value[network] === assetData); - if (assetDataGroupIfExists === undefined) { - return; - } - return assetDataGroupIfExists[Network.Mainnet]; - }, - getERC20AssetsFromAssets: (assets: Asset[]): ERC20Asset[] => { - const erc20sOrUndefined = _.map(assets, asset => - asset.metaData.assetProxyId === AssetProxyId.ERC20 ? (asset as ERC20Asset) : undefined, - ); - return _.compact(erc20sOrUndefined); - }, - swapQuoterErrorMessage: (asset: Asset, error: Error): string | undefined => { - if (error.message === SwapQuoterError.InsufficientAssetLiquidity) { - const assetName = assetUtils.bestNameForAsset(asset, 'of this asset'); - if ( - error instanceof InsufficientAssetLiquidityError && - error.amountAvailableToFill.isGreaterThan(BIG_NUMBER_ZERO) - ) { - const unitAmountAvailableToFill = - asset.metaData.assetProxyId === AssetProxyId.ERC20 - ? Web3Wrapper.toUnitAmount(error.amountAvailableToFill, asset.metaData.decimals) - : error.amountAvailableToFill; - const roundedUnitAmountAvailableToFill = unitAmountAvailableToFill.decimalPlaces( - 2, - BigNumber.ROUND_DOWN, - ); - - if (roundedUnitAmountAvailableToFill.isGreaterThan(BIG_NUMBER_ZERO)) { - return `There are only ${roundedUnitAmountAvailableToFill} ${assetName} available to buy`; - } - } - - return `Not enough ${assetName} available`; - } else if ( - error.message === SwapQuoterError.StandardRelayerApiError || - error.message.startsWith(SwapQuoterError.AssetUnavailable) - ) { - const assetName = assetUtils.bestNameForAsset(asset, 'This asset'); - return `${assetName} is currently unavailable`; - } - - return undefined; - }, -}; diff --git a/packages/instant/src/util/asset_data_encoder.ts b/packages/instant/src/util/asset_data_encoder.ts deleted file mode 100644 index 1a4800028b..0000000000 --- a/packages/instant/src/util/asset_data_encoder.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { IAssetDataContract } from '@0x/contract-wrappers'; -import { hexUtils, NULL_ADDRESS } from '@0x/utils'; - -const fakeProvider = { isEIP1193: true } as any; - -// instantiate once per app to be more performant -export const assetDataEncoder = new IAssetDataContract(NULL_ADDRESS, fakeProvider); - -/** - * Returns the first four bytes of a given hex string. - * Does not have any validations, so the hex string MUST - * be a valid asset data, or this function returns garbage - * without throwing errors. - * @param assetData A hex string where the first four bytes are a valid Asset Proxy Id - * - */ -export function decodeAssetProxyId(assetData: string): string { - return hexUtils.slice(assetData, 0, 4); -} diff --git a/packages/instant/src/util/asset_swapper_factory.ts b/packages/instant/src/util/asset_swapper_factory.ts deleted file mode 100644 index 806dcabaac..0000000000 --- a/packages/instant/src/util/asset_swapper_factory.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { SwapQuoteConsumer, SwapQuoter, SwapQuoterOpts } from '@0x/asset-swapper'; -import { SupportedProvider } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { Network, OrderSource } from '../types'; - -export const assetSwapperFactory = { - getSwapQuoter: (supportedProvider: SupportedProvider, orderSource: OrderSource, network: Network): SwapQuoter => { - const swapQuoterOpts: Partial = { - chainId: network, - }; - const swapQuoter = _.isString(orderSource) - ? SwapQuoter.getSwapQuoterForStandardRelayerAPIUrl(supportedProvider, orderSource, swapQuoterOpts) - : SwapQuoter.getSwapQuoterForProvidedOrders(supportedProvider, orderSource, swapQuoterOpts); - return swapQuoter; - }, - getSwapQuoteConsumer: (supportedProvider: SupportedProvider, network: Network): SwapQuoteConsumer => { - const swapQuoteConsumerOptions: Partial = { - chainId: network, - }; - return new SwapQuoteConsumer(supportedProvider, swapQuoteConsumerOptions); - }, -}; diff --git a/packages/instant/src/util/coinbase_api.ts b/packages/instant/src/util/coinbase_api.ts deleted file mode 100644 index faac8d82dc..0000000000 --- a/packages/instant/src/util/coinbase_api.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { BigNumber, fetchAsync } from '@0x/utils'; - -import { COINBASE_API_BASE_URL } from '../constants'; - -export const coinbaseApi = { - getEthUsdPrice: async (): Promise => { - const res = await fetchAsync(`${COINBASE_API_BASE_URL}/prices/ETH-USD/buy`); - const resJson = await res.json(); - return new BigNumber(resJson.data.amount); - }, -}; diff --git a/packages/instant/src/util/env.ts b/packages/instant/src/util/env.ts deleted file mode 100644 index fd5e36df22..0000000000 --- a/packages/instant/src/util/env.ts +++ /dev/null @@ -1,79 +0,0 @@ -import * as bowser from 'bowser'; -import { ZeroExProvider } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { PROVIDER_TYPE_TO_NAME } from '../constants'; -import { Browser, OperatingSystem, ProviderType } from '../types'; - -export const envUtil = { - getBrowser(): Browser { - if (bowser.chrome) { - return Browser.Chrome; - } else if (bowser.firefox) { - return Browser.Firefox; - } else if (bowser.opera) { - return Browser.Opera; - } else if (bowser.msedge) { - return Browser.Edge; - } else if (bowser.safari) { - return Browser.Safari; - } else { - return Browser.Other; - } - }, - isMobileOperatingSystem(): boolean { - return bowser.mobile; - }, - getOperatingSystem(): OperatingSystem { - if (bowser.android) { - return OperatingSystem.Android; - } else if (bowser.ios) { - return OperatingSystem.iOS; - } else if (bowser.mac) { - return OperatingSystem.Mac; - } else if (bowser.windows) { - return OperatingSystem.Windows; - } else if (bowser.windowsphone) { - return OperatingSystem.WindowsPhone; - } else if (bowser.linux) { - return OperatingSystem.Linux; - } else { - return OperatingSystem.Other; - } - }, - getProviderType(provider: ZeroExProvider): ProviderType | undefined { - const anyProvider = provider as any; - if (provider.constructor.name === 'EthereumProvider') { - return ProviderType.Mist; - } else if (anyProvider.isTrust) { - return ProviderType.TrustWallet; - } else if (anyProvider.isParity) { - return ProviderType.Parity; - } else if (anyProvider.isMetaMask) { - return ProviderType.MetaMask; - } else if (anyProvider.isFortmatic) { - return ProviderType.Fortmatic; - } else if (_.get(window, 'SOFA') !== undefined) { - return ProviderType.CoinbaseWallet; - } else if (_.get(window, '__CIPHER__') !== undefined) { - return ProviderType.Cipher; - } else if (envUtil.getBrowser() === Browser.Opera && !anyProvider.isMetaMask) { - return ProviderType.Opera; - } - return undefined; - }, - getProviderName(provider: ZeroExProvider): string { - const providerTypeIfExists = envUtil.getProviderType(provider); - if (providerTypeIfExists === undefined) { - return provider.constructor.name; - } - return PROVIDER_TYPE_TO_NAME[providerTypeIfExists]; - }, - getProviderDisplayName(provider: ZeroExProvider): string { - const providerTypeIfExists = envUtil.getProviderType(provider); - if (providerTypeIfExists === undefined) { - return 'Wallet'; - } - return PROVIDER_TYPE_TO_NAME[providerTypeIfExists]; - }, -}; diff --git a/packages/instant/src/util/error_flasher.ts b/packages/instant/src/util/error_flasher.ts deleted file mode 100644 index 068c12fe29..0000000000 --- a/packages/instant/src/util/error_flasher.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { Dispatch } from 'redux'; - -import { Action, actions } from '../redux/actions'; - -class ErrorFlasher { - private _timeoutId?: number; - public flashNewErrorMessage(dispatch: Dispatch, errorMessage?: string, delayMs: number = 7000): void { - this._clearTimeout(); - // dispatch new message - dispatch(actions.setErrorMessage(errorMessage || 'Something went wrong...')); - this._timeoutId = window.setTimeout(() => { - dispatch(actions.hideError()); - }, delayMs); - } - public clearError(dispatch: Dispatch): void { - this._clearTimeout(); - dispatch(actions.hideError()); - } - private _clearTimeout(): void { - if (this._timeoutId) { - window.clearTimeout(this._timeoutId); - } - } -} - -export const errorFlasher = new ErrorFlasher(); diff --git a/packages/instant/src/util/error_reporter.ts b/packages/instant/src/util/error_reporter.ts deleted file mode 100644 index a419f36c51..0000000000 --- a/packages/instant/src/util/error_reporter.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { logUtils } from '@0x/utils'; -import * as _ from 'lodash'; - -import { - GIT_SHA, - HOST_DOMAINS_EXTERNAL, - HOST_DOMAINS_LOCAL, - INSTANT_DISCHARGE_TARGET, - NODE_ENV, - ROLLBAR_CLIENT_TOKEN, - ROLLBAR_ENABLED, -} from '../constants'; - -// Import version of Rollbar designed for embedded components -// See https://docs.rollbar.com/docs/using-rollbarjs-inside-an-embedded-component -// tslint:disable-next-line:no-var-requires -const Rollbar = require('rollbar/dist/rollbar.noconflict.umd'); - -const getRollbarHostDomains = (): string[] => { - if (NODE_ENV === 'development') { - return HOST_DOMAINS_EXTERNAL.concat(HOST_DOMAINS_LOCAL); - } else { - return HOST_DOMAINS_EXTERNAL; - } -}; - -let rollbar: any; -// Configures rollbar and sets up error catching -export const setupRollbar = (): any => { - if (rollbar === undefined && ROLLBAR_CLIENT_TOKEN && ROLLBAR_ENABLED) { - const hostDomains = getRollbarHostDomains(); - rollbar = new Rollbar({ - accessToken: ROLLBAR_CLIENT_TOKEN, - captureUncaught: true, - captureUnhandledRejections: true, - enabled: true, - itemsPerMinute: 10, - maxItems: 500, - payload: { - environment: INSTANT_DISCHARGE_TARGET || `Local ${NODE_ENV}`, - client: { - javascript: { - source_map_enabled: true, - code_version: GIT_SHA, - guess_uncaught_frames: true, - }, - }, - }, - hostWhiteList: hostDomains, - uncaughtErrorLevel: 'error', - ignoredMessages: [ - // Errors from the third-party scripts - 'Script error', - // Network errors or ad-blockers - 'TypeError: Failed to fetch', - 'Exchange has not been deployed to detected network (network/artifact mismatch)', - // Source: https://groups.google.com/a/chromium.org/forum/#!topic/chromium-discuss/7VU0_VvC7mE - "undefined is not an object (evaluating '__gCrWeb.autofill.extractForms')", - // Source: http://stackoverflow.com/questions/43399818/securityerror-from-facebook-and-cross-domain-messaging - 'SecurityError (DOM Exception 18)', - ], - }); - } -}; - -export const errorReporter = { - report(err: Error): void { - if (!rollbar) { - logUtils.log('Not reporting to rollbar because not configured', err); - return; - } - - rollbar.error(err, (rollbarErr: Error) => { - if (rollbarErr) { - logUtils.log(`Error reporting to rollbar, ignoring: ${rollbarErr}`); - } - }); - }, -}; diff --git a/packages/instant/src/util/etherscan.ts b/packages/instant/src/util/etherscan.ts deleted file mode 100644 index b22bd0043b..0000000000 --- a/packages/instant/src/util/etherscan.ts +++ /dev/null @@ -1,30 +0,0 @@ -import * as _ from 'lodash'; - -import { Network } from '../types'; - -const etherscanPrefix = (networkId: number): string | undefined => { - switch (networkId) { - case Network.Kovan: - return 'kovan.'; - case Network.Mainnet: - return ''; - } - return ''; -}; - -export const etherscanUtil = { - getEtherScanTxnAddressIfExists: (txHash: string, networkId: number) => { - const prefix = etherscanPrefix(networkId); - if (prefix === undefined) { - return; - } - return `https://${prefix}etherscan.io/tx/${txHash}`; - }, - getEtherScanEthAddressIfExists: (ethAddress: string, networkId: number) => { - const prefix = etherscanPrefix(networkId); - if (prefix === undefined) { - return; - } - return `https://${prefix}etherscan.io/address/${ethAddress}`; - }, -}; diff --git a/packages/instant/src/util/format.ts b/packages/instant/src/util/format.ts deleted file mode 100644 index f48f358b25..0000000000 --- a/packages/instant/src/util/format.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { BigNumber } from '@0x/utils'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import * as _ from 'lodash'; - -import { BIG_NUMBER_ZERO, ETH_DECIMALS } from '../constants'; - -export const format = { - ethBaseUnitAmount: ( - ethBaseUnitAmount?: BigNumber, - decimalPlaces: number = 4, - defaultText: React.ReactNode = '0 ETH', - ): React.ReactNode => { - if (ethBaseUnitAmount === undefined) { - return defaultText; - } - const ethUnitAmount = Web3Wrapper.toUnitAmount(ethBaseUnitAmount, ETH_DECIMALS); - return format.ethUnitAmount(ethUnitAmount, decimalPlaces); - }, - ethUnitAmount: ( - ethUnitAmount?: BigNumber, - decimalPlaces: number = 4, - defaultText: React.ReactNode = '0 ETH', - minUnitAmountToDisplay: BigNumber = new BigNumber('0.00001'), - ): React.ReactNode => { - if (ethUnitAmount === undefined) { - return defaultText; - } - let roundedAmount = ethUnitAmount.decimalPlaces(decimalPlaces).precision(decimalPlaces); - - if (roundedAmount.eq(BIG_NUMBER_ZERO) && ethUnitAmount.isGreaterThan(BIG_NUMBER_ZERO)) { - // Sometimes for small ETH amounts (i.e. 0.000045) the amount rounded to 4 decimalPlaces is 0 - // If that is the case, show to 1 significant digit - roundedAmount = new BigNumber(ethUnitAmount.toPrecision(1)); - } - - const displayAmount = - roundedAmount.isGreaterThan(BIG_NUMBER_ZERO) && roundedAmount.isLessThan(minUnitAmountToDisplay) - ? `< ${minUnitAmountToDisplay.toString()}` - : roundedAmount.toString(); - - return `${displayAmount} ETH`; - }, - ethBaseUnitAmountInUsd: ( - ethBaseUnitAmount?: BigNumber, - ethUsdPrice?: BigNumber, - decimalPlaces: number = 2, - defaultText: React.ReactNode = '$0.00', - minUnitAmountToDisplay: BigNumber = new BigNumber('0.00001'), - ): React.ReactNode => { - if (ethBaseUnitAmount === undefined || ethUsdPrice === undefined) { - return defaultText; - } - const ethUnitAmount = Web3Wrapper.toUnitAmount(ethBaseUnitAmount, ETH_DECIMALS); - return format.ethUnitAmountInUsd(ethUnitAmount, ethUsdPrice, decimalPlaces, minUnitAmountToDisplay); - }, - ethUnitAmountInUsd: ( - ethUnitAmount?: BigNumber, - ethUsdPrice?: BigNumber, - decimalPlaces: number = 2, - defaultText: React.ReactNode = '$0.00', - ): React.ReactNode => { - if (ethUnitAmount === undefined || ethUsdPrice === undefined) { - return defaultText; - } - const rawUsdPrice = ethUnitAmount.multipliedBy(ethUsdPrice); - const roundedUsdPrice = rawUsdPrice.toFixed(decimalPlaces); - if (roundedUsdPrice === '0.00' && rawUsdPrice.gt(BIG_NUMBER_ZERO)) { - return '<$0.01'; - } else { - return `$${roundedUsdPrice}`; - } - }, - ethAddress: (address: string): string => { - return `0x${address.slice(2, 7)}…${address.slice(-5)}`; - }, -}; diff --git a/packages/instant/src/util/gas_price_estimator.ts b/packages/instant/src/util/gas_price_estimator.ts deleted file mode 100644 index 9792b60bae..0000000000 --- a/packages/instant/src/util/gas_price_estimator.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { BigNumber, fetchAsync } from '@0x/utils'; - -import { - DEFAULT_ESTIMATED_TRANSACTION_TIME_MS, - DEFAULT_GAS_PRICE, - ETH_GAS_STATION_API_BASE_URL, - GWEI_IN_WEI, -} from '../constants'; - -import { errorReporter } from './error_reporter'; - -interface EthGasStationResult { - average: number; - fastestWait: number; - fastWait: number; - fast: number; - safeLowWait: number; - blockNum: number; - avgWait: number; - block_time: number; - speed: number; - fastest: number; - safeLow: number; -} - -interface GasInfo { - gasPriceInWei: BigNumber; - estimatedTimeMs: number; -} - -const fetchFastAmountInWeiAsync = async (): Promise => { - const res = await fetchAsync(`${ETH_GAS_STATION_API_BASE_URL}/json/ethgasAPI.json`); - const gasInfo = (await res.json()) as EthGasStationResult; - // Eth Gas Station result is gwei * 10 - const gasPriceInGwei = new BigNumber(gasInfo.fast / 10); - // Time is in minutes - const estimatedTimeMs = gasInfo.fastWait * 60 * 1000; // Minutes to MS - return { gasPriceInWei: gasPriceInGwei.multipliedBy(GWEI_IN_WEI), estimatedTimeMs }; -}; - -export class GasPriceEstimator { - private _lastFetched?: GasInfo; - public async getGasInfoAsync(): Promise { - let fetchedAmount: GasInfo | undefined; - try { - fetchedAmount = await fetchFastAmountInWeiAsync(); - } catch (e) { - fetchedAmount = undefined; - errorReporter.report(e); - } - - if (fetchedAmount) { - this._lastFetched = fetchedAmount; - } - - return ( - fetchedAmount || - this._lastFetched || { - gasPriceInWei: DEFAULT_GAS_PRICE, - estimatedTimeMs: DEFAULT_ESTIMATED_TRANSACTION_TIME_MS, - } - ); - } -} -export const gasPriceEstimator = new GasPriceEstimator(); diff --git a/packages/instant/src/util/heap.ts b/packages/instant/src/util/heap.ts deleted file mode 100644 index c644b55cd9..0000000000 --- a/packages/instant/src/util/heap.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { ObjectMap } from '@0x/types'; -import { logUtils } from '@0x/utils'; -import * as _ from 'lodash'; - -import { HEAP_ANALYTICS_ID } from '../constants'; - -import { AnalyticsEventOptions, AnalyticsUserOptions } from './analytics'; -import { errorReporter } from './error_reporter'; - -export type EventProperties = ObjectMap; - -export interface HeapAnalytics { - loaded: boolean; - appid: string; - identify(id: string, idType: string): void; - track(eventName: string, eventProperties?: EventProperties): void; - resetIdentity(): void; - addUserProperties(properties: AnalyticsUserOptions): void; - addEventProperties(properties: AnalyticsEventOptions): void; - removeEventProperty(property: string): void; - clearEventProperties(): void; -} -interface ModifiedWindow { - heap?: HeapAnalytics; - zeroExInstantLoadedHeap?: boolean; -} -const getWindow = (): ModifiedWindow => { - return window as ModifiedWindow; -}; - -const setupZeroExInstantHeap = () => { - if (HEAP_ANALYTICS_ID === undefined) { - return; - } - - const curWindow = getWindow(); - // Set property to specify that this is zeroEx's heap - curWindow.zeroExInstantLoadedHeap = true; - - // TypeScript-compatible version of https://docs.heapanalytics.com/docs/installation - /* tslint:disable */ - ((window as any).heap = (window as any).heap || []), - ((window as any).heap.load = function(e: any, t: any) { - ((window as any).heap.appid = e), ((window as any).heap.config = t = t || {}); - var r = t.forceSSL || 'https:' === (document.location as Location).protocol, - a = document.createElement('script'); - (a.type = 'text/javascript'), - (a.async = !0), - (a.src = (r ? 'https:' : 'http:') + '//cdn.heapanalytics.com/js/heap-' + e + '.js'); - var n = document.getElementsByTagName('script')[0]; - (n.parentNode as Node).insertBefore(a, n); - for ( - var o = function(e: any) { - return function() { - (window as any).heap.push([e].concat(Array.prototype.slice.call(arguments, 0))); - }; - }, - p = [ - 'addEventProperties', - 'addUserProperties', - 'clearEventProperties', - 'identify', - 'resetIdentity', - 'removeEventProperty', - 'setEventProperties', - 'track', - 'unsetEventProperty', - ], - c = 0; - c < p.length; - c++ - ) - (window as any).heap[p[c]] = o(p[c]); - }); - (window as any).heap.load(HEAP_ANALYTICS_ID); - /* tslint:enable */ - - return curWindow.heap as HeapAnalytics; -}; - -export const heapUtil = { - getHeap: (): HeapAnalytics | undefined => { - const curWindow = getWindow(); - const hasOtherExistingHeapIntegration = curWindow.heap && !curWindow.zeroExInstantLoadedHeap; - if (hasOtherExistingHeapIntegration) { - return undefined; - } - - const zeroExInstantHeapIntegration = curWindow.zeroExInstantLoadedHeap && curWindow.heap; - if (zeroExInstantHeapIntegration) { - return zeroExInstantHeapIntegration; - } - - return setupZeroExInstantHeap(); - }, - evaluateHeapCall: (heapFunctionCall: (heap: HeapAnalytics) => void): void => { - if (HEAP_ANALYTICS_ID === undefined) { - return; - } - - const curHeap = heapUtil.getHeap(); - if (curHeap) { - try { - if (curHeap.appid !== HEAP_ANALYTICS_ID) { - // Integrator has included heap after us and reset the app id - return; - } - heapFunctionCall(curHeap); - } catch (e) { - // We never want analytics to crash our React component - logUtils.log('Analytics error', e); - errorReporter.report(e); - } - } - }, -}; diff --git a/packages/instant/src/util/heartbeater.ts b/packages/instant/src/util/heartbeater.ts deleted file mode 100644 index 9c4c7e06dd..0000000000 --- a/packages/instant/src/util/heartbeater.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { intervalUtils } from '@0x/utils'; -import * as _ from 'lodash'; - -type HeartbeatableFunction = () => Promise; -export class Heartbeater { - private _intervalId?: NodeJS.Timer; - private readonly _performImmediatelyOnStart: boolean; - private readonly _performFunction: HeartbeatableFunction; - - public constructor(performingFunctionAsync: HeartbeatableFunction, performImmediatelyOnStart: boolean) { - this._performFunction = performingFunctionAsync; - this._performImmediatelyOnStart = performImmediatelyOnStart; - } - - public start(intervalTimeMs: number): void { - if (this._intervalId !== undefined) { - throw new Error('Heartbeat is running, please stop before restarting'); - } - - if (this._performImmediatelyOnStart) { - // tslint:disable-next-line:no-floating-promises - this._performFunction(); - } - - // tslint:disable-next-line:no-unbound-method - this._intervalId = intervalUtils.setAsyncExcludingInterval(this._performFunction, intervalTimeMs, _.noop); - } - - public stop(): void { - if (this._intervalId) { - intervalUtils.clearInterval(this._intervalId); - } - this._intervalId = undefined; - } -} diff --git a/packages/instant/src/util/heartbeater_factory.ts b/packages/instant/src/util/heartbeater_factory.ts deleted file mode 100644 index c80eccd8b2..0000000000 --- a/packages/instant/src/util/heartbeater_factory.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { asyncData } from '../redux/async_data'; -import { Store } from '../redux/store'; -import { QuoteFetchOrigin } from '../types'; - -import { Heartbeater } from './heartbeater'; - -export interface HeartbeatFactoryOptions { - store: Store; - shouldPerformImmediatelyOnStart: boolean; -} -export const generateAccountHeartbeater = (options: HeartbeatFactoryOptions): Heartbeater => { - const { store, shouldPerformImmediatelyOnStart } = options; - return new Heartbeater(async () => { - await asyncData.fetchAccountInfoAndDispatchToStore(store.getState().providerState, store.dispatch, false); - }, shouldPerformImmediatelyOnStart); -}; - -export const generateSwapQuoteHeartbeater = (options: HeartbeatFactoryOptions): Heartbeater => { - const { store, shouldPerformImmediatelyOnStart } = options; - return new Heartbeater(async () => { - await asyncData.fetchCurrentSwapQuoteAndDispatchToStore( - store.getState(), - store.dispatch, - QuoteFetchOrigin.Heartbeat, - { - updateSilently: true, - }, - ); - }, shouldPerformImmediatelyOnStart); -}; diff --git a/packages/instant/src/util/maybe_big_number.ts b/packages/instant/src/util/maybe_big_number.ts deleted file mode 100644 index 6b246f6a43..0000000000 --- a/packages/instant/src/util/maybe_big_number.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { BigNumber } from '@0x/utils'; -import * as _ from 'lodash'; - -import { Maybe } from '../types'; - -export const maybeBigNumberUtil = { - // converts a string to a Maybe - // if string is a NaN, considered undefined - stringToMaybeBigNumber: (stringValue: string): Maybe => { - let validBigNumber: BigNumber; - try { - validBigNumber = new BigNumber(stringValue); - } catch { - return undefined; - } - - return validBigNumber.isNaN() ? undefined : validBigNumber; - }, - areMaybeBigNumbersEqual: (val1: Maybe, val2: Maybe): boolean => { - if (val1 !== undefined && val2 !== undefined) { - return val1.isEqualTo(val2); - } - return val1 === undefined && val2 === undefined; - }, - // converts a BigNumber or String to the BigNumber used by 0x libraries - toMaybeBigNumber: (value: any): Maybe => { - if (_.isString(value)) { - return maybeBigNumberUtil.stringToMaybeBigNumber(value); - } - // checks for pre v8 bignumber with member variable - if (BigNumber.isBigNumber(value) || value.isBigNumber) { - return new BigNumber(value.toString()); - } - return undefined; - }, -}; diff --git a/packages/instant/src/util/order_coercion.ts b/packages/instant/src/util/order_coercion.ts deleted file mode 100644 index d56dcc77d7..0000000000 --- a/packages/instant/src/util/order_coercion.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { BigNumber } from '@0x/utils'; -import * as _ from 'lodash'; - -import { maybeBigNumberUtil } from './maybe_big_number'; - -const coerceBigNumberOrString = (value: any): BigNumber => { - const bn = maybeBigNumberUtil.toMaybeBigNumber(value); - return !!bn ? bn : value; -}; - -// function implies that the signed order already has been validated -export const orderCoercionUtil = { - // coerces order big number values to the BigNumber version utilized by 0x - coerceFieldsToBigNumbers(obj: any, fields: string[]): any { - const result = _.assign({}, obj); - _.each(fields, field => { - _.update(result, field, (value: string) => { - if (value === undefined) { - throw new Error(`Could not find field '${field}' while converting fields to BigNumber.`); - } - return coerceBigNumberOrString(value); - }); - }); - return result; - }, - - coerceOrderFieldsToBigNumber: (order: any): any => { - return orderCoercionUtil.coerceFieldsToBigNumbers(order, [ - 'makerFee', - 'takerFee', - 'makerAssetAmount', - 'takerAssetAmount', - 'salt', - 'expirationTimeSeconds', - ]); - }, - coerceOrderArrayFieldsToBigNumber: (orders: any[]): any[] => { - return _.map(orders, (value: any) => { - return orderCoercionUtil.coerceOrderFieldsToBigNumber(value); - }); - }, -}; diff --git a/packages/instant/src/util/provider_factory.ts b/packages/instant/src/util/provider_factory.ts deleted file mode 100644 index cde241527d..0000000000 --- a/packages/instant/src/util/provider_factory.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { EmptyWalletSubprovider, RPCSubprovider, Web3ProviderEngine } from '@0x/subproviders'; -import { providerUtils } from '@0x/utils'; -import { ZeroExProvider } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { ETHEREUM_NODE_URL_BY_NETWORK } from '../constants'; -import { Maybe, Network } from '../types'; - -export const providerFactory = { - getInjectedProviderIfExists: (): Maybe => { - const injectedProviderIfExists = (window as any).ethereum; - if (injectedProviderIfExists !== undefined) { - const provider = providerUtils.standardizeOrThrow(injectedProviderIfExists); - return provider; - } - const injectedWeb3IfExists = (window as any).web3; - if (injectedWeb3IfExists !== undefined && injectedWeb3IfExists.currentProvider !== undefined) { - const currentProvider = injectedWeb3IfExists.currentProvider; - const provider = providerUtils.standardizeOrThrow(currentProvider); - return provider; - } - return undefined; - }, - getFallbackNoSigningProvider: (network: Network): Web3ProviderEngine => { - const providerEngine = new Web3ProviderEngine(); - // Intercept calls to `eth_accounts` and always return empty - providerEngine.addProvider(new EmptyWalletSubprovider()); - // Construct an RPC subprovider, all data based requests will be sent via the RPCSubprovider - // TODO(bmillman): make this more resilient to infura failures - const rpcUrl = ETHEREUM_NODE_URL_BY_NETWORK[network]; - providerEngine.addProvider(new RPCSubprovider(rpcUrl)); - // Start the Provider Engine - providerUtils.startProviderEngine(providerEngine); - return providerEngine; - }, -}; diff --git a/packages/instant/src/util/provider_state_factory.ts b/packages/instant/src/util/provider_state_factory.ts deleted file mode 100644 index d32d0178ce..0000000000 --- a/packages/instant/src/util/provider_state_factory.ts +++ /dev/null @@ -1,158 +0,0 @@ -import { providerUtils } from '@0x/utils'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import { SupportedProvider, ZeroExProvider } from 'ethereum-types'; -import * as Fortmatic from 'fortmatic'; - -import { FORTMATIC_API_KEY, LOCKED_ACCOUNT, NO_ACCOUNT } from '../constants'; -import { Maybe, Network, OrderSource, ProviderState, ProviderType } from '../types'; -import { envUtil } from '../util/env'; - -import { assetSwapperFactory } from './asset_swapper_factory'; -import { providerFactory } from './provider_factory'; - -export const providerStateFactory = { - getInitialProviderState: ( - orderSource: OrderSource, - network: Network, - supportedProvider?: SupportedProvider, - walletDisplayName?: string, - ): ProviderState => { - if (supportedProvider !== undefined) { - const provider = providerUtils.standardizeOrThrow(supportedProvider); - return providerStateFactory.getInitialProviderStateFromProvider( - orderSource, - network, - provider, - walletDisplayName, - ); - } - const providerStateFromWindowIfExits = providerStateFactory.getInitialProviderStateFromWindowIfExists( - orderSource, - network, - walletDisplayName, - ); - if (providerStateFromWindowIfExits) { - return providerStateFromWindowIfExits; - } else { - return providerStateFactory.getInitialProviderStateFallback(orderSource, network, walletDisplayName); - } - }, - getInitialProviderStateFromProvider: ( - orderSource: OrderSource, - network: Network, - provider: ZeroExProvider, - walletDisplayName?: string, - ): ProviderState => { - const providerState: ProviderState = { - name: envUtil.getProviderName(provider), - displayName: walletDisplayName || envUtil.getProviderDisplayName(provider), - provider, - web3Wrapper: new Web3Wrapper(provider), - swapQuoter: assetSwapperFactory.getSwapQuoter(provider, orderSource, network), - swapQuoteConsumer: assetSwapperFactory.getSwapQuoteConsumer(provider, network), - account: LOCKED_ACCOUNT, - orderSource, - isProviderInjected: false, - }; - return providerState; - }, - getInitialProviderStateFromWindowIfExists: ( - orderSource: OrderSource, - network: Network, - walletDisplayName?: string, - ): Maybe => { - const injectedProviderIfExists = providerFactory.getInjectedProviderIfExists(); - if (injectedProviderIfExists !== undefined) { - const providerState: ProviderState = { - name: envUtil.getProviderName(injectedProviderIfExists), - displayName: walletDisplayName || envUtil.getProviderDisplayName(injectedProviderIfExists), - provider: injectedProviderIfExists, - web3Wrapper: new Web3Wrapper(injectedProviderIfExists), - swapQuoter: assetSwapperFactory.getSwapQuoter(injectedProviderIfExists, orderSource, network), - swapQuoteConsumer: assetSwapperFactory.getSwapQuoteConsumer(injectedProviderIfExists, network), - account: LOCKED_ACCOUNT, - orderSource, - isProviderInjected: true, - }; - return providerState; - } else { - return undefined; - } - }, - getInitialProviderStateFallback: ( - orderSource: OrderSource, - network: Network, - walletDisplayName?: string, - ): ProviderState => { - const provider = providerFactory.getFallbackNoSigningProvider(network); - const providerState: ProviderState = { - name: 'Fallback', - displayName: walletDisplayName || envUtil.getProviderDisplayName(provider), - provider, - web3Wrapper: new Web3Wrapper(provider), - swapQuoter: assetSwapperFactory.getSwapQuoter(provider, orderSource, network), - swapQuoteConsumer: assetSwapperFactory.getSwapQuoteConsumer(provider, network), - account: NO_ACCOUNT, - orderSource, - isProviderInjected: true, - }; - return providerState; - }, - // function to call getInitialProviderState with parameters retreived from a provided ProviderState - getInitialProviderStateWithCurrentProviderState: (currentProviderState: ProviderState): ProviderState => { - const orderSource = currentProviderState.orderSource; - const chainId = currentProviderState.swapQuoter.chainId; - // If provider is provided to instant, use that and the displayName - if (!currentProviderState.isProviderInjected) { - return providerStateFactory.getInitialProviderState( - orderSource, - chainId, - currentProviderState.provider, - currentProviderState.displayName, - ); - } - const newProviderState = providerStateFactory.getInitialProviderState(orderSource, chainId); - newProviderState.account = LOCKED_ACCOUNT; - return newProviderState; - }, - getProviderStateBasedOnProviderType: ( - currentProviderState: ProviderState, - providerType: ProviderType, - ): ProviderState => { - const chainId = currentProviderState.swapQuoter.chainId; - const orderSource = currentProviderState.orderSource; - // Returns current provider if the provider type selected is not found - if (providerType === ProviderType.MetaMask) { - const provider = providerFactory.getInjectedProviderIfExists(); - if (provider) { - return { - displayName: envUtil.getProviderDisplayName(provider), - name: envUtil.getProviderName(provider), - provider, - web3Wrapper: new Web3Wrapper(provider), - swapQuoter: assetSwapperFactory.getSwapQuoter(provider, orderSource, chainId), - swapQuoteConsumer: assetSwapperFactory.getSwapQuoteConsumer(provider, chainId), - account: LOCKED_ACCOUNT, - orderSource, - isProviderInjected: true, - }; - } - } - if (providerType === ProviderType.Fortmatic) { - const fm = new Fortmatic(FORTMATIC_API_KEY); - const fmProvider = fm.getProvider(); - return { - displayName: envUtil.getProviderDisplayName(fmProvider), - name: envUtil.getProviderName(fmProvider), - provider: fmProvider, - web3Wrapper: new Web3Wrapper(fmProvider), - swapQuoter: assetSwapperFactory.getSwapQuoter(fmProvider, orderSource, chainId), - swapQuoteConsumer: assetSwapperFactory.getSwapQuoteConsumer(fmProvider, chainId), - account: LOCKED_ACCOUNT, - orderSource, - isProviderInjected: true, - }; - } - return providerStateFactory.getInitialProviderState(orderSource, chainId); - }, -}; diff --git a/packages/instant/src/util/swap_quote_updater.ts b/packages/instant/src/util/swap_quote_updater.ts deleted file mode 100644 index 97bfcad0ba..0000000000 --- a/packages/instant/src/util/swap_quote_updater.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { MarketBuySwapQuote, SwapQuoter } from '@0x/asset-swapper'; -import { AssetProxyId } from '@0x/types'; -import { BigNumber } from '@0x/utils'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import { Dispatch } from 'redux'; - -import { Action, actions } from '../redux/actions'; -import { Asset, QuoteFetchOrigin } from '../types'; - -import { analytics } from './analytics'; -import { assetUtils } from './asset'; -import { errorFlasher } from './error_flasher'; -import { errorReporter } from './error_reporter'; -import { gasPriceEstimator } from './gas_price_estimator'; - -export const swapQuoteUpdater = { - updateSwapQuoteAsync: async ( - swapQuoter: SwapQuoter, - dispatch: Dispatch, - asset: Asset, - assetUnitAmount: BigNumber, - fetchOrigin: QuoteFetchOrigin, - options: { - setPending: boolean; - dispatchErrors: boolean; - }, - ): Promise => { - // get a new swap quote. - const baseUnitValue = - asset.metaData.assetProxyId === AssetProxyId.ERC20 - ? Web3Wrapper.toBaseUnitAmount(assetUnitAmount, asset.metaData.decimals) - : assetUnitAmount; - if (options.setPending) { - // mark quote as pending - dispatch(actions.setQuoteRequestStatePending()); - } - const wethAssetData = await swapQuoter.getEtherTokenAssetDataOrThrowAsync(); - let newSwapQuote: MarketBuySwapQuote | undefined; - try { - const gasInfo = await gasPriceEstimator.getGasInfoAsync(); - newSwapQuote = await swapQuoter.getMarketBuySwapQuoteForAssetDataAsync( - asset.assetData, - wethAssetData, - baseUnitValue, - { - gasPrice: gasInfo.gasPriceInWei, - // Only use native orders - // excludedSources: [ERC20BridgeSource.Eth2Dai, ERC20BridgeSource.Kyber, ERC20BridgeSource.Uniswap], - }, - ); - } catch (error) { - const errorMessage = assetUtils.swapQuoterErrorMessage(asset, error); - - errorReporter.report(error); - analytics.trackQuoteError(error.message ? error.message : 'other', baseUnitValue, fetchOrigin); - - if (options.dispatchErrors) { - dispatch(actions.setQuoteRequestStateFailure()); - errorFlasher.flashNewErrorMessage(dispatch, errorMessage || 'Error fetching price, please try again'); - } - return; - } - // We have a successful new swap quote - errorFlasher.clearError(dispatch); - // invalidate the last swap quote. - dispatch(actions.updateLatestSwapQuote(newSwapQuote)); - analytics.trackQuoteFetched(newSwapQuote, fetchOrigin); - }, -}; diff --git a/packages/instant/src/util/time.ts b/packages/instant/src/util/time.ts deleted file mode 100644 index bfe69cad59..0000000000 --- a/packages/instant/src/util/time.ts +++ /dev/null @@ -1,39 +0,0 @@ -const secondsToMinutesAndRemainingSeconds = (seconds: number): { minutes: number; remainingSeconds: number } => { - const minutes = Math.floor(seconds / 60); - const remainingSeconds = seconds - minutes * 60; - - return { - minutes, - remainingSeconds, - }; -}; - -const padZero = (aNumber: number): string => { - return aNumber < 10 ? `0${aNumber}` : aNumber.toString(); -}; - -export const timeUtil = { - // converts seconds to human readable version of seconds or minutes - secondsToHumanDescription: (seconds: number): string => { - const { minutes, remainingSeconds } = secondsToMinutesAndRemainingSeconds(seconds); - - if (minutes === 0) { - const suffix = seconds > 1 ? 's' : ''; - return `${seconds} second${suffix}`; - } - - const minuteSuffix = minutes > 1 ? 's' : ''; - const minuteText = `${minutes} minute${minuteSuffix}`; - - const secondsSuffix = remainingSeconds > 1 ? 's' : ''; - const secondsText = remainingSeconds === 0 ? '' : ` ${remainingSeconds} second${secondsSuffix}`; - - return `${minuteText}${secondsText}`; - }, - // converts seconds to stopwatch time (i.e. 05:30 and 00:30) - // only goes up to minutes, not hours - secondsToStopwatchTime: (seconds: number): string => { - const { minutes, remainingSeconds } = secondsToMinutesAndRemainingSeconds(seconds); - return `${padZero(minutes)}:${padZero(remainingSeconds)}`; - }, -}; diff --git a/packages/instant/src/util/util.ts b/packages/instant/src/util/util.ts deleted file mode 100644 index 29b6b1d2bf..0000000000 --- a/packages/instant/src/util/util.ts +++ /dev/null @@ -1,6 +0,0 @@ -import * as _ from 'lodash'; - -export const util = { - boundNoop: _.noop.bind(_), - createOpenUrlInNewWindow: (href: string) => () => window.open(href, '_blank'), -}; diff --git a/packages/instant/test/components/zero_ex_instant.test.tsx b/packages/instant/test/components/zero_ex_instant.test.tsx deleted file mode 100644 index e373bb002d..0000000000 --- a/packages/instant/test/components/zero_ex_instant.test.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { configure, shallow } from 'enzyme'; -import * as Adapter from 'enzyme-adapter-react-16'; -import * as React from 'react'; - -configure({ adapter: new Adapter() }); - -// TODO: Write non-trivial tests. -// At time of writing we cannot render ZeroExInstant -// because we are looking for a provider on window. -// But in the future it will be dependency injected. -describe('', () => { - it('runs a test', () => { - shallow(
); - }); -}); diff --git a/packages/instant/test/util/asset.test.ts b/packages/instant/test/util/asset.test.ts deleted file mode 100644 index 57950f8eb8..0000000000 --- a/packages/instant/test/util/asset.test.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { BigNumber, InsufficientAssetLiquidityError, SwapQuoterError } from '@0x/asset-swapper'; -import { AssetProxyId, ObjectMap } from '@0x/types'; -import { Web3Wrapper } from '@0x/web3-wrapper'; - -import { Asset, AssetMetaData, ERC20Asset, ERC20AssetMetaData, Network, ZeroExInstantError } from '../../src/types'; -import { assetUtils } from '../../src/util/asset'; - -const ZRX_ASSET_DATA = '0xf47261b0000000000000000000000000e41d2489571d322189246dafa5ebde1f4699f498'; -const ZRX_ASSET_DATA_KOVAN = '0xf47261b00000000000000000000000002002d3812f58e35f0ea1ffbf80a75a38c32175fa'; -const ZRX_META_DATA: ERC20AssetMetaData = { - assetProxyId: AssetProxyId.ERC20, - symbol: 'zrx', - decimals: 18, - name: '0x', -}; -const ZRX_ASSET: ERC20Asset = { - assetData: ZRX_ASSET_DATA, - metaData: ZRX_META_DATA, -}; -const META_DATA_MAP: ObjectMap = { - [ZRX_ASSET_DATA]: ZRX_META_DATA, -}; -const WAX_ASSET: ERC20Asset = { - assetData: '0xf47261b000000000000000000000000039bb259f66e1c59d5abef88375979b4d20d98022', - metaData: { - assetProxyId: AssetProxyId.ERC20, - decimals: 8, - primaryColor: '#EDB740', - symbol: 'wax', - name: 'WAX', - }, -}; - -describe('assetDataUtil', () => { - describe('bestNameForAsset', () => { - it('should return default string if assetData is undefined', () => { - expect(assetUtils.bestNameForAsset(undefined, 'xyz')).toEqual('xyz'); - }); - it('should return ZRX for ZRX assetData', () => { - expect(assetUtils.bestNameForAsset(ZRX_ASSET, 'mah default')).toEqual('ZRX'); - }); - }); - describe('getMetaDataOrThrow', () => { - it('should return the metaData for the supplied mainnet asset data', () => { - expect(assetUtils.getMetaDataOrThrow(ZRX_ASSET_DATA, META_DATA_MAP, Network.Mainnet)).toEqual( - ZRX_META_DATA, - ); - }); - it('should return the metaData for the supplied non-mainnet asset data', () => { - expect(assetUtils.getMetaDataOrThrow(ZRX_ASSET_DATA_KOVAN, META_DATA_MAP, Network.Kovan)).toEqual( - ZRX_META_DATA, - ); - }); - it('should throw if the metaData for the asset is not available', () => { - expect(() => - assetUtils.getMetaDataOrThrow('asset data we dont have', META_DATA_MAP, Network.Mainnet), - ).toThrowError(ZeroExInstantError.AssetMetaDataNotAvailable); - }); - }); - describe('assetBuyerErrorMessage', () => { - it('should return message for generic InsufficientAssetLiquidity error', () => { - const insufficientAssetError = new Error(SwapQuoterError.InsufficientAssetLiquidity); - expect(assetUtils.swapQuoterErrorMessage(ZRX_ASSET, insufficientAssetError)).toEqual( - 'Not enough ZRX available', - ); - }); - describe('InsufficientAssetLiquidityError', () => { - it('should return custom message for token w/ 18 decimals', () => { - const amountAvailable = Web3Wrapper.toBaseUnitAmount(new BigNumber(20.059), 18); - expect( - assetUtils.swapQuoterErrorMessage(ZRX_ASSET, new InsufficientAssetLiquidityError(amountAvailable)), - ).toEqual('There are only 20.05 ZRX available to buy'); - }); - it('should return custom message for token w/ 18 decimals and small amount available', () => { - const amountAvailable = Web3Wrapper.toBaseUnitAmount(new BigNumber(0.01), 18); - expect( - assetUtils.swapQuoterErrorMessage(ZRX_ASSET, new InsufficientAssetLiquidityError(amountAvailable)), - ).toEqual('There are only 0.01 ZRX available to buy'); - }); - it('should return custom message for token w/ 8 decimals', () => { - const amountAvailable = Web3Wrapper.toBaseUnitAmount(new BigNumber(3), 8); - expect( - assetUtils.swapQuoterErrorMessage(WAX_ASSET, new InsufficientAssetLiquidityError(amountAvailable)), - ).toEqual('There are only 3 WAX available to buy'); - }); - it('should return generic message when amount available rounds to zero', () => { - const amountAvailable = Web3Wrapper.toBaseUnitAmount(new BigNumber(0.002), 18); - expect( - assetUtils.swapQuoterErrorMessage(ZRX_ASSET, new InsufficientAssetLiquidityError(amountAvailable)), - ).toEqual('Not enough ZRX available'); - }); - }); - it('should message for StandardRelayerApiError', () => { - const standardRelayerError = new Error(SwapQuoterError.StandardRelayerApiError); - expect(assetUtils.swapQuoterErrorMessage(ZRX_ASSET, standardRelayerError)).toEqual( - 'ZRX is currently unavailable', - ); - }); - it('should return error for AssetUnavailable error', () => { - const assetUnavailableError = new Error( - `${SwapQuoterError.AssetUnavailable}: For assetData ${ZRX_ASSET_DATA}`, - ); - expect(assetUtils.swapQuoterErrorMessage(ZRX_ASSET, assetUnavailableError)).toEqual( - 'ZRX is currently unavailable', - ); - }); - }); -}); diff --git a/packages/instant/test/util/format.test.ts b/packages/instant/test/util/format.test.ts deleted file mode 100644 index 38bf356ec6..0000000000 --- a/packages/instant/test/util/format.test.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { BigNumber } from '@0x/utils'; -import { Web3Wrapper } from '@0x/web3-wrapper'; - -import { ETH_DECIMALS } from '../../src/constants'; -import { format } from '../../src/util/format'; - -const BIG_NUMBER_ONE = new BigNumber(1); -const BIG_NUMBER_DECIMAL = new BigNumber(0.432414); -const BIG_NUMBER_IRRATIONAL = new BigNumber(5.3014059295032); -const ONE_ETH_IN_BASE_UNITS = Web3Wrapper.toBaseUnitAmount(BIG_NUMBER_ONE, ETH_DECIMALS); -const DECIMAL_ETH_IN_BASE_UNITS = Web3Wrapper.toBaseUnitAmount(BIG_NUMBER_DECIMAL, ETH_DECIMALS); -const IRRATIONAL_ETH_IN_BASE_UNITS = Web3Wrapper.toBaseUnitAmount(BIG_NUMBER_IRRATIONAL, ETH_DECIMALS); -const BIG_NUMBER_FAKE_ETH_USD_PRICE = new BigNumber(2.534); - -describe('format', () => { - describe('ethBaseAmount', () => { - it('converts 1 ETH in base units to the string `1 ETH`', () => { - expect(format.ethBaseUnitAmount(ONE_ETH_IN_BASE_UNITS)).toBe('1 ETH'); - }); - it('converts .432414 ETH in base units to the string `.4324 ETH`', () => { - expect(format.ethBaseUnitAmount(DECIMAL_ETH_IN_BASE_UNITS)).toBe('0.4324 ETH'); - }); - it('converts 5.3014059295032 ETH in base units to the string `5.301 ETH`', () => { - expect(format.ethBaseUnitAmount(IRRATIONAL_ETH_IN_BASE_UNITS)).toBe('5.301 ETH'); - }); - it('returns defaultText param when ethBaseAmount is not defined', () => { - const defaultText = 'defaultText'; - expect(format.ethBaseUnitAmount(undefined, 4, defaultText)).toBe(defaultText); - }); - it('it allows for configurable decimal places', () => { - expect(format.ethBaseUnitAmount(DECIMAL_ETH_IN_BASE_UNITS, 2)).toBe('0.43 ETH'); - }); - }); - describe('ethUnitAmount', () => { - it('converts BigNumber(1) to the string `1 ETH`', () => { - expect(format.ethUnitAmount(BIG_NUMBER_ONE)).toBe('1 ETH'); - }); - it('converts BigNumer(.432414) to the string `.4324 ETH`', () => { - expect(format.ethUnitAmount(BIG_NUMBER_DECIMAL)).toBe('0.4324 ETH'); - }); - it('converts BigNumber(5.3014059295032) to the string `5.301 ETH`', () => { - expect(format.ethUnitAmount(BIG_NUMBER_IRRATIONAL)).toBe('5.301 ETH'); - }); - it('shows 1 significant digit when rounded amount would be 0', () => { - expect(format.ethUnitAmount(new BigNumber(0.00003))).toBe('0.00003 ETH'); - expect(format.ethUnitAmount(new BigNumber(0.000034))).toBe('0.00003 ETH'); - expect(format.ethUnitAmount(new BigNumber(0.000035))).toBe('0.00004 ETH'); - }); - it('shows < 0.00001 when hits threshold', () => { - expect(format.ethUnitAmount(new BigNumber(0.000011))).toBe('0.00001 ETH'); - expect(format.ethUnitAmount(new BigNumber(0.00001))).toBe('0.00001 ETH'); - expect(format.ethUnitAmount(new BigNumber(0.000009))).toBe('< 0.00001 ETH'); - expect(format.ethUnitAmount(new BigNumber(0.0000000009))).toBe('< 0.00001 ETH'); - expect(format.ethUnitAmount(new BigNumber(0))).toBe('0 ETH'); - }); - it('returns defaultText param when ethUnitAmount is not defined', () => { - const defaultText = 'defaultText'; - expect(format.ethUnitAmount(undefined, 4, defaultText)).toBe(defaultText); - expect(format.ethUnitAmount(BIG_NUMBER_ONE, 4, defaultText)).toBe('1 ETH'); - }); - it('it allows for configurable decimal places', () => { - expect(format.ethUnitAmount(BIG_NUMBER_DECIMAL, 2)).toBe('0.43 ETH'); - }); - }); - describe('ethBaseAmountInUsd', () => { - it('correctly formats 1 ETH to usd according to some price', () => { - expect(format.ethBaseUnitAmountInUsd(ONE_ETH_IN_BASE_UNITS, BIG_NUMBER_FAKE_ETH_USD_PRICE)).toBe('$2.53'); - }); - it('correctly formats .432414 ETH to usd according to some price', () => { - expect(format.ethBaseUnitAmountInUsd(DECIMAL_ETH_IN_BASE_UNITS, BIG_NUMBER_FAKE_ETH_USD_PRICE)).toBe( - '$1.10', - ); - }); - it('correctly formats 5.3014059295032 ETH to usd according to some price', () => { - expect(format.ethBaseUnitAmountInUsd(IRRATIONAL_ETH_IN_BASE_UNITS, BIG_NUMBER_FAKE_ETH_USD_PRICE)).toBe( - '$13.43', - ); - }); - it('returns defaultText param when ethBaseAmountInUsd or ethUsdPrice is not defined', () => { - const defaultText = 'defaultText'; - expect(format.ethBaseUnitAmountInUsd(undefined, undefined, 2, defaultText)).toBe(defaultText); - expect(format.ethBaseUnitAmountInUsd(BIG_NUMBER_ONE, undefined, 2, defaultText)).toBe(defaultText); - expect(format.ethBaseUnitAmountInUsd(undefined, BIG_NUMBER_ONE, 2, defaultText)).toBe(defaultText); - }); - it('it allows for configurable decimal places', () => { - expect(format.ethBaseUnitAmountInUsd(DECIMAL_ETH_IN_BASE_UNITS, BIG_NUMBER_FAKE_ETH_USD_PRICE, 4)).toBe( - '$1.0957', - ); - }); - }); - describe('ethUnitAmountInUsd', () => { - it('correctly formats 1 ETH to usd according to some price', () => { - expect(format.ethUnitAmountInUsd(BIG_NUMBER_ONE, BIG_NUMBER_FAKE_ETH_USD_PRICE)).toBe('$2.53'); - }); - it('correctly formats .432414 ETH to usd according to some price', () => { - expect(format.ethUnitAmountInUsd(BIG_NUMBER_DECIMAL, BIG_NUMBER_FAKE_ETH_USD_PRICE)).toBe('$1.10'); - }); - it('correctly formats 5.3014059295032 ETH to usd according to some price', () => { - expect(format.ethUnitAmountInUsd(BIG_NUMBER_IRRATIONAL, BIG_NUMBER_FAKE_ETH_USD_PRICE)).toBe('$13.43'); - }); - it('correctly formats amount that is less than 1 cent', () => { - expect(format.ethUnitAmountInUsd(new BigNumber(0.000001), BIG_NUMBER_FAKE_ETH_USD_PRICE)).toBe('<$0.01'); - }); - it('correctly formats exactly 1 cent', () => { - expect(format.ethUnitAmountInUsd(new BigNumber(0.0039), BIG_NUMBER_FAKE_ETH_USD_PRICE)).toBe('$0.01'); - }); - it('returns defaultText param when ethUnitAmountInUsd or ethUsdPrice is not defined', () => { - const defaultText = 'defaultText'; - expect(format.ethUnitAmountInUsd(undefined, undefined, 2, defaultText)).toBe(defaultText); - expect(format.ethUnitAmountInUsd(BIG_NUMBER_ONE, undefined, 2, defaultText)).toBe(defaultText); - expect(format.ethUnitAmountInUsd(undefined, BIG_NUMBER_ONE, 2, defaultText)).toBe(defaultText); - }); - it('it allows for configurable decimal places', () => { - expect(format.ethUnitAmountInUsd(BIG_NUMBER_DECIMAL, BIG_NUMBER_FAKE_ETH_USD_PRICE, 4)).toBe('$1.0957'); - }); - }); -}); diff --git a/packages/instant/test/util/maybe_big_number.test.ts b/packages/instant/test/util/maybe_big_number.test.ts deleted file mode 100644 index 508e8aaf06..0000000000 --- a/packages/instant/test/util/maybe_big_number.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { BigNumber } from '@0x/utils'; - -import { maybeBigNumberUtil } from '../../src/util/maybe_big_number'; - -const BIG_NUMBER_1 = new BigNumber('10.1'); -const BIG_NUMBER_2 = new BigNumber('10.1'); -const BIG_NUMBER_3 = new BigNumber('11.1'); - -describe('maybeBigNumberUtil', () => { - describe('stringToMaybeBigNumber', () => { - it('should return undefined if stringValue is NaN', () => { - expect(maybeBigNumberUtil.stringToMaybeBigNumber('NaN')).toEqual(undefined); - }); - it('should return bignumber constructed with stringValue', () => { - const bn = maybeBigNumberUtil.stringToMaybeBigNumber('10.1'); - if (!!bn) { - expect(bn.toString()).toEqual('10.1'); - } - }); - it('should return undefined if stringValue is not valid (i.e not numeric)', () => { - expect(maybeBigNumberUtil.stringToMaybeBigNumber('test')).toEqual(undefined); - }); - }); - - describe('areMaybeBigNumbersEqual', () => { - it('should return true if val1 and val2 are equivalent BigNumber values', () => { - expect(maybeBigNumberUtil.areMaybeBigNumbersEqual(BIG_NUMBER_1, BIG_NUMBER_2)).toEqual(true); - }); - it('should return true if val1 and val2 are both undefined', () => { - expect(maybeBigNumberUtil.areMaybeBigNumbersEqual(undefined, undefined)).toEqual(true); - }); - it('should return false if either one val1 or val2 is undefined', () => { - expect(maybeBigNumberUtil.areMaybeBigNumbersEqual(BIG_NUMBER_1, undefined)).toEqual(false); - }); - it('should return false if val1 and val2 are equivalent values BigNumber', () => { - expect(maybeBigNumberUtil.areMaybeBigNumbersEqual(BIG_NUMBER_1, BIG_NUMBER_3)).toEqual(false); - }); - }); - - // this doesn't test coercing a pre v8.0.0 version of big number to desired version - describe('toMaybeBigNumber', () => { - it('should return BigNumber (>=v8.0.0) constructed with value if type is string', () => { - const bn = maybeBigNumberUtil.toMaybeBigNumber('10.1'); - if (!!bn) { - expect(bn.toString()).toEqual('10.1'); - } - }); - it('should return undefined if value is NaN', () => { - expect(maybeBigNumberUtil.toMaybeBigNumber('NaN')).toEqual(undefined); - }); - it('should return undefined if value as string is not valid (i.e not numeric)', () => { - expect(maybeBigNumberUtil.toMaybeBigNumber('test')).toEqual(undefined); - }); - it('should return undefined if value as string is not valid (i.e not numeric)', () => { - expect(maybeBigNumberUtil.toMaybeBigNumber('test')).toEqual(undefined); - }); - it('should return BigNumber (>=v8.0.0) when passed a value as BigNumber (>=v8.0.0)', () => { - const bn = maybeBigNumberUtil.toMaybeBigNumber(BIG_NUMBER_1); - expect(BigNumber.isBigNumber(bn)).toEqual(true); - }); - it('should return undefined if value is not BigNumber or string', () => { - expect(maybeBigNumberUtil.toMaybeBigNumber(true)).toEqual(undefined); - }); - }); -}); diff --git a/packages/instant/test/util/order_coercion.test.ts b/packages/instant/test/util/order_coercion.test.ts deleted file mode 100644 index f7a958c9d3..0000000000 --- a/packages/instant/test/util/order_coercion.test.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { BigNumber } from '@0x/utils'; - -import { orderCoercionUtil } from '../../src/util/order_coercion'; - -const ORDER = { - senderAddress: '0x0000000000000000000000000000000000000000', - makerAddress: '0x34a745008a643eebc58920eaa29fb1165b4a288e', - takerAddress: '0x0000000000000000000000000000000000000000', - makerFee: new BigNumber('0'), - takerFee: new BigNumber('0'), - makerAssetAmount: new BigNumber('200000000000000000000'), - takerAssetAmount: new BigNumber('10000000000000000000'), - makerAssetData: '0xf47261b00000000000000000000000008cb3971b8eb709c14616bd556ff6683019e90d9c', - takerAssetData: '0xf47261b0000000000000000000000000d0a1e359811322d97991e03f863a0c30c2cf029c', - expirationTimeSeconds: new BigNumber('1601535600'), - feeRecipientAddress: '0x0000000000000000000000000000000000000000', - salt: new BigNumber('3101985707338942582579795423923841749956600670712030922928319824580764688653'), - signature: - '0x1bd4d5686fea801fe33c68c4944356085e7e6cb553eb7073160abd815609f714e85fb47f44b7ffd0a2a1321ac40d72d55163869d0a50fdb5a402132150fe33a08403', - exchangeAddress: '0x35dd2932454449b14cee11a94d3674a936d5d7b2', -}; - -const STRING_ORDER = { - senderAddress: '0x0000000000000000000000000000000000000000', - makerAddress: '0x34a745008a643eebc58920eaa29fb1165b4a288e', - takerAddress: '0x0000000000000000000000000000000000000000', - makerFee: '0', - takerFee: '0', - makerAssetAmount: '300000000000000000000', - takerAssetAmount: '31000000000000000000', - makerAssetData: '0xf47261b00000000000000000000000002002d3812f58e35f0ea1ffbf80a75a38c32175fa', - takerAssetData: '0xf47261b0000000000000000000000000d0a1e359811322d97991e03f863a0c30c2cf029c', - expirationTimeSeconds: '2524636800', - feeRecipientAddress: '0x0000000000000000000000000000000000000000', - salt: '64592004666704945574675477805199411288137454783320798602050822322450089238268', - signature: - '0x1c13cacddca8d7d8248e91f412377e68f8f1f9891a59a6c1b2eea9f7b33558c30c4fb86a448e08ab7def40a28fb3a3062dcb33bb3c45302447fce5c4288b7c7f5b03', - exchangeAddress: '0x35dd2932454449b14cee11a94d3674a936d5d7b2', -}; - -const ORDERS = [ORDER, STRING_ORDER]; - -describe('orderCoercionUtil', () => { - describe('coerceFieldsToBigNumbers', () => { - it('should coerce all fields specified to a big number', () => { - const coercedOrder = orderCoercionUtil.coerceFieldsToBigNumbers(STRING_ORDER, ['makerFee', 'takerFee']); - expect(coercedOrder.makerFee.toString()).toEqual('0'); - expect(coercedOrder.takerFee.toString()).toEqual('0'); - }); - it("should throw if a field can't be found", () => { - expect(() => { - orderCoercionUtil.coerceFieldsToBigNumbers(ORDER, ['salty']); - }).toThrow("Could not find field 'salty' while converting fields to BigNumber."); - }); - it('should not change value if not numeric string or big number', () => { - const obj = { number: 'number' }; - const coercedObj = orderCoercionUtil.coerceFieldsToBigNumbers(obj, ['number']); - expect(coercedObj).toEqual({ - number: 'number', - }); - }); - }); - // Note: this doesn't test coercing pre v8.0.0 BigNumber versions to specified one used by 0x - describe('coerceOrderFieldsToBigNumber', () => { - it('should convert string values in order to big number', () => { - const coercedOrder = orderCoercionUtil.coerceOrderFieldsToBigNumber(STRING_ORDER); - expect(coercedOrder.makerFee.toString()).toEqual(STRING_ORDER.makerFee); - expect(coercedOrder.takerFee.toString()).toEqual(STRING_ORDER.takerFee); - expect(coercedOrder.takerAssetAmount.toString()).toEqual(STRING_ORDER.takerAssetAmount); - expect(coercedOrder.makerAssetAmount.toString()).toEqual(STRING_ORDER.makerAssetAmount); - expect(coercedOrder.salt.toString()).toEqual(STRING_ORDER.salt); - expect(coercedOrder.expirationTimeSeconds.toString()).toEqual(STRING_ORDER.expirationTimeSeconds); - }); - it('should convert big number values in order to big number', () => { - const coercedOrder = orderCoercionUtil.coerceOrderFieldsToBigNumber(ORDER); - expect(coercedOrder.makerFee).toEqual(ORDER.makerFee); - expect(coercedOrder.takerFee).toEqual(ORDER.takerFee); - expect(coercedOrder.takerAssetAmount).toEqual(ORDER.takerAssetAmount); - expect(coercedOrder.makerAssetAmount).toEqual(ORDER.makerAssetAmount); - expect(coercedOrder.salt).toEqual(ORDER.salt); - expect(coercedOrder.expirationTimeSeconds).toEqual(ORDER.expirationTimeSeconds); - }); - }); - // Note: this doesn't test coercing pre v8.0.0 BigNumber versions to specified one used by 0x - describe('coerceOrderArrayFieldsToBigNumber', () => { - it('should convert string values and big numbers in orders to big number', () => { - const coercedOrders = orderCoercionUtil.coerceOrderArrayFieldsToBigNumber(ORDERS); - expect(coercedOrders[0].makerFee).toEqual(ORDER.makerFee); - expect(coercedOrders[0].takerFee).toEqual(ORDER.takerFee); - expect(coercedOrders[0].takerAssetAmount).toEqual(ORDER.takerAssetAmount); - expect(coercedOrders[0].makerAssetAmount).toEqual(ORDER.makerAssetAmount); - expect(coercedOrders[0].salt).toEqual(ORDER.salt); - expect(coercedOrders[0].expirationTimeSeconds).toEqual(ORDER.expirationTimeSeconds); - - expect(coercedOrders[1].makerFee.toString()).toEqual(STRING_ORDER.makerFee); - expect(coercedOrders[1].takerFee.toString()).toEqual(STRING_ORDER.takerFee); - expect(coercedOrders[1].takerAssetAmount.toString()).toEqual(STRING_ORDER.takerAssetAmount); - expect(coercedOrders[1].makerAssetAmount.toString()).toEqual(STRING_ORDER.makerAssetAmount); - expect(coercedOrders[1].salt.toString()).toEqual(STRING_ORDER.salt); - expect(coercedOrders[1].expirationTimeSeconds.toString()).toEqual(STRING_ORDER.expirationTimeSeconds); - }); - }); -}); diff --git a/packages/instant/test/util/time.test.ts b/packages/instant/test/util/time.test.ts deleted file mode 100644 index fcb4e1875c..0000000000 --- a/packages/instant/test/util/time.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { timeUtil } from '../../src/util/time'; - -describe('timeUtil', () => { - describe('secondsToHumanDescription', () => { - const numsToResults: { - [aNumber: number]: string; - } = { - 1: '1 second', - 59: '59 seconds', - 60: '1 minute', - 119: '1 minute 59 seconds', - 120: '2 minutes', - 121: '2 minutes 1 second', - 122: '2 minutes 2 seconds', - }; - - const nums = Object.keys(numsToResults); - nums.forEach(aNum => { - const numInt = parseInt(aNum, 10); - it(`should work for ${aNum} seconds`, () => { - const expectedResult = numsToResults[numInt]; - expect(timeUtil.secondsToHumanDescription(numInt)).toEqual(expectedResult); - }); - }); - }); - describe('secondsToStopwatchTime', () => { - const numsToResults: { - [aNumber: number]: string; - } = { - 1: '00:01', - 59: '00:59', - 60: '01:00', - 119: '01:59', - 120: '02:00', - 121: '02:01', - 2701: '45:01', - }; - - const nums = Object.keys(numsToResults); - nums.forEach(aNum => { - const numInt = parseInt(aNum, 10); - it(`should work for ${aNum} seconds`, () => { - const expectedResult = numsToResults[numInt]; - expect(timeUtil.secondsToStopwatchTime(numInt)).toEqual(expectedResult); - }); - }); - }); -}); diff --git a/packages/instant/tsconfig.json b/packages/instant/tsconfig.json deleted file mode 100644 index 2b3c11c9f7..0000000000 --- a/packages/instant/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../tsconfig", - "compilerOptions": { - "outDir": "lib", - "rootDir": "src", - "jsx": "react", - "noImplicitAny": true, - "allowSyntheticDefaultImports": true, - "declaration": false, - "declarationMap": false, - "composite": false - }, - "include": ["./src/**/*"] -} diff --git a/packages/instant/tslint.json b/packages/instant/tslint.json deleted file mode 100644 index d43ee8da7e..0000000000 --- a/packages/instant/tslint.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "extends": ["@0x/tslint-config"], - "rules": { - "custom-no-magic-numbers": false, - "semicolon": [true, "always", "ignore-bound-class-methods"], - "max-classes-per-file": false, - "switch-default": false - } -} diff --git a/packages/instant/webpack.config.js b/packages/instant/webpack.config.js deleted file mode 100644 index d1f91a8f9d..0000000000 --- a/packages/instant/webpack.config.js +++ /dev/null @@ -1,216 +0,0 @@ -const childProcess = require('child_process'); -const ip = require('ip'); -const path = require('path'); -const RollbarSourceMapPlugin = require('rollbar-sourcemap-webpack-plugin'); -const webpack = require('webpack'); - -const GIT_SHA = childProcess - .execSync('git rev-parse HEAD') - .toString() - .trim(); - -const DISCHARGE_TARGETS_THAT_REQUIRED_HEAP = ['production', 'staging', 'dogfood']; -const getHeapConfigForDischargeTarget = dischargeTarget => { - return { - heapAnalyticsIdEnvName: - dischargeTarget === 'production' - ? 'INSTANT_HEAP_ANALYTICS_ID_PRODUCTION' - : 'INSTANT_HEAP_ANALYTICS_ID_DEVELOPMENT', - heapAnalyticsIdRequired: DISCHARGE_TARGETS_THAT_REQUIRED_HEAP.includes(dischargeTarget), - }; -}; - -const DISCHARGE_TARGETS_THAT_REQUIRE_ROLLBAR = ['production', 'staging', 'dogfood']; -const getRollbarConfigForDischargeTarget = dischargeTarget => { - if (DISCHARGE_TARGETS_THAT_REQUIRE_ROLLBAR.includes(dischargeTarget)) { - const rollbarSourceMapPublicPath = - dischargeTarget === 'production' - ? 'https://instant.0xproject.com' - : `http://0x-instant-${dischargeTarget}.s3-website-us-east-1.amazonaws.com`; - - return { - rollbarSourceMapPublicPath, - rollbarRequired: true, - }; - } - - return { - rollbarRequired: false, - }; -}; - -const ROLLBAR_CLIENT_TOKEN_ENV_VAR_NAME = 'INSTANT_ROLLBAR_CLIENT_TOKEN'; -const ROLLBAR_PUBLISH_TOKEN_ENV_VAR_NAME = 'INSTANT_ROLLBAR_PUBLISH_TOKEN'; -const getRollbarTokens = (dischargeTarget, rollbarRequired) => { - const clientToken = process.env[ROLLBAR_CLIENT_TOKEN_ENV_VAR_NAME]; - const publishToken = process.env[ROLLBAR_PUBLISH_TOKEN_ENV_VAR_NAME]; - - if (rollbarRequired) { - if (!clientToken) { - throw new Error( - `Rollbar client token required for ${dischargeTarget}, please set env var ${ROLLBAR_CLIENT_TOKEN_ENV_VAR_NAME}`, - ); - } - if (!publishToken) { - throw new Error( - `Rollbar publish token required for ${dischargeTarget}, please set env var ${ROLLBAR_PUBLISH_TOKEN_ENV_VAR_NAME}`, - ); - } - } - - return { clientToken, publishToken }; -}; - -const generateConfig = (dischargeTarget, heapConfigOptions, rollbarConfigOptions, nodeEnv) => { - const outputPath = process.env.WEBPACK_OUTPUT_PATH || 'umd/v3'; - - const { heapAnalyticsIdEnvName, heapAnalyticsIdRequired } = heapConfigOptions; - const heapAnalyticsId = process.env[heapAnalyticsIdEnvName]; - if (heapAnalyticsIdRequired && !heapAnalyticsId) { - throw new Error( - `Must define heap analytics id in ENV var ${heapAnalyticsIdEnvName} when building for ${dischargeTarget}`, - ); - } - const heapEnabled = heapAnalyticsId && (nodeEnv !== 'development' || process.env.INSTANT_HEAP_FORCE_DEVELOPMENT); - - const rollbarTokens = getRollbarTokens(dischargeTarget, rollbarConfigOptions.rollbarRequired); - const rollbarEnabled = - rollbarTokens.clientToken && (nodeEnv !== 'development' || process.env.INSTANT_ROLLBAR_FORCE_DEVELOPMENT); - - let rollbarPlugin; - if (rollbarConfigOptions.rollbarRequired) { - if (!rollbarEnabled || !rollbarTokens.publishToken || !rollbarConfigOptions.rollbarSourceMapPublicPath) { - throw new Error(`Rollbar required for ${dischargeTarget} but not configured`); - } - rollbarPlugin = new RollbarSourceMapPlugin({ - accessToken: rollbarTokens.publishToken, - version: GIT_SHA, - publicPath: rollbarConfigOptions.rollbarSourceMapPublicPath, - }); - } - - const infuraProjectId = - dischargeTarget === 'production' - ? process.env.INSTANT_INFURA_PROJECT_ID_PRODUCTION - : process.env.INSTANT_INFURA_PROJECT_ID_DEVELOPMENT; - - const fortmaticApiKey = - dischargeTarget === 'production' - ? process.env.INSTANT_FORTMATIC_API_KEY_PRODUCTION - : process.env.INSTANT_FORTMATIC_API_KEY_DEVELOPMENT; - - const envVars = { - GIT_SHA: JSON.stringify(GIT_SHA), - NPM_PACKAGE_VERSION: JSON.stringify(process.env.npm_package_version), - ROLLBAR_ENABLED: rollbarEnabled, - HEAP_ENABLED: heapEnabled, - INSTANT_FORTMATIC_API_KEY: JSON.stringify(fortmaticApiKey), - INSTANT_INFURA_PROJECT_ID: JSON.stringify(infuraProjectId), - }; - if (dischargeTarget) { - envVars.INSTANT_DISCHARGE_TARGET = JSON.stringify(dischargeTarget); - } - if (heapAnalyticsId) { - envVars.HEAP_ANALYTICS_ID = JSON.stringify(heapAnalyticsId); - } - if (rollbarTokens.clientToken) { - envVars.ROLLBAR_CLIENT_TOKEN = JSON.stringify(rollbarTokens.clientToken); - } - - const plugins = [ - new webpack.DefinePlugin({ - 'process.env': envVars, - }), - ]; - if (rollbarPlugin) { - plugins.push(rollbarPlugin); - } - - const config = { - entry: { - instant: './src/index.umd.ts', - }, - output: { - filename: '[name].js', - path: path.resolve(__dirname, outputPath), - library: 'zeroExInstant', - libraryTarget: 'umd', - }, - plugins, - devtool: 'source-map', - resolve: { - extensions: ['.js', '.json', '.ts', '.tsx'], - }, - // This supports the ethereumjs-vm dependency in `@0x/base-contract` - // The .wasm 'glue' code generated by Emscripten requires these node builtins, - // but won't actually use them in a web environment. We tell Webpack to not resolve those - // require statements since we know we won't need them. - externals: { - fs: true, - }, - module: { - rules: [ - { - test: /\.(ts|tsx)$/, - loader: 'awesome-typescript-loader', - }, - { - test: /\.svg$/, - loader: 'svg-react-loader', - }, - { - test: /\.js$/, - use: [ - { - loader: 'babel-loader', - options: { - plugins: ['transform-runtime'], - presets: [ - [ - 'env', - { - targets: { - chrome: 41, - }, - }, - ], - ], - }, - }, - { - loader: 'source-map-loader', - }, - ], - exclude: function(modulePath) { - return ( - /node_modules/.test(modulePath) && - /node_modules\/(core-js|lodash|react|websocket)/.test(modulePath) - ); - }, - }, - ], - }, - devServer: { - contentBase: path.join(__dirname, 'public'), - port: 5000, - host: '0.0.0.0', - after: () => { - if (config.devServer.host === '0.0.0.0') { - console.log( - `webpack-dev-server can be accessed externally at: http://${ip.address()}:${ - config.devServer.port - }`, - ); - } - }, - }, - }; - return config; -}; - -module.exports = (env, argv) => { - const dischargeTarget = env ? env.discharge_target : undefined; - const heapConfigOptions = getHeapConfigForDischargeTarget(dischargeTarget); - const rollbarConfigOptions = getRollbarConfigForDischargeTarget(dischargeTarget); - return generateConfig(dischargeTarget, heapConfigOptions, rollbarConfigOptions, argv.mode); -}; diff --git a/packages/json-schemas/.npmignore b/packages/json-schemas/.npmignore deleted file mode 100644 index ea588d4859..0000000000 --- a/packages/json-schemas/.npmignore +++ /dev/null @@ -1,9 +0,0 @@ -# Blacklist all files -.* -* -# Whitelist lib -!lib/**/* -# Blacklist tests and publish scripts -/lib/test/* -/lib/monorepo_scripts/ -# Package specific ignore diff --git a/packages/json-schemas/CHANGELOG.json b/packages/json-schemas/CHANGELOG.json deleted file mode 100644 index c8c72da14d..0000000000 --- a/packages/json-schemas/CHANGELOG.json +++ /dev/null @@ -1,706 +0,0 @@ -[ - { - "version": "5.2.0", - "changes": [ - { - "note": "Add `exchangeProxyMetaTransactionSchema`", - "pr": 2657 - } - ] - }, - { - "version": "5.1.0", - "changes": [ - { - "note": "Add geth eth_call properties to `CallData`", - "pr": 2620 - } - ], - "timestamp": 1594788383 - }, - { - "timestamp": 1592969527, - "version": "5.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1582623685, - "version": "5.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1581204851, - "version": "5.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1580988106, - "version": "5.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1579682890, - "version": "5.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1578272714, - "version": "5.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1576540892, - "version": "5.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1575931811, - "version": "5.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "5.0.0", - "changes": [ - { - "note": "All references to network ID have been removed, and references to chain ID have been introduced instead", - "pr": 2313 - }, - { - "note": "Add `eip712DomainSchema` schema", - "pr": 1742 - }, - { - "note": "Add required field `domain` to `order` and `zeroExTransaction` schemas", - "pr": 1742 - }, - { - "note": "Add `makerAssetData` and `takerAssetData` to `Order` schemas", - "pr": 1819 - }, - { - "note": "Add `expirationTimeSeconds` to `ZeroExTransaction` schema", - "pr": 1832 - } - ], - "timestamp": 1575296764 - }, - { - "version": "4.1.0-beta.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1575290197 - }, - { - "version": "4.1.0-beta.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1574030254 - }, - { - "version": "4.1.0-beta.1", - "changes": [ - { - "note": "All references to network ID have been removed, and references to chain ID have been introduced instead", - "pr": 2313 - } - ], - "timestamp": 1573159180 - }, - { - "version": "4.1.0-beta.0", - "changes": [ - { - "note": "Add `eip712DomainSchema` schema", - "pr": 1742 - }, - { - "note": "Add required field `domain` to `order` and `zeroExTransaction` schemas", - "pr": 1742 - }, - { - "note": "Add `makerAssetData` and `takerAssetData` to `Order` schemas", - "pr": 1819 - }, - { - "note": "Add `expirationTimeSeconds` to `ZeroExTransaction` schema", - "pr": 1832 - } - ], - "timestamp": 1570135330 - }, - { - "timestamp": 1568744790, - "version": "4.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1567521715, - "version": "4.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "4.0.0", - "changes": [ - { - "note": "Removed @0x/order-watcher" - } - ], - "timestamp": 1566446343 - }, - { - "timestamp": 1565296576, - "version": "3.1.13", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1564604963, - "version": "3.1.12", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.1.11", - "changes": [ - { - "note": "permit mixed-case addresses" - } - ], - "timestamp": 1563957393 - }, - { - "timestamp": 1563006338, - "version": "3.0.11", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1557507213, - "version": "3.0.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1554997931 - }, - { - "timestamp": 1553183790, - "version": "3.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1553091633, - "version": "3.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551479279, - "version": "3.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551220833, - "version": "3.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551130135, - "version": "3.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1549733923, - "version": "3.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1549547375 - }, - { - "timestamp": 1549452781, - "version": "3.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.0.0", - "changes": [ - { - "note": "Upgrade the bignumber.js to v8.0.2", - "pr": 1517 - }, - { - "note": "Add `verifyingContractAddress` to `zeroExTransactionSchema`", - "pr": 1576 - } - ], - "timestamp": 1549373905 - }, - { - "timestamp": 1547561734, - "version": "2.1.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547225310, - "version": "2.1.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547040760, - "version": "2.1.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.1.4", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544739608 - }, - { - "version": "2.1.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544570656 - }, - { - "timestamp": 1542821676, - "version": "2.1.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542208198, - "version": "2.1.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.1.0", - "changes": [ - { - "note": "Improve schemas by enforcing that amounts that must be whole numbers (e.g Order asset amounts) no longer allow decimal amounts", - "pr": 1173 - }, - { - "note": "Add schemas from @0x/connect", - "pr": 1250 - } - ], - "timestamp": 1542028948 - }, - { - "version": "2.0.0", - "changes": [ - { - "note": "Convert all schemas to JSON files so that they can be used with `json-schema` implemenations in other programming languages.", - "pr": 1145 - } - ], - "timestamp": 1539871071 - }, - { - "timestamp": 1538693146, - "version": "1.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1538475601, - "version": "1.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1538157789, - "version": "1.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537907159, - "version": "1.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537875740, - "version": "1.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537541580, - "version": "1.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1536142250, - "version": "1.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.1-rc.6", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1535377027 - }, - { - "version": "1.0.1-rc.5", - "changes": [ - { - "note": "Update incorrect relayer api fee recipients response schema", - "pr": 974 - } - ], - "timestamp": 1535133899 - }, - { - "version": "1.0.1-rc.4", - "changes": [ - { - "note": "Allow for additional properties in txData schema", - "pr": 938 - }, - { - "note": "Change hexSchema to match `0x`", - "pr": 937 - }, - { - "note": "Upgrade Relayer API schemas for relayer API V2", - "pr": 916 - } - ], - "timestamp": 1534210131 - }, - { - "version": "1.0.1-rc.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1532619515 - }, - { - "version": "1.0.1-rc.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1532614997 - }, - { - "version": "1.0.1-rc.1", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1532605697 - }, - { - "timestamp": 1532357734, - "version": "1.0.0", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532043000, - "version": "1.0.0-rc.1", - "changes": [ - { - "note": "Update schemas for V2 or 0x Protocol", - "pr": 615 - }, - { - "note": "Added CallData schema", - "pr": 821 - }, - { - "note": "Update CallData schema id to CallData", - "pr": 894 - } - ] - }, - { - "timestamp": 1531919263, - "version": "0.8.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1531149657, - "version": "0.8.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1529397769, - "version": "0.8.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.8.0", - "changes": [ - { - "note": "Update Order & SignedOrder schemas, remove ECSignature schema and add Hex schema as part of V2 upgrades", - "pr": 615 - } - ], - "timestamp": 1527008794 - }, - { - "timestamp": 1527008794, - "version": "0.7.24", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1525477860, - "version": "0.7.23", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1525428773, - "version": "0.7.22", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1524044013, - "version": "0.7.21", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1523462196, - "version": "0.7.20", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1522673609, - "version": "0.7.19", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1522658513, - "version": "0.7.18", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.7.13", - "changes": [ - { - "note": " Fix publishing issue where .npmignore was not properly excluding undesired content", - "pr": 389 - } - ], - "timestamp": 1518102000 - }, - { - "version": "0.7.0", - "changes": [ - { - "note": "Rename `subscriptionOptsSchema` to `blockRangeSchema`", - "pr": 272 - } - ], - "timestamp": 1513695600 - }, - { - "version": "0.6.7", - "changes": [ - { - "note": "Re-publish JSON-schema previously published under NPM package 0x-json-schemas" - } - ], - "timestamp": 1510585200 - } -] diff --git a/packages/json-schemas/CHANGELOG.md b/packages/json-schemas/CHANGELOG.md deleted file mode 100644 index 605cd67733..0000000000 --- a/packages/json-schemas/CHANGELOG.md +++ /dev/null @@ -1,299 +0,0 @@ - - -CHANGELOG - -## v5.1.0 - _July 15, 2020_ - - * Add geth eth_call properties to `CallData` (#2620) - -## v5.0.8 - _June 24, 2020_ - - * Dependencies updated - -## v5.0.7 - _February 25, 2020_ - - * Dependencies updated - -## v5.0.6 - _February 8, 2020_ - - * Dependencies updated - -## v5.0.5 - _February 6, 2020_ - - * Dependencies updated - -## v5.0.4 - _January 22, 2020_ - - * Dependencies updated - -## v5.0.3 - _January 6, 2020_ - - * Dependencies updated - -## v5.0.2 - _December 17, 2019_ - - * Dependencies updated - -## v5.0.1 - _December 9, 2019_ - - * Dependencies updated - -## v5.0.0 - _December 2, 2019_ - - * All references to network ID have been removed, and references to chain ID have been introduced instead (#2313) - * Add `eip712DomainSchema` schema (#1742) - * Add required field `domain` to `order` and `zeroExTransaction` schemas (#1742) - * Add `makerAssetData` and `takerAssetData` to `Order` schemas (#1819) - * Add `expirationTimeSeconds` to `ZeroExTransaction` schema (#1832) - -## v4.1.0-beta.3 - _December 2, 2019_ - - * Dependencies updated - -## v4.1.0-beta.2 - _November 17, 2019_ - - * Dependencies updated - -## v4.1.0-beta.1 - _November 7, 2019_ - - * All references to network ID have been removed, and references to chain ID have been introduced instead (#2313) - -## v4.1.0-beta.0 - _October 3, 2019_ - - * Add `eip712DomainSchema` schema (#1742) - * Add required field `domain` to `order` and `zeroExTransaction` schemas (#1742) - * Add `makerAssetData` and `takerAssetData` to `Order` schemas (#1819) - * Add `expirationTimeSeconds` to `ZeroExTransaction` schema (#1832) - -## v4.0.2 - _September 17, 2019_ - - * Dependencies updated - -## v4.0.1 - _September 3, 2019_ - - * Dependencies updated - -## v4.0.0 - _August 22, 2019_ - - * Removed @0x/order-watcher - -## v3.1.13 - _August 8, 2019_ - - * Dependencies updated - -## v3.1.12 - _July 31, 2019_ - - * Dependencies updated - -## v3.1.11 - _July 24, 2019_ - - * permit mixed-case addresses - -## v3.0.11 - _July 13, 2019_ - - * Dependencies updated - -## v3.0.10 - _May 10, 2019_ - - * Dependencies updated - -## v3.0.9 - _April 11, 2019_ - - * Dependencies updated - -## v3.0.8 - _March 21, 2019_ - - * Dependencies updated - -## v3.0.7 - _March 20, 2019_ - - * Dependencies updated - -## v3.0.6 - _March 1, 2019_ - - * Dependencies updated - -## v3.0.5 - _February 26, 2019_ - - * Dependencies updated - -## v3.0.4 - _February 25, 2019_ - - * Dependencies updated - -## v3.0.3 - _February 9, 2019_ - - * Dependencies updated - -## v3.0.2 - _February 7, 2019_ - - * Dependencies updated - -## v3.0.1 - _February 6, 2019_ - - * Dependencies updated - -## v3.0.0 - _February 5, 2019_ - - * Upgrade the bignumber.js to v8.0.2 (#1517) - * Add `verifyingContractAddress` to `zeroExTransactionSchema` (#1576) - -## v2.1.7 - _January 15, 2019_ - - * Dependencies updated - -## v2.1.6 - _January 11, 2019_ - - * Dependencies updated - -## v2.1.5 - _January 9, 2019_ - - * Dependencies updated - -## v2.1.4 - _December 13, 2018_ - - * Dependencies updated - -## v2.1.3 - _December 11, 2018_ - - * Dependencies updated - -## v2.1.2 - _November 21, 2018_ - - * Dependencies updated - -## v2.1.1 - _November 14, 2018_ - - * Dependencies updated - -## v2.1.0 - _November 12, 2018_ - - * Improve schemas by enforcing that amounts that must be whole numbers (e.g Order asset amounts) no longer allow decimal amounts (#1173) - * Add schemas from @0x/connect (#1250) - -## v2.0.0 - _October 18, 2018_ - - * Convert all schemas to JSON files so that they can be used with `json-schema` implemenations in other programming languages. (#1145) - -## v1.0.7 - _October 4, 2018_ - - * Dependencies updated - -## v1.0.6 - _October 2, 2018_ - - * Dependencies updated - -## v1.0.5 - _September 28, 2018_ - - * Dependencies updated - -## v1.0.4 - _September 25, 2018_ - - * Dependencies updated - -## v1.0.3 - _September 25, 2018_ - - * Dependencies updated - -## v1.0.2 - _September 21, 2018_ - - * Dependencies updated - -## v1.0.1 - _September 5, 2018_ - - * Dependencies updated - -## v1.0.1-rc.6 - _August 27, 2018_ - - * Dependencies updated - -## v1.0.1-rc.5 - _August 24, 2018_ - - * Update incorrect relayer api fee recipients response schema (#974) - -## v1.0.1-rc.4 - _August 14, 2018_ - - * Allow for additional properties in txData schema (#938) - * Change hexSchema to match `0x` (#937) - * Upgrade Relayer API schemas for relayer API V2 (#916) - -## v1.0.1-rc.3 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.1-rc.2 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.1-rc.1 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.0 - _July 23, 2018_ - - * Dependencies updated - -## v1.0.0-rc.1 - _July 19, 2018_ - - * Update schemas for V2 or 0x Protocol (#615) - * Added CallData schema (#821) - * Update CallData schema id to CallData (#894) - -## v0.8.3 - _July 18, 2018_ - - * Dependencies updated - -## v0.8.2 - _July 9, 2018_ - - * Dependencies updated - -## v0.8.1 - _June 19, 2018_ - - * Dependencies updated - -## v0.8.0 - _May 22, 2018_ - - * Update Order & SignedOrder schemas, remove ECSignature schema and add Hex schema as part of V2 upgrades (#615) - -## v0.7.24 - _May 22, 2018_ - - * Dependencies updated - -## v0.7.23 - _May 4, 2018_ - - * Dependencies updated - -## v0.7.22 - _May 4, 2018_ - - * Dependencies updated - -## v0.7.21 - _April 18, 2018_ - - * Dependencies updated - -## v0.7.20 - _April 11, 2018_ - - * Dependencies updated - -## v0.7.19 - _April 2, 2018_ - - * Dependencies updated - -## v0.7.18 - _April 2, 2018_ - - * Dependencies updated - -## v0.7.13 - _February 8, 2018_ - - * Fix publishing issue where .npmignore was not properly excluding undesired content (#389) - -## v0.7.0 - _December 19, 2017_ - - * Rename `subscriptionOptsSchema` to `blockRangeSchema` (#272) - -## v0.6.7 - _November 13, 2017_ - - * Re-publish JSON-schema previously published under NPM package 0x-json-schemas diff --git a/packages/json-schemas/README.md b/packages/json-schemas/README.md deleted file mode 100644 index 71138df86d..0000000000 --- a/packages/json-schemas/README.md +++ /dev/null @@ -1,83 +0,0 @@ -## @0x/json-schemas - -Contains 0x-related json schemas - -### Read the [Documentation](https://0x.org/docs/tools/json-schemas). - -## Installation - -```bash -yarn add @0x/json-schemas -``` - -**Import** - -```typescript -import { SchemaValidator, ValidatorResult, schemas } from '@0x/json-schemas'; -``` - -or - -```javascript -var schemas = require('@0x/json-schemas').schemas; -``` - -If your project is in [TypeScript](https://www.typescriptlang.org/), add the following to your `tsconfig.json`: - -```json -"compilerOptions": { - "typeRoots": ["node_modules/@0x/typescript-typings/types", "node_modules/@types"], -} -``` - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install dependencies - -If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: - -```bash -yarn config set workspaces-experimental true -``` - -Then install dependencies - -```bash -yarn install -``` - -### Build - -To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory: - -```bash -PKG=@0x/json-schemas yarn build -``` - -Or continuously rebuild on change: - -```bash -PKG=@0x/json-schemas yarn watch -``` - -### Clean - -```bash -yarn clean -``` - -### Lint - -```bash -yarn lint -``` - -### Run Tests - -```bash -yarn test -``` diff --git a/packages/json-schemas/coverage/.gitkeep b/packages/json-schemas/coverage/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/json-schemas/docs/reference.mdx b/packages/json-schemas/docs/reference.mdx deleted file mode 100644 index 4edbcbe0d0..0000000000 --- a/packages/json-schemas/docs/reference.mdx +++ /dev/null @@ -1,85 +0,0 @@ -# Class: SchemaValidator - -A validator for [JSON-schemas](http://json-schema.org/) - - -## Constructors - - - -\+ **new SchemaValidator**(): *[SchemaValidator](#class-schemavalidator)* - -*Defined in [schema_validator.ts:15](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/json-schemas/src/schema_validator.ts#L15)* - -Instantiates a SchemaValidator instance - -**Returns:** *[SchemaValidator](#class-schemavalidator)* - -## Methods - -### addSchema - -▸ **addSchema**(`schema`: `Schema`): *void* - -*Defined in [schema_validator.ts:32](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/json-schemas/src/schema_validator.ts#L32)* - -Add a schema to the validator. All schemas and sub-schemas must be added to -the validator before the `validate` and `isValid` methods can be called with -instances of that schema. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`schema` | `Schema` | The schema to add | - -**Returns:** *void* - -___ - -### isValid - -▸ **isValid**(`instance`: any, `schema`: `Schema`): *boolean* - -*Defined in [schema_validator.ts:57](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/json-schemas/src/schema_validator.ts#L57)* - -Check whether an instance properly adheres to a JSON schema - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`instance` | any | JS object in question | -`schema` | `Schema` | Schema to check against | - -**Returns:** *boolean* - -Whether or not the instance adheres to the schema - -___ - -### validate - -▸ **validate**(`instance`: any, `schema`: `Schema`): *`ValidatorResult`* - -*Defined in [schema_validator.ts:46](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/json-schemas/src/schema_validator.ts#L46)* - -Validate the JS object conforms to a specific JSON schema - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`instance` | any | JS object in question | -`schema` | `Schema` | Schema to check against | - -**Returns:** *`ValidatorResult`* - -The results of the validation - -
- - - -
- diff --git a/packages/json-schemas/package.json b/packages/json-schemas/package.json deleted file mode 100644 index 7a5b1b6c60..0000000000 --- a/packages/json-schemas/package.json +++ /dev/null @@ -1,74 +0,0 @@ -{ - "name": "@0x/json-schemas", - "version": "5.1.0", - "engines": { - "node": ">=6.12" - }, - "description": "0x-related json schemas", - "main": "lib/src/index.js", - "types": "lib/src/index.d.ts", - "scripts": { - "build": "tsc -b", - "build:ci": "yarn build", - "lint": "tslint --format stylish --project . --exclude **/schemas/**/*", - "fix": "tslint --fix --format stylish --project . --exclude **/schemas/**/*", - "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", - "run_mocha": "mocha --require source-map-support/register --require make-promises-safe lib/test/**/*_test.js --exit", - "clean": "shx rm -rf lib test_temp generated_docs", - "diff_docs": "git diff --exit-code ./docs", - "s3:sync_md_docs": "aws s3 sync ./docs s3://docs-markdown/${npm_package_name}/v${npm_package_version} --profile 0xproject --region us-east-1 --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers", - "docs:md": "ts-doc-gen --sourceDir='$PROJECT_FILES' --output=$MD_FILE_DIR --fileExtension=mdx --tsconfig=./typedoc-tsconfig.json", - "docs:json": "typedoc --excludePrivate --excludeExternals --excludeProtected --ignoreCompilerErrors --target ES5 --tsconfig typedoc-tsconfig.json --json $JSON_FILE_PATH $PROJECT_FILES" - }, - "config": { - "postpublish": { - "assets": [], - "docOmitExports": [ - "schemas" - ] - } - }, - "repository": { - "type": "git", - "url": "https://github.com/0xProject/0x-monorepo.git" - }, - "author": "", - "license": "Apache-2.0", - "bugs": { - "url": "https://github.com/0xProject/0x-monorepo/issues" - }, - "homepage": "https://github.com/0xProject/0x-monorepo/packages/json-schemas/README.md", - "dependencies": { - "@0x/typescript-typings": "^5.1.1", - "@types/node": "12.12.54", - "jsonschema": "^1.2.0", - "lodash.values": "^4.3.0" - }, - "devDependencies": { - "@0x/ts-doc-gen": "^0.0.22", - "@0x/tslint-config": "^4.1.0", - "@0x/utils": "^5.5.1", - "@types/lodash.foreach": "^4.5.3", - "@types/lodash.values": "^4.3.3", - "@types/mocha": "^5.2.7", - "chai": "^4.0.1", - "dirty-chai": "^2.0.1", - "lodash.foreach": "^4.5.0", - "make-promises-safe": "^1.1.0", - "mocha": "^6.2.0", - "npm-run-all": "^4.1.2", - "nyc": "^11.0.1", - "shx": "^0.2.2", - "tslint": "5.11.0", - "typedoc": "^0.15.0", - "typescript": "3.0.1" - }, - "publishConfig": { - "access": "public" - }, - "gitHead": "4f91bfd907996b2f4dd383778b50c479c2602b56" -} diff --git a/packages/json-schemas/schemas/address_schema.json b/packages/json-schemas/schemas/address_schema.json deleted file mode 100644 index db49edc557..0000000000 --- a/packages/json-schemas/schemas/address_schema.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "id": "/addressSchema", - "type": "string", - "pattern": "^0x[0-9a-fA-F]{40}$" -} diff --git a/packages/json-schemas/schemas/asset_pairs_request_opts_schema.json b/packages/json-schemas/schemas/asset_pairs_request_opts_schema.json deleted file mode 100644 index fad0bd3719..0000000000 --- a/packages/json-schemas/schemas/asset_pairs_request_opts_schema.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "id": "/AssetPairsRequestOptsSchema", - "type": "object", - "properties": { - "assetDataA": { "$ref": "/hexSchema" }, - "assetDataB": { "$ref": "/hexSchema" } - } -} diff --git a/packages/json-schemas/schemas/block_param_schema.json b/packages/json-schemas/schemas/block_param_schema.json deleted file mode 100644 index ed4dd1e875..0000000000 --- a/packages/json-schemas/schemas/block_param_schema.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "id": "/blockParamSchema", - "oneOf": [ - { - "type": "number" - }, - { - "enum": ["latest", "earliest", "pending"] - } - ] -} diff --git a/packages/json-schemas/schemas/block_range_schema.json b/packages/json-schemas/schemas/block_range_schema.json deleted file mode 100644 index b142946490..0000000000 --- a/packages/json-schemas/schemas/block_range_schema.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "id": "/blockRangeSchema", - "properties": { - "fromBlock": { "$ref": "/blockParamSchema" }, - "toBlock": { "$ref": "/blockParamSchema" } - }, - "type": "object" -} diff --git a/packages/json-schemas/schemas/call_data_schema.json b/packages/json-schemas/schemas/call_data_schema.json deleted file mode 100644 index cc531f40ed..0000000000 --- a/packages/json-schemas/schemas/call_data_schema.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "id": "/callDataSchema", - "properties": { - "from": { "$ref": "/addressSchema" }, - "to": { "$ref": "/addressSchema" }, - "value": { - "oneOf": [{ "$ref": "/numberSchema" }, { "$ref": "/jsNumberSchema" }] - }, - "gas": { - "oneOf": [{ "$ref": "/numberSchema" }, { "$ref": "/jsNumberSchema" }] - }, - "gasPrice": { - "oneOf": [{ "$ref": "/numberSchema" }, { "$ref": "/jsNumberSchema" }] - }, - "data": { - "type": "string", - "pattern": "^0x[0-9a-f]*$" - }, - "nonce": { - "type": "number", - "minimum": 0 - }, - "overrides": { - "type": "object", - "additionalProperties": { - "type": "object", - "properties": { - "code": { - "type": "string", - "pattern": "^0x[0-9a-fA-F]*$" - }, - "nonce": { - "oneOf": [{ "$ref": "/wholeNumberSchema" }] - }, - "balance": { - "oneOf": [{ "$ref": "/wholeNumberSchema" }] - } - } - } - } - }, - "required": [], - "type": "object", - "additionalProperties": false -} diff --git a/packages/json-schemas/schemas/ec_signature_parameter_schema.json b/packages/json-schemas/schemas/ec_signature_parameter_schema.json deleted file mode 100644 index 0c08ec2403..0000000000 --- a/packages/json-schemas/schemas/ec_signature_parameter_schema.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "id": "/ecSignatureParameterSchema", - "type": "string", - "pattern": "^0[xX][0-9A-Fa-f]{64}$" -} diff --git a/packages/json-schemas/schemas/ec_signature_schema.json b/packages/json-schemas/schemas/ec_signature_schema.json deleted file mode 100644 index 52ccfe7bb4..0000000000 --- a/packages/json-schemas/schemas/ec_signature_schema.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "id": "/ecSignatureSchema", - "properties": { - "v": { - "type": "number", - "minimum": 27, - "maximum": 28 - }, - "r": { "$ref": "/ecSignatureParameterSchema" }, - "s": { "$ref": "/ecSignatureParameterSchema" } - }, - "required": ["v", "r", "s"], - "type": "object" -} diff --git a/packages/json-schemas/schemas/eip712_domain_schema.json b/packages/json-schemas/schemas/eip712_domain_schema.json deleted file mode 100644 index 268254fff3..0000000000 --- a/packages/json-schemas/schemas/eip712_domain_schema.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "id": "/eip712DomainSchema", - "properties": { - "name": { - "type": "string" - }, - "version": { - "type": "version" - }, - "chainId": { - "type": "number" - }, - "verifyingContract": { - "$ref": "/addressSchema" - } - }, - "required": [ - "chainId", - "verifyingContract" - ], - "type": "object" -} diff --git a/packages/json-schemas/schemas/eip712_typed_data_schema.json b/packages/json-schemas/schemas/eip712_typed_data_schema.json deleted file mode 100644 index 6409819fc6..0000000000 --- a/packages/json-schemas/schemas/eip712_typed_data_schema.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "id": "/eip712TypedDataSchema", - "type": "object", - "properties": { - "types": { - "type": "object", - "properties": { - "EIP712Domain": { "type": "array" } - }, - "additionalProperties": { - "type": "array", - "items": { - "type": "object", - "properties": { - "name": { "type": "string" }, - "type": { "type": "string" } - }, - "required": ["name", "type"] - } - }, - "required": ["EIP712Domain"] - }, - "primaryType": { "type": "string" }, - "domain": { "$ref": "/eip712DomainSchema" }, - "message": { "type": "object" } - }, - "required": ["types", "primaryType", "domain", "message"] -} diff --git a/packages/json-schemas/schemas/exchange_proxy_meta_transaction_schema.json b/packages/json-schemas/schemas/exchange_proxy_meta_transaction_schema.json deleted file mode 100644 index 7c9a5a7d98..0000000000 --- a/packages/json-schemas/schemas/exchange_proxy_meta_transaction_schema.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "id": "/exchangeProxyMetaTransactionSchema", - "properties": { - "signer": { "$ref": "/addressSchema" }, - "sender": { "$ref": "/addressSchema" }, - "minGasPrice": { "$ref": "/wholeNumberSchema" }, - "maxGasPrice": { "$ref": "/wholeNumberSchema" }, - "expirationTimeSeconds": { "$ref": "/wholeNumberSchema" }, - "salt": { "$ref": "/wholeNumberSchema" }, - "callData": { "$ref": "/hexSchema" }, - "value": { "$ref": "/wholeNumberSchema" }, - "feeToken": { "$ref": "/addressSchema" }, - "feeAmount": { "$ref": "/wholeNumberSchema" }, - "domain": { "$ref": "/eip712DomainSchema" } - }, - "required": [ - "signer", - "sender", - "minGasPrice", - "maxGasPrice", - "expirationTimeSeconds", - "salt", - "callData", - "value", - "feeToken", - "feeAmount", - "domain" - ], - "type": "object" -} diff --git a/packages/json-schemas/schemas/hex_schema.json b/packages/json-schemas/schemas/hex_schema.json deleted file mode 100644 index f37815d5bd..0000000000 --- a/packages/json-schemas/schemas/hex_schema.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "id": "/hexSchema", - "type": "string", - "pattern": "^0x(([0-9a-f][0-9a-f])+)?$" -} diff --git a/packages/json-schemas/schemas/index_filter_values_schema.json b/packages/json-schemas/schemas/index_filter_values_schema.json deleted file mode 100644 index bec00d79e8..0000000000 --- a/packages/json-schemas/schemas/index_filter_values_schema.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "id": "/indexFilterValuesSchema", - "additionalProperties": { - "oneOf": [{ "$ref": "/numberSchema" }, { "$ref": "/addressSchema" }, { "$ref": "/orderHashSchema" }] - }, - "type": "object" -} diff --git a/packages/json-schemas/schemas/js_number_schema.json b/packages/json-schemas/schemas/js_number_schema.json deleted file mode 100644 index 7df1c47472..0000000000 --- a/packages/json-schemas/schemas/js_number_schema.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "id": "/jsNumberSchema", - "type": "number", - "minimum": 0 -} diff --git a/packages/json-schemas/schemas/number_schema.json b/packages/json-schemas/schemas/number_schema.json deleted file mode 100644 index a48f3e8cff..0000000000 --- a/packages/json-schemas/schemas/number_schema.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "id": "/numberSchema", - "type": "string", - "pattern": "^\\d+(\\.\\d+)?$" -} diff --git a/packages/json-schemas/schemas/order_cancel_schema.json b/packages/json-schemas/schemas/order_cancel_schema.json deleted file mode 100644 index 8d0999941a..0000000000 --- a/packages/json-schemas/schemas/order_cancel_schema.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "id": "/orderCancellationRequestsSchema", - "type": "array", - "items": { - "properties": { - "order": { "$ref": "/orderSchema" }, - "takerTokenCancelAmount": { "$ref": "/wholeNumberSchema" } - }, - "required": ["order", "takerTokenCancelAmount"], - "type": "object" - } -} diff --git a/packages/json-schemas/schemas/order_config_request_schema.json b/packages/json-schemas/schemas/order_config_request_schema.json deleted file mode 100644 index 19b043e7f9..0000000000 --- a/packages/json-schemas/schemas/order_config_request_schema.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "id": "/OrderConfigRequestSchema", - "type": "object", - "properties": { - "makerAddress": { "$ref": "/addressSchema" }, - "takerAddress": { "$ref": "/addressSchema" }, - "makerAssetAmount": { "$ref": "/wholeNumberSchema" }, - "takerAssetAmount": { "$ref": "/wholeNumberSchema" }, - "makerAssetData": { "$ref": "/hexSchema" }, - "takerAssetData": { "$ref": "/hexSchema" }, - "exchangeAddress": { "$ref": "/addressSchema" }, - "expirationTimeSeconds": { "$ref": "/wholeNumberSchema" } - }, - "required": [ - "makerAddress", - "takerAddress", - "makerAssetAmount", - "takerAssetAmount", - "makerAssetData", - "takerAssetData", - "exchangeAddress", - "expirationTimeSeconds" - ] -} diff --git a/packages/json-schemas/schemas/order_fill_or_kill_requests_schema.json b/packages/json-schemas/schemas/order_fill_or_kill_requests_schema.json deleted file mode 100644 index 73bbf20bb1..0000000000 --- a/packages/json-schemas/schemas/order_fill_or_kill_requests_schema.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "id": "/orderFillOrKillRequestsSchema", - "type": "array", - "items": { - "properties": { - "signedOrder": { "$ref": "/signedOrderSchema" }, - "fillTakerAmount": { "$ref": "/wholeNumberSchema" } - }, - "required": ["signedOrder", "fillTakerAmount"], - "type": "object" - } -} diff --git a/packages/json-schemas/schemas/order_fill_requests_schema.json b/packages/json-schemas/schemas/order_fill_requests_schema.json deleted file mode 100644 index d06fb19a29..0000000000 --- a/packages/json-schemas/schemas/order_fill_requests_schema.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "id": "/orderFillRequestsSchema", - "type": "array", - "items": { - "properties": { - "signedOrder": { "$ref": "/signedOrderSchema" }, - "takerTokenFillAmount": { "$ref": "/wholeNumberSchema" } - }, - "required": ["signedOrder", "takerTokenFillAmount"], - "type": "object" - } -} diff --git a/packages/json-schemas/schemas/order_hash_schema.json b/packages/json-schemas/schemas/order_hash_schema.json deleted file mode 100644 index 4a770579fc..0000000000 --- a/packages/json-schemas/schemas/order_hash_schema.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "id": "/orderHashSchema", - "type": "string", - "pattern": "^0x[0-9a-fA-F]{64}$" -} diff --git a/packages/json-schemas/schemas/order_schema.json b/packages/json-schemas/schemas/order_schema.json deleted file mode 100644 index aae83c81c2..0000000000 --- a/packages/json-schemas/schemas/order_schema.json +++ /dev/null @@ -1,72 +0,0 @@ -{ - "id": "/orderSchema", - "properties": { - "makerAddress": { - "$ref": "/addressSchema" - }, - "takerAddress": { - "$ref": "/addressSchema" - }, - "makerFee": { - "$ref": "/wholeNumberSchema" - }, - "takerFee": { - "$ref": "/wholeNumberSchema" - }, - "senderAddress": { - "$ref": "/addressSchema" - }, - "makerAssetAmount": { - "$ref": "/wholeNumberSchema" - }, - "takerAssetAmount": { - "$ref": "/wholeNumberSchema" - }, - "makerAssetData": { - "$ref": "/hexSchema" - }, - "takerAssetData": { - "$ref": "/hexSchema" - }, - "makerFeeAssetData": { - "$ref": "/hexSchema" - }, - "takerFeeAssetData": { - "$ref": "/hexSchema" - }, - "salt": { - "$ref": "/wholeNumberSchema" - }, - "feeRecipientAddress": { - "$ref": "/addressSchema" - }, - "expirationTimeSeconds": { - "$ref": "/wholeNumberSchema" - }, - "chainId": { - "type": "number" - }, - "exchangeAddress": { - "$ref": "/addressSchema" - } - }, - "required": [ - "makerAddress", - "takerAddress", - "makerFee", - "takerFee", - "senderAddress", - "makerAssetAmount", - "takerAssetAmount", - "makerAssetData", - "takerAssetData", - "makerFeeAssetData", - "takerFeeAssetData", - "salt", - "feeRecipientAddress", - "expirationTimeSeconds", - "chainId", - "exchangeAddress" - ], - "type": "object" -} diff --git a/packages/json-schemas/schemas/orderbook_request_schema.json b/packages/json-schemas/schemas/orderbook_request_schema.json deleted file mode 100644 index 5ce6e8ab0d..0000000000 --- a/packages/json-schemas/schemas/orderbook_request_schema.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "id": "/OrderbookRequestSchema", - "type": "object", - "properties": { - "baseAssetData": { "$ref": "/hexSchema" }, - "quoteAssetData": { "$ref": "/hexSchema" } - }, - "required": ["baseAssetData", "quoteAssetData"] -} diff --git a/packages/json-schemas/schemas/orders_request_opts_schema.json b/packages/json-schemas/schemas/orders_request_opts_schema.json deleted file mode 100644 index 05f486930d..0000000000 --- a/packages/json-schemas/schemas/orders_request_opts_schema.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "id": "/OrdersRequestOptsSchema", - "type": "object", - "properties": { - "makerAssetProxyId": { - "$ref": "/hexSchema" - }, - "takerAssetProxyId": { - "$ref": "/hexSchema" - }, - "makerAssetAddress": { - "$ref": "/addressSchema" - }, - "takerAssetAddress": { - "$ref": "/addressSchema" - }, - "exchangeAddress": { - "$ref": "/addressSchema" - }, - "senderAddress": { - "$ref": "/addressSchema" - }, - "makerAssetData": { - "$ref": "/hexSchema" - }, - "takerAssetData": { - "$ref": "/hexSchema" - }, - "traderAssetData": { - "$ref": "/hexSchema" - }, - "makerFeeAssetData": { - "$ref": "/hexSchema" - }, - "takerFeeAssetData": { - "$ref": "/hexSchema" - }, - "makerAddress": { - "$ref": "/addressSchema" - }, - "takerAddress": { - "$ref": "/addressSchema" - }, - "traderAddress": { - "$ref": "/addressSchema" - }, - "feeRecipientAddress": { - "$ref": "/addressSchema" - } - } -} diff --git a/packages/json-schemas/schemas/orders_schema.json b/packages/json-schemas/schemas/orders_schema.json deleted file mode 100644 index 1e1c6a8751..0000000000 --- a/packages/json-schemas/schemas/orders_schema.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "id": "/ordersSchema", - "type": "array", - "items": { "$ref": "/orderSchema" } -} diff --git a/packages/json-schemas/schemas/paged_request_opts_schema.json b/packages/json-schemas/schemas/paged_request_opts_schema.json deleted file mode 100644 index f143c28b0f..0000000000 --- a/packages/json-schemas/schemas/paged_request_opts_schema.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "id": "/PagedRequestOptsSchema", - "type": "object", - "properties": { - "page": { "type": "number" }, - "perPage": { "type": "number" } - } -} diff --git a/packages/json-schemas/schemas/paginated_collection_schema.json b/packages/json-schemas/schemas/paginated_collection_schema.json deleted file mode 100644 index 9dcedf5b47..0000000000 --- a/packages/json-schemas/schemas/paginated_collection_schema.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "id": "/paginatedCollectionSchema", - "type": "object", - "properties": { - "total": { "type": "number" }, - "perPage": { "type": "number" }, - "page": { "type": "number" } - }, - "required": ["total", "perPage", "page"] -} diff --git a/packages/json-schemas/schemas/relayer_api_asset_data_pairs_response_schema.json b/packages/json-schemas/schemas/relayer_api_asset_data_pairs_response_schema.json deleted file mode 100644 index d1150d3dbc..0000000000 --- a/packages/json-schemas/schemas/relayer_api_asset_data_pairs_response_schema.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "id": "/relayerApiAssetDataPairsResponseSchema", - "type": "object", - "allOf": [ - { "$ref": "/paginatedCollectionSchema" }, - { - "properties": { - "records": { "$ref": "/relayerApiAssetDataPairsSchema" } - }, - "required": ["records"] - } - ] -} diff --git a/packages/json-schemas/schemas/relayer_api_asset_data_pairs_schema.json b/packages/json-schemas/schemas/relayer_api_asset_data_pairs_schema.json deleted file mode 100644 index 62d4745b8c..0000000000 --- a/packages/json-schemas/schemas/relayer_api_asset_data_pairs_schema.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "id": "/relayerApiAssetDataPairsSchema", - "type": "array", - "items": { - "properties": { - "assetDataA": { "$ref": "/relayerApiAssetDataTradeInfoSchema" }, - "assetDataB": { "$ref": "/relayerApiAssetDataTradeInfoSchema" } - }, - "required": ["assetDataA", "assetDataB"], - "type": "object" - } -} diff --git a/packages/json-schemas/schemas/relayer_api_asset_data_trade_info_schema.json b/packages/json-schemas/schemas/relayer_api_asset_data_trade_info_schema.json deleted file mode 100644 index e0f274c5d8..0000000000 --- a/packages/json-schemas/schemas/relayer_api_asset_data_trade_info_schema.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "id": "/relayerApiAssetDataTradeInfoSchema", - "type": "object", - "properties": { - "assetData": { "$ref": "/hexSchema" }, - "minAmount": { "$ref": "/wholeNumberSchema" }, - "maxAmount": { "$ref": "/wholeNumberSchema" }, - "precision": { "type": "number" } - }, - "required": ["assetData"] -} diff --git a/packages/json-schemas/schemas/relayer_api_error_response_schema.json b/packages/json-schemas/schemas/relayer_api_error_response_schema.json deleted file mode 100644 index be4659b0bd..0000000000 --- a/packages/json-schemas/schemas/relayer_api_error_response_schema.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "id": "/relayerApiErrorResponseSchema", - "type": "object", - "properties": { - "code": { "type": "integer", "minimum": 100, "maximum": 103 }, - "reason": { "type": "string" }, - "validationErrors": { - "type": "array", - "items": { - "type": "object", - "properties": { - "field": { "type": "string" }, - "code": { "type": "integer", "minimum": 1000, "maximum": 1006 }, - "reason": { "type": "string" } - }, - "required": ["field", "code", "reason"] - } - } - }, - "required": ["code", "reason"] -} diff --git a/packages/json-schemas/schemas/relayer_api_fee_recipients_response_schema.json b/packages/json-schemas/schemas/relayer_api_fee_recipients_response_schema.json deleted file mode 100644 index c73506dbb1..0000000000 --- a/packages/json-schemas/schemas/relayer_api_fee_recipients_response_schema.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "id": "/relayerApiFeeRecipientsResponseSchema", - "type": "object", - "allOf": [ - { "$ref": "/paginatedCollectionSchema" }, - { - "properties": { - "records": { - "type": "array", - "items": { "$ref": "/addressSchema" } - } - }, - "required": ["records"] - } - ] -} diff --git a/packages/json-schemas/schemas/relayer_api_order_config_payload_schema.json b/packages/json-schemas/schemas/relayer_api_order_config_payload_schema.json deleted file mode 100644 index f4583fc625..0000000000 --- a/packages/json-schemas/schemas/relayer_api_order_config_payload_schema.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "id": "/relayerApiOrderConfigPayloadSchema", - "type": "object", - "properties": { - "makerAddress": { "$ref": "/addressSchema" }, - "takerAddress": { "$ref": "/addressSchema" }, - "makerAssetAmount": { "$ref": "/wholeNumberSchema" }, - "takerAssetAmount": { "$ref": "/wholeNumberSchema" }, - "makerAssetData": { "$ref": "/hexSchema" }, - "takerAssetData": { "$ref": "/hexSchema" }, - "exchangeAddress": { "$ref": "/addressSchema" }, - "expirationTimeSeconds": { "$ref": "/wholeNumberSchema" } - }, - "required": [ - "makerAddress", - "takerAddress", - "makerAssetAmount", - "takerAssetAmount", - "makerAssetData", - "takerAssetData", - "exchangeAddress", - "expirationTimeSeconds" - ] -} diff --git a/packages/json-schemas/schemas/relayer_api_order_config_response_schema.json b/packages/json-schemas/schemas/relayer_api_order_config_response_schema.json deleted file mode 100644 index 3d060a7631..0000000000 --- a/packages/json-schemas/schemas/relayer_api_order_config_response_schema.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "id": "/relayerApiOrderConfigResponseSchema", - "type": "object", - "properties": { - "makerFee": { - "$ref": "/wholeNumberSchema" - }, - "takerFee": { - "$ref": "/wholeNumberSchema" - }, - "feeRecipientAddress": { - "$ref": "/addressSchema" - }, - "senderAddress": { - "$ref": "/addressSchema" - }, - "makerFeeAssetData": { - "$ref": "/hexSchema" - }, - "takerFeeAssetData": { - "$ref": "/hexSchema" - } - }, - "required": [ - "makerFee", - "takerFee", - "feeRecipientAddress", - "senderAddress", - "makerFeeAssetData", - "takerFeeAssetData" - ] -} diff --git a/packages/json-schemas/schemas/relayer_api_order_schema.json b/packages/json-schemas/schemas/relayer_api_order_schema.json deleted file mode 100644 index e0f6539b9f..0000000000 --- a/packages/json-schemas/schemas/relayer_api_order_schema.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "id": "/relayerApiOrderSchema", - "type": "object", - "properties": { - "order": { "$ref": "/orderSchema" }, - "metaData": { "type": "object" } - }, - "required": ["order", "metaData"] -} diff --git a/packages/json-schemas/schemas/relayer_api_orderbook_response_schema.json b/packages/json-schemas/schemas/relayer_api_orderbook_response_schema.json deleted file mode 100644 index b44f2a7408..0000000000 --- a/packages/json-schemas/schemas/relayer_api_orderbook_response_schema.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "id": "/relayerApiOrderbookResponseSchema", - "type": "object", - "properties": { - "bids": { "$ref": "/relayerApiOrdersResponseSchema" }, - "asks": { "$ref": "/relayerApiOrdersResponseSchema" } - }, - "required": ["bids", "asks"] -} diff --git a/packages/json-schemas/schemas/relayer_api_orders_channel_subscribe_payload_schema.json b/packages/json-schemas/schemas/relayer_api_orders_channel_subscribe_payload_schema.json deleted file mode 100644 index a002c21fb9..0000000000 --- a/packages/json-schemas/schemas/relayer_api_orders_channel_subscribe_payload_schema.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "id": "/relayerApiOrdersChannelSubscribePayloadSchema", - "type": "object", - "properties": { - "makerAssetProxyId": { - "$ref": "/hexSchema" - }, - "takerAssetProxyId": { - "$ref": "/hexSchema" - }, - "makerAssetAddress": { - "$ref": "/addressSchema" - }, - "takerAssetAddress": { - "$ref": "/addressSchema" - }, - "makerAssetData": { - "$ref": "/hexSchema" - }, - "takerAssetData": { - "$ref": "/hexSchema" - }, - "traderAssetData": { - "$ref": "/hexSchema" - } - } -} diff --git a/packages/json-schemas/schemas/relayer_api_orders_channel_subscribe_schema.json b/packages/json-schemas/schemas/relayer_api_orders_channel_subscribe_schema.json deleted file mode 100644 index 29561d09fc..0000000000 --- a/packages/json-schemas/schemas/relayer_api_orders_channel_subscribe_schema.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "id": "/relayerApiOrdersChannelSubscribeSchema", - "type": "object", - "properties": { - "type": { "enum": ["subscribe"] }, - "channel": { "enum": ["orders"] }, - "requestId": { "type": "string" }, - "payload": { "$ref": "/relayerApiOrdersChannelSubscribePayloadSchema" } - }, - "required": ["type", "channel", "requestId"] -} diff --git a/packages/json-schemas/schemas/relayer_api_orders_channel_update_response_schema.json b/packages/json-schemas/schemas/relayer_api_orders_channel_update_response_schema.json deleted file mode 100644 index 239e7c5861..0000000000 --- a/packages/json-schemas/schemas/relayer_api_orders_channel_update_response_schema.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "id": "/relayerApiOrdersChannelUpdateSchema", - "type": "object", - "properties": { - "type": { "enum": ["update"] }, - "channel": { "enum": ["orders"] }, - "requestId": { "type": "string" }, - "payload": { "$ref": "/relayerApiOrdersSchema" } - }, - "required": ["type", "channel", "requestId"] -} diff --git a/packages/json-schemas/schemas/relayer_api_orders_response_schema.json b/packages/json-schemas/schemas/relayer_api_orders_response_schema.json deleted file mode 100644 index a5023a3fc1..0000000000 --- a/packages/json-schemas/schemas/relayer_api_orders_response_schema.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "id": "/relayerApiOrdersResponseSchema", - "type": "object", - "allOf": [ - { "$ref": "/paginatedCollectionSchema" }, - { - "properties": { - "records": { "$ref": "/relayerApiOrdersSchema" } - }, - "required": ["records"] - } - ] -} diff --git a/packages/json-schemas/schemas/relayer_api_orders_schema.json b/packages/json-schemas/schemas/relayer_api_orders_schema.json deleted file mode 100644 index a8c970e718..0000000000 --- a/packages/json-schemas/schemas/relayer_api_orders_schema.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "id": "/relayerApiOrdersSchema", - "type": "array", - "items": { - "$ref": "/relayerApiOrderSchema" - } -} diff --git a/packages/json-schemas/schemas/signed_order_schema.json b/packages/json-schemas/schemas/signed_order_schema.json deleted file mode 100644 index 137ae4a249..0000000000 --- a/packages/json-schemas/schemas/signed_order_schema.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "id": "/signedOrderSchema", - "allOf": [ - { "$ref": "/orderSchema" }, - { - "properties": { - "signature": { "$ref": "/hexSchema" } - }, - "required": ["signature"] - } - ] -} diff --git a/packages/json-schemas/schemas/signed_orders_schema.json b/packages/json-schemas/schemas/signed_orders_schema.json deleted file mode 100644 index e7c3a0b6c9..0000000000 --- a/packages/json-schemas/schemas/signed_orders_schema.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "id": "/signedOrdersSchema", - "type": "array", - "items": { "$ref": "/signedOrderSchema" } -} diff --git a/packages/json-schemas/schemas/token_schema.json b/packages/json-schemas/schemas/token_schema.json deleted file mode 100644 index 31e41c4b87..0000000000 --- a/packages/json-schemas/schemas/token_schema.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "id": "/tokenSchema", - "properties": { - "name": { "type": "string" }, - "symbol": { "type": "string" }, - "decimals": { "type": "number" }, - "address": { "$ref": "/addressSchema" } - }, - "required": ["name", "symbol", "decimals", "address"], - "type": "object" -} diff --git a/packages/json-schemas/schemas/tx_data_schema.json b/packages/json-schemas/schemas/tx_data_schema.json deleted file mode 100644 index 8c3daba4e5..0000000000 --- a/packages/json-schemas/schemas/tx_data_schema.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "id": "/txDataSchema", - "properties": { - "from": { "$ref": "/addressSchema" }, - "to": { "$ref": "/addressSchema" }, - "value": { - "oneOf": [{ "$ref": "/numberSchema" }, { "$ref": "/jsNumberSchema" }] - }, - "gas": { - "oneOf": [{ "$ref": "/numberSchema" }, { "$ref": "/jsNumberSchema" }] - }, - "gasPrice": { - "oneOf": [{ "$ref": "/numberSchema" }, { "$ref": "/jsNumberSchema" }] - }, - "data": { - "type": "string", - "pattern": "^0x[0-9a-f]*$" - }, - "nonce": { - "type": "number", - "minimum": 0 - } - }, - "required": ["from"], - "type": "object" -} diff --git a/packages/json-schemas/schemas/whole_number_schema.json b/packages/json-schemas/schemas/whole_number_schema.json deleted file mode 100644 index aa469954ca..0000000000 --- a/packages/json-schemas/schemas/whole_number_schema.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "id": "/wholeNumberSchema", - "anyOf": [ - { - "type": "string", - "pattern": "^\\d+$" - }, - { - "type": "integer" - } - ] -} diff --git a/packages/json-schemas/schemas/zero_ex_transaction_schema.json b/packages/json-schemas/schemas/zero_ex_transaction_schema.json deleted file mode 100644 index 9d470b1244..0000000000 --- a/packages/json-schemas/schemas/zero_ex_transaction_schema.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "id": "/zeroExTransactionSchema", - "properties": { - "data": { "$ref": "/hexSchema" }, - "signerAddress": { "$ref": "/addressSchema" }, - "salt": { "$ref": "/wholeNumberSchema" }, - "expirationTimeSeconds": { "$ref": "/wholeNumberSchema" }, - "gasPrice": { "$ref": "/wholeNumberSchema" }, - "domain": { "$ref": "/eip712DomainSchema" } - }, - "required": ["data", "salt", "expirationTimeSeconds", "gasPrice", "signerAddress", "domain"], - "type": "object" -} diff --git a/packages/json-schemas/src/index.ts b/packages/json-schemas/src/index.ts deleted file mode 100644 index 9d8470348d..0000000000 --- a/packages/json-schemas/src/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -export { ValidatorResult, Schema } from 'jsonschema'; - -export { SchemaValidator } from './schema_validator'; -export { schemas } from './schemas'; diff --git a/packages/json-schemas/src/schema_validator.ts b/packages/json-schemas/src/schema_validator.ts deleted file mode 100644 index 43647b5940..0000000000 --- a/packages/json-schemas/src/schema_validator.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { Schema, Validator, ValidatorResult } from 'jsonschema'; -import values = require('lodash.values'); - -import { schemas } from './schemas'; - -/** - * A validator for [JSON-schemas](http://json-schema.org/) - */ -export class SchemaValidator { - private readonly _validator: Validator; - private static _assertSchemaDefined(schema: Schema): void { - if (schema === undefined) { - throw new Error(`Cannot add undefined schema`); - } - } - /** - * Instantiates a SchemaValidator instance - */ - constructor() { - this._validator = new Validator(); - for (const schema of values(schemas)) { - SchemaValidator._assertSchemaDefined(schema); - this._validator.addSchema(schema, schema.id); - } - } - /** - * Add a schema to the validator. All schemas and sub-schemas must be added to - * the validator before the `validate` and `isValid` methods can be called with - * instances of that schema. - * @param schema The schema to add - */ - public addSchema(schema: Schema): void { - SchemaValidator._assertSchemaDefined(schema); - this._validator.addSchema(schema, schema.id); - } - // In order to validate a complex JS object using jsonschema, we must replace any complex - // sub-types (e.g BigNumber) with a simpler string representation. Since BigNumber and other - // complex types implement the `toString` method, we can stringify the object and - // then parse it. The resultant object can then be checked using jsonschema. - /** - * Validate the JS object conforms to a specific JSON schema - * @param instance JS object in question - * @param schema Schema to check against - * @returns The results of the validation - */ - public validate(instance: any, schema: Schema): ValidatorResult { - SchemaValidator._assertSchemaDefined(schema); - const jsonSchemaCompatibleObject = JSON.parse(JSON.stringify(instance)); - return this._validator.validate(jsonSchemaCompatibleObject, schema); - } - /** - * Check whether an instance properly adheres to a JSON schema - * @param instance JS object in question - * @param schema Schema to check against - * @returns Whether or not the instance adheres to the schema - */ - public isValid(instance: any, schema: Schema): boolean { - const isValid = this.validate(instance, schema).errors.length === 0; - return isValid; - } -} diff --git a/packages/json-schemas/src/schemas.ts b/packages/json-schemas/src/schemas.ts deleted file mode 100644 index 2e306e5939..0000000000 --- a/packages/json-schemas/src/schemas.ts +++ /dev/null @@ -1,93 +0,0 @@ -import * as addressSchema from '../schemas/address_schema.json'; -import * as assetPairsRequestOptsSchema from '../schemas/asset_pairs_request_opts_schema.json'; -import * as blockParamSchema from '../schemas/block_param_schema.json'; -import * as blockRangeSchema from '../schemas/block_range_schema.json'; -import * as callDataSchema from '../schemas/call_data_schema.json'; -import * as ecSignatureParameterSchema from '../schemas/ec_signature_parameter_schema.json'; -import * as ecSignatureSchema from '../schemas/ec_signature_schema.json'; -import * as eip712DomainSchema from '../schemas/eip712_domain_schema.json'; -import * as eip712TypedDataSchema from '../schemas/eip712_typed_data_schema.json'; -import * as exchangeProxyMetaTransactionSchema from '../schemas/exchange_proxy_meta_transaction_schema.json'; -import * as hexSchema from '../schemas/hex_schema.json'; -import * as indexFilterValuesSchema from '../schemas/index_filter_values_schema.json'; -import * as jsNumber from '../schemas/js_number_schema.json'; -import * as numberSchema from '../schemas/number_schema.json'; -import * as orderCancellationRequestsSchema from '../schemas/order_cancel_schema.json'; -import * as orderConfigRequestSchema from '../schemas/order_config_request_schema.json'; -import * as orderFillOrKillRequestsSchema from '../schemas/order_fill_or_kill_requests_schema.json'; -import * as orderFillRequestsSchema from '../schemas/order_fill_requests_schema.json'; -import * as orderHashSchema from '../schemas/order_hash_schema.json'; -import * as orderSchema from '../schemas/order_schema.json'; -import * as orderBookRequestSchema from '../schemas/orderbook_request_schema.json'; -import * as ordersRequestOptsSchema from '../schemas/orders_request_opts_schema.json'; -import * as ordersSchema from '../schemas/orders_schema.json'; -import * as pagedRequestOptsSchema from '../schemas/paged_request_opts_schema.json'; -import * as paginatedCollectionSchema from '../schemas/paginated_collection_schema.json'; -import * as relayerApiAssetDataPairsResponseSchema from '../schemas/relayer_api_asset_data_pairs_response_schema.json'; -import * as relayerApiAssetDataPairsSchema from '../schemas/relayer_api_asset_data_pairs_schema.json'; -import * as relayerApiAssetDataTradeInfoSchema from '../schemas/relayer_api_asset_data_trade_info_schema.json'; -import * as relayerApiErrorResponseSchema from '../schemas/relayer_api_error_response_schema.json'; -import * as relayerApiFeeRecipientsResponseSchema from '../schemas/relayer_api_fee_recipients_response_schema.json'; -import * as relayerApiOrderConfigPayloadSchema from '../schemas/relayer_api_order_config_payload_schema.json'; -import * as relayerApiOrderConfigResponseSchema from '../schemas/relayer_api_order_config_response_schema.json'; -import * as relayerApiOrderSchema from '../schemas/relayer_api_order_schema.json'; -import * as relayerApiOrderbookResponseSchema from '../schemas/relayer_api_orderbook_response_schema.json'; -import * as relayerApiOrdersChannelSubscribePayloadSchema from '../schemas/relayer_api_orders_channel_subscribe_payload_schema.json'; -import * as relayerApiOrdersChannelSubscribeSchema from '../schemas/relayer_api_orders_channel_subscribe_schema.json'; -import * as relayerApiOrdersChannelUpdateSchema from '../schemas/relayer_api_orders_channel_update_response_schema.json'; -import * as relayerApiOrdersResponseSchema from '../schemas/relayer_api_orders_response_schema.json'; -import * as relayerApiOrdersSchema from '../schemas/relayer_api_orders_schema.json'; -import * as signedOrderSchema from '../schemas/signed_order_schema.json'; -import * as signedOrdersSchema from '../schemas/signed_orders_schema.json'; -import * as tokenSchema from '../schemas/token_schema.json'; -import * as txDataSchema from '../schemas/tx_data_schema.json'; -import * as wholeNumberSchema from '../schemas/whole_number_schema.json'; -import * as zeroExTransactionSchema from '../schemas/zero_ex_transaction_schema.json'; - -export const schemas = { - numberSchema, - addressSchema, - callDataSchema, - hexSchema, - ecSignatureParameterSchema, - ecSignatureSchema, - eip712DomainSchema, - eip712TypedDataSchema, - indexFilterValuesSchema, - orderCancellationRequestsSchema, - orderFillOrKillRequestsSchema, - orderFillRequestsSchema, - orderHashSchema, - orderSchema, - signedOrderSchema, - signedOrdersSchema, - ordersSchema, - blockParamSchema, - blockRangeSchema, - tokenSchema, - jsNumber, - pagedRequestOptsSchema, - ordersRequestOptsSchema, - orderBookRequestSchema, - orderConfigRequestSchema, - assetPairsRequestOptsSchema, - txDataSchema, - paginatedCollectionSchema, - relayerApiErrorResponseSchema, - relayerApiFeeRecipientsResponseSchema, - relayerApiOrderSchema, - relayerApiOrdersSchema, - relayerApiOrderConfigPayloadSchema, - relayerApiOrderConfigResponseSchema, - relayerApiOrderbookResponseSchema, - relayerApiAssetDataPairsResponseSchema, - relayerApiAssetDataTradeInfoSchema, - relayerApiOrdersChannelSubscribeSchema, - relayerApiOrdersChannelSubscribePayloadSchema, - relayerApiOrdersChannelUpdateSchema, - relayerApiOrdersResponseSchema, - relayerApiAssetDataPairsSchema, - zeroExTransactionSchema, - exchangeProxyMetaTransactionSchema, - wholeNumberSchema, -}; diff --git a/packages/json-schemas/test/schema_test.ts b/packages/json-schemas/test/schema_test.ts deleted file mode 100644 index 6c3aa4f379..0000000000 --- a/packages/json-schemas/test/schema_test.ts +++ /dev/null @@ -1,872 +0,0 @@ -import { BigNumber } from '@0x/utils'; -import * as chai from 'chai'; -import * as dirtyChai from 'dirty-chai'; -import forEach = require('lodash.foreach'); -import 'mocha'; - -import { schemas, SchemaValidator } from '../src/index'; - -chai.config.includeStack = true; -chai.use(dirtyChai); -const expect = chai.expect; -const NULL_ADDRESS = '0x0000000000000000000000000000000000000000'; -const CHAIN_ID = 1337; -const { - numberSchema, - addressSchema, - hexSchema, - orderCancellationRequestsSchema, - orderFillOrKillRequestsSchema, - orderFillRequestsSchema, - orderHashSchema, - orderSchema, - signedOrderSchema, - signedOrdersSchema, - blockParamSchema, - blockRangeSchema, - tokenSchema, - jsNumber, - txDataSchema, - paginatedCollectionSchema, - relayerApiErrorResponseSchema, - relayerApiOrderbookResponseSchema, - relayerApiAssetDataPairsResponseSchema, - relayerApiOrderConfigPayloadSchema, - relayerApiOrderConfigResponseSchema, - relayerApiOrdersChannelSubscribeSchema, - relayerApiOrdersChannelUpdateSchema, - relayerApiOrdersResponseSchema, - relayerApiOrderSchema, - wholeNumberSchema, -} = schemas; - -describe('Schema', () => { - const validator = new SchemaValidator(); - const validateAgainstSchema = (testCases: any[], schema: any, shouldFail = false) => { - forEach(testCases, (testCase: any) => { - const validationResult = validator.validate(testCase, schema); - const hasErrors = validationResult.errors.length !== 0; - if (shouldFail) { - if (!hasErrors) { - throw new Error( - `Expected testCase: ${JSON.stringify(testCase, null, '\t')} to fail and it didn't.`, - ); - } - } else { - if (hasErrors) { - throw new Error(JSON.stringify(validationResult.errors, null, '\t')); - } - } - }); - }; - const paginatedResponse = { - total: 100, - perPage: 10, - page: 3, - }; - describe('#numberSchema', () => { - it('should validate valid numbers', () => { - const testCases = ['42', '0', '1.3', '0.2', '00.00']; - validateAgainstSchema(testCases, numberSchema); - }); - it('should fail for invalid numbers', () => { - const testCases = ['.3', '1.', 'abacaba', 'и', '1..0']; - const shouldFail = true; - validateAgainstSchema(testCases, numberSchema, shouldFail); - }); - }); - describe('#wholeNumberSchema', () => { - it('should validate valid numbers', () => { - const testCases = ['5', '42', '0']; - validateAgainstSchema(testCases, wholeNumberSchema); - }); - it('should fail for invalid numbers', () => { - const testCases = ['1.3', '0.2', '00.00', '.3', '1.', 'abacaba', 'и', '1..0']; - const shouldFail = true; - validateAgainstSchema(testCases, wholeNumberSchema, shouldFail); - }); - }); - describe('#addressSchema', () => { - it('should validate valid addresses', () => { - const testCases = ['0x8b0292b11a196601ed2ce54b665cafeca0347d42', NULL_ADDRESS]; - validateAgainstSchema(testCases, addressSchema); - }); - it('should fail for invalid addresses', () => { - const testCases = ['0x', '0', '0x00', '0xzzzzzzB11a196601eD2ce54B665CaFEca0347D42']; - const shouldFail = true; - validateAgainstSchema(testCases, addressSchema, shouldFail); - }); - }); - describe('#hexSchema', () => { - it('should validate valid hex string', () => { - const testCases = ['0x8b0292b11a196601ed2ce54b665cafeca0347d42', NULL_ADDRESS]; - validateAgainstSchema(testCases, hexSchema); - }); - it('should fail for invalid hex string', () => { - const testCases = ['0', '0xzzzzzzB11a196601eD2ce54B665CaFEca0347D42']; - const shouldFail = true; - validateAgainstSchema(testCases, hexSchema, shouldFail); - }); - }); - describe('#orderHashSchema', () => { - it('should validate valid order hash', () => { - const testCases = [ - '0x61a3ed31B43c8780e905a260a35faefEc527be7516aa11c0256729b5b351bc33', - '0x40349190569279751135161d22529dc25add4f6069af05be04cacbda2ace2254', - ]; - validateAgainstSchema(testCases, orderHashSchema); - }); - it('should fail for invalid order hash', () => { - const testCases = [ - {}, - '0x', - '0x8b0292B11a196601eD2ce54B665CaFEca0347D42', - '61a3ed31B43c8780e905a260a35faefEc527be7516aa11c0256729b5b351bc33', - ]; - const shouldFail = true; - validateAgainstSchema(testCases, orderHashSchema, shouldFail); - }); - }); - describe('#blockParamSchema', () => { - it('should validate valid block param', () => { - const blockNumber = 42; - const testCases = [blockNumber, 'latest', 'pending', 'earliest']; - validateAgainstSchema(testCases, blockParamSchema); - }); - it('should fail for invalid block param', () => { - const testCases = [{}, '42', 'pemding']; - const shouldFail = true; - validateAgainstSchema(testCases, blockParamSchema, shouldFail); - }); - }); - describe('#blockRangeSchema', () => { - it('should validate valid subscription opts', () => { - const testCases = [{ fromBlock: 42, toBlock: 'latest' }, { fromBlock: 42 }, {}]; - validateAgainstSchema(testCases, blockRangeSchema); - }); - it('should fail for invalid subscription opts', () => { - const testCases = [{ fromBlock: '42' }]; - const shouldFail = true; - validateAgainstSchema(testCases, blockRangeSchema, shouldFail); - }); - }); - describe('#tokenSchema', () => { - const token = { - name: 'Zero Ex', - symbol: 'ZRX', - decimals: 100500, - address: '0x8b0292b11a196601ed2ce54b665cafeca0347d42', - url: 'https://0xproject.com', - }; - it('should validate valid token', () => { - const testCases = [token]; - validateAgainstSchema(testCases, tokenSchema); - }); - it('should fail for invalid token', () => { - const num = 4; - const testCases = [ - { - ...token, - address: null, - }, - { - ...token, - decimals: undefined, - }, - [], - num, - ]; - const shouldFail = true; - validateAgainstSchema(testCases, tokenSchema, shouldFail); - }); - }); - describe('#paginatedCollectionSchema', () => { - it('should validate valid paginated collections', () => { - const testCases = [paginatedResponse]; - validateAgainstSchema(testCases, paginatedCollectionSchema); - }); - it('should fail for invalid paginated collections', () => { - const paginatedCollectionNoTotal = { - page: 10, - perPage: 2, - }; - const paginatedCollectionNoPerPage = { - page: 10, - total: 100, - }; - const paginatedCollectionNoPage = { - total: 10, - perPage: 20, - }; - const testCases = [{}, paginatedCollectionNoPage, paginatedCollectionNoPerPage, paginatedCollectionNoTotal]; - const shouldFail = true; - validateAgainstSchema(testCases, paginatedCollectionSchema, shouldFail); - }); - }); - describe('order including schemas', () => { - const order = { - makerAddress: NULL_ADDRESS, - takerAddress: NULL_ADDRESS, - senderAddress: NULL_ADDRESS, - makerFee: '1', - takerFee: '2', - makerAssetAmount: '1', - takerAssetAmount: '2', - makerAssetData: NULL_ADDRESS, - takerAssetData: NULL_ADDRESS, - makerFeeAssetData: NULL_ADDRESS, - takerFeeAssetData: NULL_ADDRESS, - salt: '67006738228878699843088602623665307406148487219438534730168799356281242528500', - feeRecipientAddress: NULL_ADDRESS, - expirationTimeSeconds: '42', - exchangeAddress: NULL_ADDRESS, - chainId: CHAIN_ID, - }; - const relayerApiOrder = { - order, - metaData: { - someMetaData: 5, - }, - }; - const relayerApiOrdersResponse = { - ...paginatedResponse, - records: [relayerApiOrder, relayerApiOrder], - }; - describe('#orderSchema', () => { - it('should validate valid order', () => { - const testCases = [order]; - validateAgainstSchema(testCases, orderSchema); - }); - it('should fail for invalid order', () => { - const testCases = [ - { - ...order, - salt: undefined, - }, - { - ...order, - salt: 'salt', - }, - 'order', - ]; - const shouldFail = true; - validateAgainstSchema(testCases, orderSchema, shouldFail); - }); - }); - describe('signed order including schemas', () => { - const signedOrder = { - ...order, - signature: - '0x031b61a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351bc3340349190569279751135161d22529dc25add4f6069af05be04cacbda2ace2254', - }; - describe('#signedOrdersSchema', () => { - it('should validate valid signed orders', () => { - const testCases = [[signedOrder], []]; - validateAgainstSchema(testCases, signedOrdersSchema); - }); - it('should fail for invalid signed orders', () => { - const testCases = [[signedOrder, 1]]; - const shouldFail = true; - validateAgainstSchema(testCases, signedOrdersSchema, shouldFail); - }); - }); - describe('#signedOrderSchema', () => { - it('should validate valid signed order', () => { - const testCases = [signedOrder]; - validateAgainstSchema(testCases, signedOrderSchema); - }); - it('should fail for invalid signed order', () => { - const testCases = [ - { - ...signedOrder, - signature: undefined, - }, - ]; - const shouldFail = true; - validateAgainstSchema(testCases, signedOrderSchema, shouldFail); - }); - }); - describe('#orderFillOrKillRequestsSchema', () => { - const orderFillOrKillRequests = [ - { - signedOrder, - fillTakerAmount: '5', - }, - ]; - it('should validate valid order fill or kill requests', () => { - const testCases = [orderFillOrKillRequests]; - validateAgainstSchema(testCases, orderFillOrKillRequestsSchema); - }); - it('should fail for invalid order fill or kill requests', () => { - const testCases = [ - [ - { - ...orderFillOrKillRequests[0], - fillTakerAmount: undefined, - }, - ], - ]; - const shouldFail = true; - validateAgainstSchema(testCases, orderFillOrKillRequestsSchema, shouldFail); - }); - }); - describe('#orderCancellationRequestsSchema', () => { - const orderCancellationRequests = [ - { - order, - takerTokenCancelAmount: '5', - }, - ]; - it('should validate valid order cancellation requests', () => { - const testCases = [orderCancellationRequests]; - validateAgainstSchema(testCases, orderCancellationRequestsSchema); - }); - it('should fail for invalid order cancellation requests', () => { - const testCases = [ - [ - { - ...orderCancellationRequests[0], - takerTokenCancelAmount: undefined, - }, - ], - ]; - const shouldFail = true; - validateAgainstSchema(testCases, orderCancellationRequestsSchema, shouldFail); - }); - }); - describe('#orderFillRequestsSchema', () => { - const orderFillRequests = [ - { - signedOrder, - takerTokenFillAmount: '5', - }, - ]; - it('should validate valid order fill requests', () => { - const testCases = [orderFillRequests]; - validateAgainstSchema(testCases, orderFillRequestsSchema); - }); - it('should fail for invalid order fill requests', () => { - const testCases = [ - [ - { - ...orderFillRequests[0], - takerTokenFillAmount: undefined, - }, - ], - ]; - const shouldFail = true; - validateAgainstSchema(testCases, orderFillRequestsSchema, shouldFail); - }); - }); - describe('standard relayer api schemas', () => { - describe('#relayerApiOrderSchema', () => { - it('should validate valid relayer api order', () => { - const testCases = [relayerApiOrder]; - validateAgainstSchema(testCases, relayerApiOrderSchema); - }); - it('should fail for invalid relayer api orders', () => { - const testCases = [{}, order, { order }, { order, metaData: 5 }]; - const shouldFail = true; - validateAgainstSchema(testCases, relayerApiOrderSchema, shouldFail); - }); - }); - describe('#relayerApiErrorResponseSchema', () => { - it('should validate valid errorResponse', () => { - const testCases = [ - { - code: 102, - reason: 'Order submission disabled', - }, - { - code: 101, - reason: 'Validation failed', - validationErrors: [ - { - field: 'maker', - code: 1002, - reason: 'Invalid address', - }, - ], - }, - ]; - validateAgainstSchema(testCases, relayerApiErrorResponseSchema); - }); - it('should fail for invalid error responses', () => { - const testCases = [ - {}, - { - code: 102, - }, - { - code: '102', - reason: 'Order submission disabled', - }, - { - reason: 'Order submission disabled', - }, - { - code: 101, - reason: 'Validation failed', - validationErrors: [ - { - field: 'maker', - reason: 'Invalid address', - }, - ], - }, - { - code: 101, - reason: 'Validation failed', - validationErrors: [ - { - field: 'maker', - code: '1002', - reason: 'Invalid address', - }, - ], - }, - ]; - const shouldFail = true; - validateAgainstSchema(testCases, relayerApiErrorResponseSchema, shouldFail); - }); - }); - describe('#relayerApiOrderConfigPayloadSchema', () => { - it('should validate valid fees payloads', () => { - const testCases = [ - { - exchangeAddress: '0x323b5d4c32345ced77393b3530b1eed0f346429d', - makerAddress: '0x323b5d4c32345ced77393b3530b1eed0f346429d', - takerAddress: '0x323b5d4c32345ced77393b3530b1eed0f346429d', - makerAssetData: NULL_ADDRESS, - takerAssetData: NULL_ADDRESS, - makerAssetAmount: '10000000000000000000', - takerAssetAmount: '30000000000000000000', - expirationTimeSeconds: '42', - }, - ]; - validateAgainstSchema(testCases, relayerApiOrderConfigPayloadSchema); - }); - it('should fail for invalid fees payloads', () => { - const checksummedAddress = '0xA2b31daCf30a9C50ca473337c01d8A201ae33e32'; - const testCases = [ - {}, - { - makerAssetAmount: '10000000000000000000', - takerAssetAmount: '30000000000000000000', - makerAssetData: NULL_ADDRESS, - takerAssetData: NULL_ADDRESS, - }, - { - takerAddress: checksummedAddress, - makerAssetAmount: '10000000000000000000', - takerAssetAmount: '30000000000000000000', - }, - { - makerAssetAmount: 10000000000000000000, - takerAssetAmount: 30000000000000000000, - }, - ]; - const shouldFail = true; - validateAgainstSchema(testCases, relayerApiOrderConfigPayloadSchema, shouldFail); - }); - }); - describe('#relayerApiOrderConfigResponseSchema', () => { - it('should validate valid fees responses', () => { - const testCases = [ - { - makerFee: '10000000000000000', - takerFee: '30000000000000000', - feeRecipientAddress: '0x323b5d4c32345ced77393b3530b1eed0f346429d', - senderAddress: '0x323b5d4c32345ced77393b3530b1eed0f346429d', - makerFeeAssetData: '0xf47261b04c32345ced77393b3530b1eed0f346429d', - takerFeeAssetData: '0xf47261b04c32345ced77393b3530b1eed0f346429d', - }, - ]; - validateAgainstSchema(testCases, relayerApiOrderConfigResponseSchema); - }); - it('should fail for invalid fees responses', () => { - const checksummedAddress = '0xA2b31daCf30a9C50ca473337c01d8A201ae33e32'; - const testCases = [ - {}, - { - makerFee: 10000000000000000, - takerFee: 30000000000000000, - }, - { - feeRecipient: checksummedAddress, - takerToSpecify: checksummedAddress, - makerFee: '10000000000000000', - takerFee: '30000000000000000', - }, - ]; - const shouldFail = true; - validateAgainstSchema(testCases, relayerApiOrderConfigResponseSchema, shouldFail); - }); - }); - describe('#relayerAssetDataPairsResponseSchema', () => { - it('should validate valid assetPairs response', () => { - const testCases = [ - { - ...paginatedResponse, - records: [], - }, - { - ...paginatedResponse, - records: [ - { - assetDataA: { - assetData: '0x323b5d4c32345ced77393b3530b1eed0f346429d', - minAmount: '0', - maxAmount: '10000000000000000000', - precision: 5, - }, - assetDataB: { - assetData: '0xef7fff64389b814a946f3e92105513705ca6b990', - minAmount: '0', - maxAmount: '50000000000000000000', - precision: 5, - }, - }, - ], - }, - { - ...paginatedResponse, - records: [ - { - assetDataA: { - assetData: '0x323b5d4c32345ced77393b3530b1eed0f346429d', - }, - assetDataB: { - assetData: '0xef7fff64389b814a946f3e92105513705ca6b990', - }, - }, - ], - }, - ]; - validateAgainstSchema(testCases, relayerApiAssetDataPairsResponseSchema); - }); - it('should fail for invalid assetPairs responses', () => { - const testCases = [ - { - ...paginatedResponse, - records: [ - { - assetDataA: { - assetData: '0x323b5d4c32345ced77393b3530b1eed0f346429d', - minAmount: '0', - maxAmount: '10000000000000000000', - precision: 5, - }, - assetDataC: { - assetData: '0xef7fff64389b814a946f3e92105513705ca6b990', - minAmount: '0', - maxAmount: '50000000000000000000', - precision: 5, - }, - }, - ], - }, - { - records: [ - { - assetDataA: { - assetData: '0x323b5d4c32345ced77393b3530b1eed0f346429d', - minAmount: '0', - maxAmount: '10000000000000000000', - precision: 5, - }, - assetDataB: { - assetData: '0xef7fff64389b814a946f3e92105513705ca6b990', - minAmount: '0', - maxAmount: '50000000000000000000', - precision: 5, - }, - }, - ], - }, - { - ...paginatedResponse, - records: [ - { - assetDataA: { - minAmount: '0', - maxAmount: '10000000000000000000', - precision: 5, - }, - assetDataB: { - minAmount: '0', - maxAmount: '50000000000000000000', - precision: 5, - }, - }, - ], - }, - ]; - const shouldFail = true; - validateAgainstSchema(testCases, relayerApiAssetDataPairsResponseSchema, shouldFail); - }); - }); - describe('#relayerApiOrdersResponseSchema', () => { - it('should validate valid orders responses', () => { - const testCases = [ - relayerApiOrdersResponse, - { - ...paginatedResponse, - records: [], - }, - ]; - validateAgainstSchema(testCases, relayerApiOrdersResponseSchema); - }); - it('should fail for invalid orders responses', () => { - const testCases = [ - { - records: [relayerApiOrder, relayerApiOrder], - }, - { - ...paginatedResponse, - }, - { - ...paginatedResponse, - records: [{}, relayerApiOrder], - }, - ]; - const shouldFail = true; - validateAgainstSchema(testCases, relayerApiOrdersResponseSchema, shouldFail); - }); - }); - describe('#relayerApiOrderbookResponseSchema', () => { - it('should validate valid order book responses', () => { - const testCases = [ - { - bids: { - ...paginatedResponse, - records: [relayerApiOrder], - }, - asks: { - ...paginatedResponse, - records: [], - }, - }, - { - bids: { - ...paginatedResponse, - records: [relayerApiOrder, relayerApiOrder], - }, - asks: { - ...paginatedResponse, - records: [relayerApiOrder, relayerApiOrder], - }, - }, - { - bids: { - ...paginatedResponse, - records: [], - }, - asks: { - ...paginatedResponse, - records: [relayerApiOrder, relayerApiOrder], - }, - }, - ]; - validateAgainstSchema(testCases, relayerApiOrderbookResponseSchema); - }); - it('should fail for invalid order fill requests', () => { - const testCases = [ - {}, - { - bids: { - records: [relayerApiOrder], - }, - asks: { - ...paginatedResponse, - records: [], - }, - }, - { - bids: { - ...paginatedResponse, - records: [relayerApiOrder, relayerApiOrder], - }, - asks: {}, - }, - { - bids: { - ...paginatedResponse, - }, - asks: { - ...paginatedResponse, - records: [relayerApiOrder, relayerApiOrder], - }, - }, - ]; - const shouldFail = true; - validateAgainstSchema(testCases, relayerApiOrdersResponseSchema, shouldFail); - }); - }); - describe('#relayerApiOrdersChannelSubscribeSchema', () => { - it('should validate valid orders channel websocket subscribe message', () => { - const testCases = [ - { - type: 'subscribe', - channel: 'orders', - requestId: 'randomId', - }, - { - type: 'subscribe', - channel: 'orders', - requestId: 'randomId', - payload: { - makerAssetProxyId: '0x02571792', - takerAssetProxyId: '0xf47261b0', - }, - }, - { - type: 'subscribe', - channel: 'orders', - requestId: 'randomId', - payload: {}, - }, - ]; - validateAgainstSchema(testCases, relayerApiOrdersChannelSubscribeSchema); - }); - it('should fail for invalid orders channel websocket subscribe message', () => { - const bogusAddress = '0xz2b31daCf30a9C50ca473337c01d8A201ae33e32'; - const testCases = [ - { - type: 'subscribe', - channel: 'orders', - }, - { - type: 'subscribe', - channel: 'orders', - requestId: 'randomId', - payload: { - makerAssetProxyId: '0x02571792', - takerAssetProxyId: '0xf47261b0', - makerAssetAddress: bogusAddress, - }, - }, - { - type: 'subscribe', - channel: 'orders', - requestId: 'randomId', - payload: { - makerAssetProxyId: 'invalidId', - }, - }, - ]; - const shouldFail = true; - validateAgainstSchema(testCases, relayerApiOrdersChannelSubscribeSchema, shouldFail); - }); - }); - describe('#relayerApiOrdersChannelUpdateSchema', () => { - it('should validate valid orders channel websocket update message', () => { - const testCases = [ - { - type: 'update', - channel: 'orders', - requestId: 'randomId', - payload: [relayerApiOrder], - }, - { - type: 'update', - channel: 'orders', - requestId: 'randomId', - payload: [], - }, - ]; - validateAgainstSchema(testCases, relayerApiOrdersChannelUpdateSchema); - }); - it('should fail for invalid orders channel websocket update message', () => { - const testCases = [ - { - type: 'foo', - channel: 'orders', - requestId: 'randomId', - }, - { - type: 'update', - channel: 'bar', - requestId: 2, - payload: [relayerApiOrder], - }, - { - type: 'update', - channel: 'orders', - requestId: 'randomId', - payload: {}, - }, - { - type: 'update', - channel: 'orders', - requestId: 'randomId', - payload: relayerApiErrorResponseSchema, - }, - ]; - const shouldFail = true; - validateAgainstSchema(testCases, relayerApiOrdersChannelUpdateSchema, shouldFail); - }); - }); - }); - }); - }); - describe('BigNumber serialization', () => { - it('should correctly serialize BigNumbers', () => { - const testCases = { - '42': '42', - '0': '0', - '1.3': '1.3', - '0.2': '0.2', - '00.00': '0', - '.3': '0.3', - }; - forEach(testCases, (serialized: string, input: string) => { - expect(JSON.parse(JSON.stringify(new BigNumber(input)))).to.be.equal(serialized); - }); - }); - }); - describe('#jsNumberSchema', () => { - it('should validate valid js number', () => { - // tslint:disable-next-line:custom-no-magic-numbers - const testCases = [1, 42]; - validateAgainstSchema(testCases, jsNumber); - }); - it('should fail for invalid js number', () => { - // tslint:disable-next-line:custom-no-magic-numbers - const testCases = [NaN, -1, new BigNumber(1)]; - const shouldFail = true; - validateAgainstSchema(testCases, jsNumber, shouldFail); - }); - }); - describe('#txDataSchema', () => { - it('should validate valid txData', () => { - const bigNumGasAmount = new BigNumber(42); - const testCases = [ - { - from: NULL_ADDRESS, - }, - { - from: NULL_ADDRESS, - gas: bigNumGasAmount, - }, - { - from: NULL_ADDRESS, - gas: 42, - }, - ]; - validateAgainstSchema(testCases, txDataSchema); - }); - it('should fail for invalid txData', () => { - const testCases = [ - { - gas: new BigNumber(42), - }, - {}, - [], - new BigNumber(1), - ]; - const shouldFail = true; - validateAgainstSchema(testCases, txDataSchema, shouldFail); - }); - }); -}); // tslint:disable:max-file-line-count diff --git a/packages/json-schemas/tsconfig.json b/packages/json-schemas/tsconfig.json deleted file mode 100644 index 430d3155d9..0000000000 --- a/packages/json-schemas/tsconfig.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "extends": "../../tsconfig", - "compilerOptions": { - "outDir": "lib", - "rootDir": ".", - "resolveJsonModule": true - }, - "include": ["./src/**/*", "./test/**/*"], - "files": [ - "./schemas/address_schema.json", - "./schemas/number_schema.json", - "./schemas/hex_schema.json", - "./schemas/block_param_schema.json", - "./schemas/block_range_schema.json", - "./schemas/call_data_schema.json", - "./schemas/ec_signature_parameter_schema.json", - "./schemas/ec_signature_schema.json", - "./schemas/eip712_domain_schema.json", - "./schemas/eip712_typed_data_schema.json", - "./schemas/order_cancel_schema.json", - "./schemas/order_fill_or_kill_requests_schema.json", - "./schemas/order_fill_requests_schema.json", - "./schemas/order_hash_schema.json", - "./schemas/order_schema.json", - "./schemas/signed_order_schema.json", - "./schemas/orders_schema.json", - "./schemas/paginated_collection_schema.json", - "./schemas/relayer_api_asset_data_pairs_response_schema.json", - "./schemas/relayer_api_asset_data_pairs_schema.json", - "./schemas/relayer_api_asset_data_trade_info_schema.json", - "./schemas/relayer_api_error_response_schema.json", - "./schemas/relayer_api_fee_recipients_response_schema.json", - "./schemas/relayer_api_order_config_payload_schema.json", - "./schemas/relayer_api_order_config_response_schema.json", - "./schemas/relayer_api_order_schema.json", - "./schemas/relayer_api_orderbook_response_schema.json", - "./schemas/relayer_api_orders_channel_subscribe_payload_schema.json", - "./schemas/relayer_api_orders_channel_subscribe_schema.json", - "./schemas/relayer_api_orders_channel_update_response_schema.json", - "./schemas/relayer_api_orders_response_schema.json", - "./schemas/relayer_api_orders_schema.json", - "./schemas/signed_orders_schema.json", - "./schemas/token_schema.json", - "./schemas/js_number_schema.json", - "./schemas/zero_ex_transaction_schema.json", - "./schemas/tx_data_schema.json", - "./schemas/index_filter_values_schema.json", - "./schemas/whole_number_schema.json", - "./schemas/asset_pairs_request_opts_schema.json", - "./schemas/orderbook_request_schema.json", - "./schemas/orders_request_opts_schema.json", - "./schemas/paged_request_opts_schema.json", - "./schemas/order_config_request_schema.json", - "./schemas/exchange_proxy_meta_transaction_schema.json" - ] -} diff --git a/packages/json-schemas/tslint.json b/packages/json-schemas/tslint.json deleted file mode 100644 index dd9053357e..0000000000 --- a/packages/json-schemas/tslint.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": ["@0x/tslint-config"] -} diff --git a/packages/json-schemas/typedoc-tsconfig.json b/packages/json-schemas/typedoc-tsconfig.json deleted file mode 100644 index c9b0af1ae6..0000000000 --- a/packages/json-schemas/typedoc-tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "../../typedoc-tsconfig", - "compilerOptions": { - "outDir": "lib" - }, - "include": ["./src/**/*", "./test/**/*"] -} diff --git a/packages/monorepo-scripts/CHANGELOG.json b/packages/monorepo-scripts/CHANGELOG.json deleted file mode 100644 index 05a7bebc51..0000000000 --- a/packages/monorepo-scripts/CHANGELOG.json +++ /dev/null @@ -1,184 +0,0 @@ -[ - { - "version": "2.0.0", - "changes": [ - { - "note": "Upgrade the bignumber.js to v8.0.2", - "pr": 1517 - }, - { - "note": "Add `Set` to `EXTERNAL_TYPE_MAP`.", - "pr": 2350 - }, - { - "note": "Add `TFillData` to `EXTERNAL_TYPE_MAP`", - "pr": 2613 - } - ] - }, - { - "version": "1.0.6", - "changes": [ - { - "note": "Render date formats in UTC to prevent conflicts when publishing in different timezones.", - "pr": 1143 - }, - { - "note": "Add AssetBuyerError to the IGNORED_EXCESSIVE_TYPES array", - "pr": 1139 - }, - { - "note": "Add ForwarderError to the IGNORED_EXCESSIVE_TYPES array", - "pr": 1147 - }, - { - "note": "Fix a bug when hardcoded CHANGELOG paths cause fetching release notes to fail", - "pr": 1311 - }, - { - "note": "Added DutchAuctionWrapper to the CLASSES_WITH_HIDDEN_CONSTRUCTORS array", - "pr": 1465 - } - ] - }, - { - "timestamp": 1534210131, - "version": "1.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532614997, - "version": "1.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532605697, - "version": "1.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532551340, - "version": "1.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532357734, - "version": "1.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532043000, - "version": "1.0.0", - "changes": [ - { - "note": "Fix git remote tag removal step & add an additional sanity assertion", - "pr": 803 - }, - { - "note": "Make PR numbers links on Github releases" - } - ] - }, - { - "timestamp": 1531149657, - "version": "0.2.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1529397769, - "version": "0.2.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1529081166, - "version": "0.2.0", - "changes": [ - { - "note": "Add `prepublish_checks` script", - "pr": 650 - } - ] - }, - { - "timestamp": 1527008794, - "version": "0.1.20", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1525428773, - "version": "0.1.19", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1524044013, - "version": "0.1.18", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1523462196, - "version": "0.1.17", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1522658513, - "version": "0.1.16", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.1.13", - "changes": [ - { - "note": "Add postpublish utils" - } - ], - "timestamp": 1521298800 - } -] diff --git a/packages/monorepo-scripts/CHANGELOG.md b/packages/monorepo-scripts/CHANGELOG.md deleted file mode 100644 index 48b739f0e3..0000000000 --- a/packages/monorepo-scripts/CHANGELOG.md +++ /dev/null @@ -1,67 +0,0 @@ - - -CHANGELOG - -## v1.0.5 - _August 13, 2018_ - - * Dependencies updated - -## v1.0.4 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.3 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.2 - _July 25, 2018_ - - * Dependencies updated - -## v1.0.1 - _July 23, 2018_ - - * Dependencies updated - -## v1.0.0 - _July 19, 2018_ - - * Fix git remote tag removal step & add an additional sanity assertion (#803) - * Make PR numbers links on Github releases - -## v0.2.2 - _July 9, 2018_ - - * Dependencies updated - -## v0.2.1 - _June 19, 2018_ - - * Dependencies updated - -## v0.2.0 - _June 15, 2018_ - - * Add `prepublish_checks` script (#650) - -## v0.1.20 - _May 22, 2018_ - - * Dependencies updated - -## v0.1.19 - _May 4, 2018_ - - * Dependencies updated - -## v0.1.18 - _April 18, 2018_ - - * Dependencies updated - -## v0.1.17 - _April 11, 2018_ - - * Dependencies updated - -## v0.1.16 - _April 2, 2018_ - - * Dependencies updated - -## v0.1.13 - _March 17, 2018_ - - * Add postpublish utils diff --git a/packages/monorepo-scripts/README.md b/packages/monorepo-scripts/README.md deleted file mode 100644 index 11ab9c4079..0000000000 --- a/packages/monorepo-scripts/README.md +++ /dev/null @@ -1,75 +0,0 @@ -## Mono repo scripts - -This repository contains a few helpful scripts for working with this mono repo. - -#### Scripts - -**`yarn deps_versions`**: Since we are a Yarn workspaces monorepo, shared dependencies between packages in the monorepo get hoisted to a top-level `node_modules` directory. If two packages use different versions of the same dependency however, both get installed. To avoid having many versions of a dependency installed, we try to keep dependency versions the same across packages in the monorepo. This script will list any dependencies for which we have multiple versions installed. We can then go through them and try to consolidate to a single version where possible. - -**`yarn find_unused_deps`**: Sometimes we accidentally leave dependencies listed in `package.json` that are no longer being used. This script finds potential dependencies that might no longer be in use. Please verify that it is no longer in use before removing, the `depcheck` package we use under-the-hood doesn't handle some TS quirks perfectly. - -**`yarn test:publish`**: Execute a test-run of the publish script. This dry run won't actually publish, nor will it commit/push anything to Github. - -## Usage - -#### Dependency versions - -In order to reduce the size of this repo, we try and use the same versions of dependencies between packages. To make it easier to discover version discrepancies between packages, you can run: - -```bash -yarn script:deps_versions -``` - -This will list out any dependencies that differ in versions between packages. - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install dependencies - -If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: - -```bash -yarn config set workspaces-experimental true -``` - -Then install dependencies - -```bash -yarn install -``` - -### Build - -To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory: - -```bash -PKG=@0x/monorepo-scripts yarn build -``` - -Or continuously rebuild on change: - -```bash -PKG=@0x/monorepo-scripts yarn watch -``` - -### Clean - -```bash -yarn clean -``` - -### Lint - -```bash -yarn lint -``` - -### Run Tests - -```bash -yarn test -``` diff --git a/packages/monorepo-scripts/package.json b/packages/monorepo-scripts/package.json deleted file mode 100644 index e24803d7ba..0000000000 --- a/packages/monorepo-scripts/package.json +++ /dev/null @@ -1,75 +0,0 @@ -{ - "private": true, - "name": "@0x/monorepo-scripts", - "version": "1.0.54", - "engines": { - "node": ">=6.12" - }, - "description": "Helper scripts for the monorepo", - "main": "lib/index.js", - "types": "lib/index.d.ts", - "scripts": { - "build": "tsc -b", - "build:ci": "yarn build", - "lint": "tslint --format stylish --project .", - "fix": "tslint --fix --format stylish --project .", - "clean": "shx rm -rf lib", - "test:publish": "run-s build script:publish", - "find_unused_deps": "run-s build script:find_unused_deps", - "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:doc_generate": "node ./lib/doc_generate.js", - "script:publish_release_notes": "node ./lib/publish_release_notes.js" - }, - "repository": { - "type": "git", - "url": "https://github.com/0xProject/0x-monorepo.git" - }, - "license": "Apache-2.0", - "bugs": { - "url": "https://github.com/0xProject/0x-monorepo/issues" - }, - "homepage": "https://github.com/0xProject/0x-monorepo/packages/monorepo-scripts/README.md", - "devDependencies": { - "@types/glob": "5.0.35", - "@types/mkdirp": "^0.5.2", - "@types/node": "12.12.54", - "@types/rimraf": "^2.0.2", - "@types/semver": "5.5.0", - "@types/yargs": "^11.0.0", - "depcheck": "^0.6.9", - "make-promises-safe": "^1.1.0", - "npm-run-all": "^4.1.2", - "shx": "^0.2.2", - "tslint": "5.11.0", - "typescript": "3.0.1" - }, - "dependencies": { - "@0x/types": "^3.2.0", - "@0x/utils": "^5.5.1", - "@lerna/batch-packages": "^3.0.0-beta.18", - "@types/depcheck": "^0.6.0", - "async-child-process": "^1.1.1", - "chalk": "^2.3.0", - "es6-promisify": "^5.0.0", - "glob": "^7.1.2", - "isomorphic-fetch": "2.2.1", - "lodash": "^4.17.11", - "mkdirp": "^0.5.1", - "moment": "2.21.0", - "promisify-child-process": "^1.0.5", - "prompt": "^1.0.0", - "publish-release": "https://github.com/0xProject/publish-release.git#3f8be1105a356527f4b362ff456d94bf9a82f2ed", - "rimraf": "^2.6.2", - "semver": "5.5.0", - "semver-diff": "^2.1.0", - "semver-sort": "0.0.4", - "typedoc": "^0.15.0", - "yargs": "^10.0.3" - }, - "publishConfig": { - "access": "public" - } -} diff --git a/packages/monorepo-scripts/src/constants.ts b/packages/monorepo-scripts/src/constants.ts deleted file mode 100644 index c15bcabf48..0000000000 --- a/packages/monorepo-scripts/src/constants.ts +++ /dev/null @@ -1,11 +0,0 @@ -import * as path from 'path'; - -export const constants = { - monorepoRootPath: path.join(__dirname, '../../..'), - 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, - discordAlertWebhookUrl: process.env.DISCORD_GITHUB_RELEASE_WEBHOOK_URL, - releasesUrl: 'https://github.com/0xProject/0x-monorepo/releases', - dependenciesUpdatedMessage: 'Dependencies updated', -}; diff --git a/packages/monorepo-scripts/src/deps_versions.ts b/packages/monorepo-scripts/src/deps_versions.ts deleted file mode 100644 index bb7e50f517..0000000000 --- a/packages/monorepo-scripts/src/deps_versions.ts +++ /dev/null @@ -1,101 +0,0 @@ -#!/usr/bin/env node - -import { PackageJSON, PackageJSONConfig } from '@0x/types'; -import chalk from 'chalk'; -import { sync as globSync } from 'glob'; -import * as path from 'path'; - -import { utils } from './utils/utils'; - -interface Dependencies { - [depName: string]: string; -} -interface Versions { - [packageName: string]: string; -} -interface VersionsByDependency { - [depName: string]: Versions; -} - -interface ParsedDependencies { - ignored: VersionsByDependency; - included: VersionsByDependency; -} - -const PACKAGE_JSON_GLOB = '../../*/package.json'; - -const config = utils.readJSONFile(path.join(__dirname, '../../../package.json')) - .config as PackageJSONConfig; // tslint:disable-line no-unnecessary-type-assertion -const dependenciesWithIgnoredVersions: string[] = (config.ignoreDependencyVersions as string).split(' '); -const packagesWithIgnoredVersions: string[] = (config.ignoreDependencyVersionsForPackage as string).split(' '); - -if (require.main === module) { - const dependencies = parseDependencies(); - const ignoredMultiples = getDependenciesWithMultipleVersions(dependencies.ignored); - const multiples = getDependenciesWithMultipleVersions(dependencies.included); - printVersionsByDependency(multiples); - utils.log(`├── ${chalk.bold('IGNORED')}`); - printVersionsByDependency(ignoredMultiples); - if (Object.keys(multiples).length !== 0) { - utils.log( - `Some dependencies have multiple versions. Please fix by trying to find compatible versions. As a last resort, you can add space-separated exceptions to root package.json config.ignoreDependencyVersions`, - ); - process.exit(1); - } -} - -function getDependencies(_path: string): Dependencies { - const packageJSON = utils.readJSONFile(_path); - const dependencies = { - ...packageJSON.dependencies, - ...packageJSON.devDependencies, - }; - return dependencies; -} - -function parseDependencies(): ParsedDependencies { - const files = globSync(path.join(__dirname, PACKAGE_JSON_GLOB)); - const parsedDependencies: ParsedDependencies = { - ignored: {}, - included: {}, - }; - files.map(_path => { - const pathParts = _path.split('/'); - const packageName = pathParts[pathParts.length - 2]; - const packageCategory = packagesWithIgnoredVersions.includes(packageName) ? 'ignored' : 'included'; - const dependencies = getDependencies(_path); - Object.keys(dependencies).forEach((depName: string) => { - const category = dependenciesWithIgnoredVersions.includes(depName) ? 'ignored' : packageCategory; - if (parsedDependencies[category][depName] === undefined) { - parsedDependencies[category][depName] = {}; - } - const version = dependencies[depName]; - parsedDependencies[category][depName][packageName] = version; - }); - }); - return parsedDependencies; -} - -function getDependenciesWithMultipleVersions(versionsByDependency: VersionsByDependency): VersionsByDependency { - return Object.keys(versionsByDependency) - .filter((depName: string) => hasMultipleVersions(versionsByDependency[depName])) - .reduce((obj, depName: string) => { - obj[depName] = versionsByDependency[depName]; - return obj; - }, {}); -} - -function printVersionsByDependency(versionsByDependency: VersionsByDependency): void { - Object.keys(versionsByDependency).forEach((depName: string) => { - const versions: Versions = versionsByDependency[depName]; - utils.log(chalk.bold(depName)); - Object.keys(versions).forEach((packageName: string) => { - utils.log(`├── ${packageName} -> ${versions[packageName]}`); - }); - }); -} - -function hasMultipleVersions(versions: Versions): boolean { - const uniques = new Set(Object.values(versions)); - return uniques.size > 1; -} diff --git a/packages/monorepo-scripts/src/doc_gen_configs.ts b/packages/monorepo-scripts/src/doc_gen_configs.ts deleted file mode 100644 index d926e1f291..0000000000 --- a/packages/monorepo-scripts/src/doc_gen_configs.ts +++ /dev/null @@ -1,78 +0,0 @@ -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_MAP: { - Array: true, - BigNumber: true, - Error: true, - ErrorConstructor: true, - Buffer: true, - 'solc.StandardContractOutput': true, - 'solc.CompilerSettings': true, - Schema: true, - Uint8Array: true, - // HACK: CI can handle these without the namespace but some local setups (Jacob) require the namespace prefix - // This is duplicated until we can discover the source of the issue. - GanacheOpts: true, - keystore: true, - 'Ganache.GanacheOpts': true, - PromiseWithTransactionHash: true, - // HACK: Asset-swapper specifies marketSell and marketBuy quotes with a descriminant MarketOperation Type to ignore the error, linking Buy and Sell to MarketOperation - Buy: true, - Sell: true, - // HACK: Asset-swapper specifies TFillData as any type that extends FillData - TFillData: true, - IterableIterator: true, - Set: true, - Exclude: true, - }, - // 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', - 'AssetBuyerError', - 'ContractError', - 'SubscriptionErrors', - 'TypedDataError', - 'SwapQuoterError', - 'SwapQuoteConsumerError', - 'SwapQuoteGetOutputOpts', - 'SwapQuoteExecutionOpts', - 'ForwarderError', - 'CoordinatorServerError', - 'CoordinatorServerCancellationResponse', - 'EventCallback', - 'IndexedFilterValues', - 'OrderInfo', - 'TransactionOpts', - 'ContractEvent', - 'SendTransactionOpts', - 'AwaitTransactionOpts', - 'ContractFunctionObj', - 'ContractTxFunctionObj', - 'EventCallback ', - 'EnvVars', - 'GlobalStakeByStatus', - 'OwnerStakeByStatus', - 'StakingPoolById', - 'AssetData', - 'SingleAssetData', - 'ERC20AssetData', - 'ERC20BridgeAssetData', - 'ERC721AssetData', - 'ERC1155AssetData', - 'MultiAssetData', - 'StaticCallAssetData', - 'MultiAssetDataWithRecursiveDecoding', - 'OrderPrunerPermittedFeeTypes', - ], - // 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', '@0x/types'], -}; diff --git a/packages/monorepo-scripts/src/doc_generate.ts b/packages/monorepo-scripts/src/doc_generate.ts deleted file mode 100644 index bc20e49d88..0000000000 --- a/packages/monorepo-scripts/src/doc_generate.ts +++ /dev/null @@ -1,24 +0,0 @@ -import * as yargs from 'yargs'; - -import { DocGenerateUtils } from './utils/doc_generate_utils'; -import { utils } from './utils/utils'; - -const args = yargs - .option('package', { - describe: 'Monorepo sub-package for which to generate DocJSON', - type: 'string', - demandOption: true, - }) - .example("$0 --package '0x.js'", 'Full usage example').argv; - -(async () => { - const packageName = args.package; - - const docGenerateAndUploadUtils = new DocGenerateUtils(packageName); - await docGenerateAndUploadUtils.generateAndUploadDocsAsync(); - - process.exit(0); -})().catch(err => { - utils.log(err); - process.exit(1); -}); diff --git a/packages/monorepo-scripts/src/find_unused_dependencies.ts b/packages/monorepo-scripts/src/find_unused_dependencies.ts deleted file mode 100644 index 42b4b78901..0000000000 --- a/packages/monorepo-scripts/src/find_unused_dependencies.ts +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env node - -import * as depcheckAsync from 'depcheck'; -import * as _ from 'lodash'; - -import { constants } from './constants'; -import { utils } from './utils/utils'; - -// For some reason, `depcheck` hangs on some packages. Add them here. -const IGNORE_PACKAGES = ['@0x/sol-compiler']; - -(async () => { - utils.log('*** NOTE: Not all deps listed here are actually not required. ***'); - utils.log("*** `depcheck` isn't perfect so double check before actually removing any. ***\n"); - const packages = utils.getPackages(constants.monorepoRootPath); - for (const pkg of packages) { - if (_.includes(IGNORE_PACKAGES, pkg.packageJson.name)) { - continue; // skip - } - utils.log(`Checking ${pkg.packageJson.name} for unused deps. This might take a while...`); - - const configs = {}; - const { dependencies } = await depcheckAsync(pkg.location, configs); - if (!_.isEmpty(dependencies)) { - _.each(dependencies, dep => { - utils.log(dep); - }); - } - utils.log('\n'); - } -})().catch(err => { - utils.log(err); - process.exit(1); -}); diff --git a/packages/monorepo-scripts/src/globals.d.ts b/packages/monorepo-scripts/src/globals.d.ts deleted file mode 100644 index 2b25802eeb..0000000000 --- a/packages/monorepo-scripts/src/globals.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -declare module 'async-child-process'; -declare module 'publish-release'; -declare module 'es6-promisify'; -declare module 'semver-diff'; - -declare module 'prompt' { - const start: () => void; - const get: (promptMessages: string[], callback: (err: Error, result: string) => void) => void; -} - -// semver-sort declarations -declare module 'semver-sort' { - const desc: (versions: string[]) => string[]; -} - -declare module 'promisify-child-process'; -declare module '@lerna/batch-packages'; diff --git a/packages/monorepo-scripts/src/index.ts b/packages/monorepo-scripts/src/index.ts deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/monorepo-scripts/src/prepublish_checks.ts b/packages/monorepo-scripts/src/prepublish_checks.ts deleted file mode 100644 index 0c2b43a7d3..0000000000 --- a/packages/monorepo-scripts/src/prepublish_checks.ts +++ /dev/null @@ -1,228 +0,0 @@ -import * as _ from 'lodash'; -import { exec as execAsync } from 'promisify-child-process'; -import semver = require('semver'); -import semverSort = require('semver-sort'); - -import { constants } from './constants'; -import { Package } from './types'; -import { changelogUtils } from './utils/changelog_utils'; -import { configs } from './utils/configs'; -import { dockerHubUtils } from './utils/docker_hub_utils'; -import { npmUtils } from './utils/npm_utils'; -import { utils } from './utils/utils'; - -async function prepublishChecksAsync(): Promise { - const shouldIncludePrivate = false; - const updatedPublicPackages = await utils.getPackagesToPublishAsync(shouldIncludePrivate); - - await checkCurrentVersionMatchesLatestPublishedNPMPackageAsync(updatedPublicPackages); - await checkChangelogFormatAsync(updatedPublicPackages); - await checkGitTagsForNextVersionAndDeleteIfExistAsync(updatedPublicPackages); - await checkPublishRequiredSetupAsync(updatedPublicPackages); - await checkDockerHubSetupAsync(); -} - -async function checkDockerHubSetupAsync(): Promise { - await dockerHubUtils.checkUserAddedToOrganizationOrThrowAsync(configs.DOCKER_HUB_ORG); - await dockerHubUtils.loginUserToDockerCommandlineOrThrowAsync(); -} - -async function checkGitTagsForNextVersionAndDeleteIfExistAsync(updatedPublicPackages: Package[]): Promise { - const packageNames = _.map(updatedPublicPackages, pkg => pkg.packageJson.name); - const localGitTags = await utils.getLocalGitTagsAsync(); - const localTagVersionsByPackageName = await utils.getGitTagsByPackageNameAsync(packageNames, localGitTags); - - const remoteGitTags = await utils.getRemoteGitTagsAsync(); - const remoteTagVersionsByPackageName = await utils.getGitTagsByPackageNameAsync(packageNames, remoteGitTags); - - for (const pkg of updatedPublicPackages) { - const currentVersion = pkg.packageJson.version; - const packageName = pkg.packageJson.name; - const packageLocation = pkg.location; - const nextVersion = await utils.getNextPackageVersionAsync(currentVersion, packageName, packageLocation); - - const remoteTagVersions = remoteTagVersionsByPackageName[packageName]; - if (_.includes(remoteTagVersions, nextVersion)) { - const tagName = `:refs/tags/${packageName}@${nextVersion}`; - await utils.removeRemoteTagAsync(tagName); - } - - const localTagVersions = localTagVersionsByPackageName[packageName]; - if (_.includes(localTagVersions, nextVersion)) { - const tagName = `${packageName}@${nextVersion}`; - await utils.removeLocalTagAsync(tagName); - } - } -} - -async function checkCurrentVersionMatchesLatestPublishedNPMPackageAsync( - updatedPublicPackages: Package[], -): Promise { - utils.log('Check package versions against npm registry...'); - const versionMismatches = []; - for (const pkg of updatedPublicPackages) { - const packageName = pkg.packageJson.name; - const packageVersion = pkg.packageJson.version; - const packageRegistryJsonIfExists = await npmUtils.getPackageRegistryJsonIfExistsAsync(packageName); - if (packageRegistryJsonIfExists === undefined) { - continue; // noop for packages not yet published to NPM - } - const allVersionsIncludingUnpublished = npmUtils.getPreviouslyPublishedVersions(packageRegistryJsonIfExists); - const sortedVersions = semverSort.desc(allVersionsIncludingUnpublished); - const latestNPMVersion = sortedVersions[0]; - if (packageVersion !== latestNPMVersion) { - versionMismatches.push({ - packageJsonVersion: packageVersion, - npmVersion: latestNPMVersion, - packageName, - }); - } - } - if (!_.isEmpty(versionMismatches)) { - utils.log(`Found version mismatches between package.json and NPM published versions (might be unpublished).`); - _.each(versionMismatches, versionMismatch => { - utils.log( - `${versionMismatch.packageName}: ${versionMismatch.packageJsonVersion} package.json, ${ - versionMismatch.npmVersion - } on NPM`, - ); - }); - throw new Error(`Please fix the above package.json/NPM inconsistencies.`); - } -} - -async function checkChangelogFormatAsync(updatedPublicPackages: Package[]): Promise { - utils.log('Check CHANGELOGs for inconsistencies...'); - const changeLogInconsistencies = []; - for (const pkg of updatedPublicPackages) { - const packageName = pkg.packageJson.name; - const changelog = changelogUtils.getChangelogOrCreateIfMissing(packageName, pkg.location); - - const currentVersion = pkg.packageJson.version; - if (!_.isEmpty(changelog)) { - const lastEntry = changelog[0]; - const doesLastEntryHaveTimestamp = lastEntry.timestamp !== undefined; - if (semver.lt(lastEntry.version, currentVersion)) { - changeLogInconsistencies.push({ - packageJsonVersion: currentVersion, - changelogVersion: lastEntry.version, - packageName, - }); - } else if (semver.gt(lastEntry.version, currentVersion) && doesLastEntryHaveTimestamp) { - // Remove incorrectly added timestamp - delete changelog[0].timestamp; - // Save updated CHANGELOG.json - await changelogUtils.writeChangelogJsonFileAsync(pkg.location, changelog); - utils.log(`${packageName}: Removed timestamp from latest CHANGELOG.json entry.`); - } - } - } - if (!_.isEmpty(changeLogInconsistencies)) { - utils.log(`CHANGELOG versions cannot below package.json versions:`); - _.each(changeLogInconsistencies, inconsistency => { - utils.log( - `${inconsistency.packageName}: ${inconsistency.packageJsonVersion} package.json, ${ - inconsistency.changelogVersion - } CHANGELOG.json`, - ); - }); - throw new Error('Fix the above inconsistencies to continue.'); - } -} - -async function checkPublishRequiredSetupAsync(updatedPublicPackages: Package[]): Promise { - // check to see if logged into npm before publishing - try { - // HACK: for some reason on some setups, the `npm whoami` will not recognize a logged-in user - // unless run with `sudo` (i.e Fabio's NVM setup) but is fine for others (Jacob's NVM setup). - utils.log('Checking that the user is logged in on npm...'); - await execAsync(`sudo npm whoami`); - } catch (err) { - throw new Error('You must be logged into npm in the commandline to publish. Run `npm login` and try again.'); - } - - // check to see that all required write permissions exist - utils.log(`Checking that all necessary npm write permissions exist...`); - const pkgPermissionsResult = await execAsync(`sudo npm access ls-packages`); - const pkgPermissions = JSON.parse(pkgPermissionsResult.stdout); - const writePermissions = Object.keys(pkgPermissions).filter(pkgName => { - return pkgPermissions[pkgName] === 'read-write'; - }); - const unwriteablePkgs = []; - for (const pkg of updatedPublicPackages) { - const isPackagePublished = - (await npmUtils.getPackageRegistryJsonIfExistsAsync(pkg.packageJson.name)) !== undefined; - const isPackageWritePermissionsGranted = writePermissions.includes(pkg.packageJson.name); - if (isPackagePublished && !isPackageWritePermissionsGranted) { - unwriteablePkgs.push(pkg); - } - } - if (unwriteablePkgs.length > 0) { - utils.log(`Missing write permissions for the following packages:`); - unwriteablePkgs.forEach(pkg => { - utils.log(pkg.packageJson.name); - }); - throw new Error(`Obtain necessary write permissions to continue.`); - } - - // Check to see if Git personal token setup - if (constants.githubPersonalAccessToken === undefined) { - throw new Error( - 'You must have a Github personal access token set to an envVar named `GITHUB_PERSONAL_ACCESS_TOKEN_0X_JS`. Add it then try again.', - ); - } - - // Check to see if discord URL is set up - if (constants.discordAlertWebhookUrl === undefined) { - throw new Error( - 'You must have a discord webhook URL set to an envVar named `DISCORD_GITHUB_RELEASE_WEBHOOK_URL`. Add it then try again.', - ); - } - - // Check Yarn version is 1.X - utils.log('Checking the yarn version...'); - const result = await execAsync(`yarn --version`); - const version = result.stdout; - const versionSegments = version.split('.'); - const majorVersion = _.parseInt(versionSegments[0]); - if (majorVersion < 1) { - throw new Error('Your yarn version must be v1.x or higher. Upgrade yarn and try again.'); - } - - // Check that `aws` commandline tool is installed - try { - utils.log('Checking that aws CLI tool is installed...'); - await execAsync(`aws help`); - } catch (err) { - throw new Error('You must have `awscli` commandline tool installed. Install it and try again.'); - } - - // Check that `aws` credentials are setup - try { - utils.log('Checking that aws credentials are configured...'); - await execAsync(`aws sts get-caller-identity`); - } catch (err) { - throw new Error('You must setup your AWS credentials by running `aws configure`. Do this and try again.'); - } - - utils.log('Checking that git branch is up to date with upstream...'); - await execAsync('git fetch'); - const res = await execAsync('git status -bs'); // s - short format, b - branch info - /** - * Possible outcomes - * ## branch_name...origin/branch_name [behind n] - * ## branch_name...origin/branch_name [ahead n] - * ## branch_name...origin/branch_name - */ - const gitShortStatusHeader = res.stdout.split('\n')[0]; - if (gitShortStatusHeader.includes('behind')) { - throw new Error('Your branch is behind upstream. Please pull before publishing.'); - } else if (gitShortStatusHeader.includes('ahead')) { - throw new Error('Your branch is ahead of upstream. Please push before publishing.'); - } -} - -prepublishChecksAsync().catch(err => { - utils.log(err); - process.exit(1); -}); diff --git a/packages/monorepo-scripts/src/publish.ts b/packages/monorepo-scripts/src/publish.ts deleted file mode 100644 index 697b599831..0000000000 --- a/packages/monorepo-scripts/src/publish.ts +++ /dev/null @@ -1,304 +0,0 @@ -#!/usr/bin/env node - -import { PackageJSON } from '@0x/types'; -import { logUtils } from '@0x/utils'; -import { spawn } from 'child_process'; -import * as promisify from 'es6-promisify'; -import * as fs from 'fs'; -import * as _ from 'lodash'; -import * as moment from 'moment'; -import * as path from 'path'; -import { exec as execAsync, spawn as spawnAsync } from 'promisify-child-process'; -import * as prompt from 'prompt'; -import semver = require('semver'); -import semverSort = require('semver-sort'); - -import { constants } from './constants'; -import { Package, PackageToNextVersion, VersionChangelog } from './types'; -import { changelogUtils } from './utils/changelog_utils'; -import { configs } from './utils/configs'; -import { alertDiscordAsync } from './utils/discord'; -import { DocGenerateUtils } from './utils/doc_generate_utils'; -import { publishReleaseNotesAsync } from './utils/github_release_utils'; -import { utils } from './utils/utils'; - -const TODAYS_TIMESTAMP = moment().unix(); - -async function confirmAsync(message: string): Promise { - prompt.start(); - const result = await promisify(prompt.get)([message]); - const didConfirm = result[message] === 'y'; - if (!didConfirm) { - utils.log('Publish process aborted.'); - process.exit(0); - } -} - -(async () => { - // Fetch public, updated Lerna packages - const shouldIncludePrivate = true; - const allPackagesToPublish = await utils.getPackagesToPublishAsync(shouldIncludePrivate); - if (_.isEmpty(allPackagesToPublish)) { - utils.log('No packages need publishing'); - process.exit(0); - } - const packagesWithDocs = getPackagesWithDocs(allPackagesToPublish); - - 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)', - ); - } - - // Update CHANGELOGs - const updatedPublicPackages = _.filter(allPackagesToPublish, pkg => !pkg.packageJson.private); - const updatedPublicPackageNames = _.map(updatedPublicPackages, pkg => pkg.packageJson.name); - utils.log(`Will update CHANGELOGs and publish: \n${updatedPublicPackageNames.join('\n')}\n`); - const packageToNextVersion = await updateChangeLogsAsync(updatedPublicPackages); - - const updatedPrivatePackages = _.filter(allPackagesToPublish, pkg => pkg.packageJson.private); - _.each(updatedPrivatePackages, pkg => { - const currentVersion = pkg.packageJson.version; - const packageName = pkg.packageJson.name; - const nextPatchVersionIfValid = semver.inc(currentVersion, 'patch'); - if (nextPatchVersionIfValid !== null) { - packageToNextVersion[packageName] = nextPatchVersionIfValid; - } else { - throw new Error(`Encountered invalid semver version: ${currentVersion} for package: ${packageName}`); - } - }); - - // Push changelogs changes and markdown docs to Github - if (!configs.IS_LOCAL_PUBLISH) { - // Generate markdown docs for packages - await generateDocMDAsync(packagesWithDocs); - await pushChangelogsAndMDDocsToGithubAsync(); - } - - // Call LernaPublish - utils.log('Version updates to apply:'); - _.each(packageToNextVersion, (versionChange: string, packageName: string) => { - utils.log(`${packageName} -> ${versionChange}`); - }); - utils.log(`Calling 'lerna publish'...`); - await lernaPublishAsync(packageToNextVersion); - - const isDryRun = configs.IS_LOCAL_PUBLISH; - if (!isDryRun) { - // Publish docker images to DockerHub - await publishImagesToDockerHubAsync(allPackagesToPublish); - - // Upload markdown docs to S3 bucket - await execAsync(`yarn upload_md_docs`, { cwd: constants.monorepoRootPath }); - } - - const releaseNotes = await publishReleaseNotesAsync(updatedPublicPackages, isDryRun); - utils.log('Published release notes'); - - if (!isDryRun && releaseNotes) { - try { - await alertDiscordAsync(releaseNotes); - } catch (e) { - utils.log("Publish successful, but couldn't auto-alert discord (", e.message, '), Please alert manually.'); - } - } - process.exit(0); -})().catch(err => { - utils.log(err); - process.exit(1); -}); - -async function publishImagesToDockerHubAsync(allUpdatedPackages: Package[]): Promise { - for (const pkg of allUpdatedPackages) { - const packageJSON = pkg.packageJson; - const shouldPublishDockerImage = - packageJSON.config !== undefined && - packageJSON.config.postpublish !== undefined && - packageJSON.config.postpublish.dockerHubRepo !== undefined; - if (!shouldPublishDockerImage) { - continue; - } - const dockerHubRepo = _.get(packageJSON, 'config.postpublish.dockerHubRepo'); - const pkgName = pkg.packageJson.name; - const packageDirName = _.startsWith(pkgName, '@0x/') ? pkgName.split('/')[1] : pkgName; - - // Build the Docker image - logUtils.log(`Building '${dockerHubRepo}' docker image...`); - await spawnAsync('docker', ['build', '-t', dockerHubRepo, '.'], { - cwd: `${constants.monorepoRootPath}/packages/${packageDirName}`, - }); - - // Tag the docker image with the latest version - const version = pkg.packageJson.version; - logUtils.log(`Tagging '${dockerHubRepo}' docker image with version ${version}...`); - await execAsync(`docker tag ${dockerHubRepo} ${configs.DOCKER_HUB_ORG}/${dockerHubRepo}:${version}`); - await execAsync(`docker tag ${dockerHubRepo} ${configs.DOCKER_HUB_ORG}/${dockerHubRepo}:latest`); - - // Publish to DockerHub - logUtils.log(`Pushing '${dockerHubRepo}' docker image to DockerHub...`); - await execAsync(`docker push ${configs.DOCKER_HUB_ORG}/${dockerHubRepo}:${version}`); - await execAsync(`docker push ${configs.DOCKER_HUB_ORG}/${dockerHubRepo}:latest`); - } -} - -function getPackagesWithDocs(allUpdatedPackages: Package[]): Package[] { - const rootPackageJsonPath = `${constants.monorepoRootPath}/package.json`; - const rootPackageJSON = utils.readJSONFile(rootPackageJsonPath); - const packagesWithDocPagesStringIfExist = _.get(rootPackageJSON, 'config.packagesWithDocPages', undefined); - if (packagesWithDocPagesStringIfExist === undefined) { - return []; // None to generate & publish - } - const packagesWithDocPages = packagesWithDocPagesStringIfExist.split(' '); - const updatedPackagesWithDocPages: Package[] = []; - _.each(allUpdatedPackages, pkg => { - const nameWithoutPrefix = pkg.packageJson.name.replace('@0x/', ''); - if (_.includes(packagesWithDocPages, nameWithoutPrefix)) { - updatedPackagesWithDocPages.push(pkg); - } - }); - return updatedPackagesWithDocPages; -} - -async function generateDocMDAsync(packagesWithDocs: Package[]): Promise { - for (const pkg of packagesWithDocs) { - const nameWithoutPrefix = pkg.packageJson.name.replace('@0x/', ''); - const docGenerateAndUploadUtils = new DocGenerateUtils(nameWithoutPrefix); - await docGenerateAndUploadUtils.generateAndUploadDocsAsync(); - } -} - -async function pushChangelogsAndMDDocsToGithubAsync(): Promise { - await execAsync(`git add . --all`, { cwd: constants.monorepoRootPath }); - await execAsync(`git commit -m "Updated CHANGELOGS & MD docs"`, { cwd: constants.monorepoRootPath }); - await execAsync(`git push`, { cwd: constants.monorepoRootPath }); - utils.log(`Pushed CHANGELOG updates & updated MD docs to Github`); -} - -async function updateChangeLogsAsync(updatedPublicPackages: Package[]): Promise { - const packageToNextVersion: PackageToNextVersion = {}; - for (const pkg of updatedPublicPackages) { - const packageName = pkg.packageJson.name; - let changelog = changelogUtils.getChangelogOrCreateIfMissing(packageName, pkg.location); - - const currentVersion = pkg.packageJson.version; - const shouldAddNewEntry = changelogUtils.shouldAddNewChangelogEntry( - pkg.packageJson.name, - currentVersion, - changelog, - ); - if (shouldAddNewEntry) { - // Create a new entry for a patch version with generic changelog entry. - const nextPatchVersionIfValid = semver.inc(currentVersion, 'patch'); - if (nextPatchVersionIfValid === null) { - throw new Error(`Encountered invalid semver version: ${currentVersion} for package: ${packageName}`); - } - const newChangelogEntry: VersionChangelog = { - timestamp: TODAYS_TIMESTAMP, - version: nextPatchVersionIfValid, - changes: [ - { - note: constants.dependenciesUpdatedMessage, - }, - ], - }; - changelog = [newChangelogEntry, ...changelog]; - packageToNextVersion[packageName] = nextPatchVersionIfValid; - } else { - // Update existing entry with timestamp - const lastEntry = changelog[0]; - if (lastEntry.timestamp === undefined) { - lastEntry.timestamp = TODAYS_TIMESTAMP; - } - // Check version number is correct. - const proposedNextVersion = lastEntry.version; - lastEntry.version = updateVersionNumberIfNeeded(currentVersion, proposedNextVersion); - changelog[0] = lastEntry; - packageToNextVersion[packageName] = lastEntry.version; - } - - // Save updated CHANGELOG.json - await changelogUtils.writeChangelogJsonFileAsync(pkg.location, changelog); - utils.log(`${packageName}: Updated CHANGELOG.json`); - // Generate updated CHANGELOG.md - const changelogMd = changelogUtils.generateChangelogMd(changelog); - await changelogUtils.writeChangelogMdFileAsync(pkg.location, changelogMd); - utils.log(`${packageName}: Updated CHANGELOG.md`); - } - - return packageToNextVersion; -} - -async function lernaPublishAsync(packageToNextVersion: { [name: string]: string }): Promise { - return new Promise((resolve, reject) => { - const packageVersionString = _.map(packageToNextVersion, (nextVersion: string, packageName: string) => { - return `${packageName}|${nextVersion}`; - }).join(','); - // HACK(fabio): Previously we would pass the packageVersionString directly to `lerna publish` using the - // `--cdVersions` flag. Since we now need to use `spawn` instead of `exec` when calling Lerna, passing - // them as a string arg is causing `spawn` to error with `ENAMETOOLONG`. In order to shorten the args - // passed to `spawn` we now write the new version to a file and pass the filepath to the `cdVersions` arg. - const cdVersionsFilepath = path.join(__dirname, 'cd_versions.txt'); - fs.writeFileSync(cdVersionsFilepath, packageVersionString); - const lernaPublishCmd = `node`; - const lernaPublishArgs = [ - `${constants.lernaExecutable}`, - 'publish', - `--cdVersions=${cdVersionsFilepath}`, - `--registry=${configs.NPM_REGISTRY_URL}`, - `--yes`, - ]; - if (configs.IS_LOCAL_PUBLISH) { - lernaPublishArgs.push('--no-git-tag-version'); - lernaPublishArgs.push('--no-push'); - } - if (configs.DIST_TAG !== '') { - lernaPublishArgs.push(`--dist-tag=${configs.DIST_TAG}`); - } - utils.log('Lerna is publishing...'); - try { - const child = spawn(lernaPublishCmd, lernaPublishArgs, { - cwd: constants.monorepoRootPath, - }); - child.stdout.on('data', async (data: Buffer) => { - const output = data.toString('utf8'); - utils.log('Lerna publish cmd: ', output); - const isOTPPrompt = _.includes(output, 'Enter OTP:'); - if (isOTPPrompt) { - // Prompt for OTP - prompt.start(); - const result = await promisify(prompt.get)(['OTP']); - child.stdin.write(`${result.OTP}\n`); - } - const didFinishPublishing = _.includes(output, 'Successfully published:'); - if (didFinishPublishing) { - // Remove temporary cdVersions file - fs.unlinkSync(cdVersionsFilepath); - resolve(); - } - }); - child.stderr.on('data', (data: Buffer) => { - const output = data.toString('utf8'); - utils.log('Lerna publish cmd: ', output); - }); - } catch (err) { - // Remove temporary cdVersions file - fs.unlinkSync(cdVersionsFilepath); - reject(err); - } - }); -} - -function updateVersionNumberIfNeeded(currentVersion: string, proposedNextVersion: string): string { - const updatedVersionIfValid = semver.inc(currentVersion, 'patch'); - if (updatedVersionIfValid === null) { - throw new Error(`Encountered invalid semver: ${currentVersion}`); - } - if (proposedNextVersion === currentVersion) { - return updatedVersionIfValid; - } - const sortedVersions = semverSort.desc([proposedNextVersion, currentVersion]); - if (sortedVersions[0] !== proposedNextVersion) { - return updatedVersionIfValid; - } - return proposedNextVersion; -} diff --git a/packages/monorepo-scripts/src/publish_release_notes.ts b/packages/monorepo-scripts/src/publish_release_notes.ts deleted file mode 100644 index 2d03249e6b..0000000000 --- a/packages/monorepo-scripts/src/publish_release_notes.ts +++ /dev/null @@ -1,36 +0,0 @@ -import * as _ from 'lodash'; -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, - }) - .option('packages', { - describe: - 'Space-separated list of packages to generated release notes for. If not supplied, it does all `Lerna updated` packages.', - type: 'string', - }) - .example('$0 --isDryRun true --packages "0x.js @0x/web3-wrapper"', 'Full usage example').argv; - -(async () => { - const isDryRun = args.isDryRun; - let packages; - if (args.packages === undefined) { - const shouldIncludePrivate = false; - packages = await utils.getPackagesToPublishAsync(shouldIncludePrivate); - } else { - const packageNames = args.packages.split(' '); - packages = await utils.getPackagesByNameAsync(packageNames); - } - - await publishReleaseNotesAsync(packages, isDryRun); - process.exit(0); -})().catch(err => { - utils.log(err); - process.exit(1); -}); diff --git a/packages/monorepo-scripts/src/test_installation.ts b/packages/monorepo-scripts/src/test_installation.ts deleted file mode 100644 index f546b224fb..0000000000 --- a/packages/monorepo-scripts/src/test_installation.ts +++ /dev/null @@ -1,163 +0,0 @@ -#!/usr/bin/env node - -import * as fs from 'fs'; -import * as _ from 'lodash'; -import * as mkdirp from 'mkdirp'; -import * as path from 'path'; -import { exec as execAsync } from 'promisify-child-process'; -import * as rimraf from 'rimraf'; -import { promisify } from 'util'; - -import { Changelog, Package } from './types'; -import { utils } from './utils/utils'; - -// Packages might not be runnable if they are command-line tools or only run in browsers. -const UNRUNNABLE_PACKAGES = ['@0x/abi-gen']; -// HACK(fabio): Temporarily adding '@0x/contracts-coordinator', '@0x/contracts-extensions' since they -// aren't working in the V3 branch yet. -// TODO(dorothy-zbornak): Remove '@0x/contracts-coordinator', '@0x/contracts-extensions' after updating -// these packages for 3.0. -const UNINSTALLABLE_PACKAGES = ['@0x/contracts-coordinator', '@0x/contracts-extensions']; - -const mkdirpAsync = promisify(mkdirp); -const rimrafAsync = promisify(rimraf); -const writeFileAsync = promisify(fs.writeFile); - -interface PackageErr { - packageName: string; - error: ExecError; -} - -interface ExecError { - message: string; - stack: string; - stderr: string; - stdout: string; -} - -// returns the index for the given package name. -function findPackageIndex(packages: Package[], packageName: string): number { - return _.findIndex(packages, pkg => pkg.packageJson.name === packageName); -} - -function logIfDefined(x: any): void { - if (x !== undefined) { - utils.log(x); - } -} - -// tslint:disable-next-line:custom-no-magic-numbers -const FIVE_MB = 1024 * 1024 * 5; - -(async () => { - const IS_LOCAL_PUBLISH = process.env.IS_LOCAL_PUBLISH === 'true'; - const registry = IS_LOCAL_PUBLISH ? 'http://localhost:4873/' : 'https://registry.npmjs.org/'; - const monorepoRootPath = path.join(__dirname, '../../..'); - // We sort error messages according to package topology so that we can see - // them in a more intuitive order. E.g. if package A has an error and - // package B imports it, the tests for both package A and package B will - // fail. But package B only fails because of an error in package A. - // Since the error in package A is the root cause, we log it first. - const packages = utils.getTopologicallySortedPackages(monorepoRootPath); - const installablePackages = _.filter(packages, pkg => { - return ( - !pkg.packageJson.private && - pkg.packageJson.main !== undefined && - pkg.packageJson.main.endsWith('.js') && - !UNINSTALLABLE_PACKAGES.includes(pkg.packageJson.name) - ); - }); - const CHUNK_SIZE = 15; - const chunkedInstallablePackages = _.chunk(installablePackages, CHUNK_SIZE); - utils.log(`Testing all packages in ${chunkedInstallablePackages.length} chunks`); - for (const installablePackagesChunk of chunkedInstallablePackages) { - utils.log('Testing packages:'); - _.map(installablePackagesChunk, pkg => utils.log(`* ${pkg.packageJson.name}`)); - // Run all package tests within that chunk asynchronously and push promises into an array so - // we can wait for all of them to resolve. - const promises: Array> = []; - const errors: PackageErr[] = []; - for (const installablePackage of installablePackagesChunk) { - const packagePromise = testInstallPackageAsync(monorepoRootPath, registry, installablePackage).catch( - error => { - errors.push({ packageName: installablePackage.packageJson.name, error }); - }, - ); - promises.push(packagePromise); - } - await Promise.all(promises); - if (errors.length > 0) { - const topologicallySortedErrors = _.sortBy(errors, packageErr => - findPackageIndex(packages, packageErr.packageName), - ); - _.forEach(topologicallySortedErrors, packageError => { - utils.log(`ERROR in package ${packageError.packageName}:`); - logIfDefined(packageError.error.message); - logIfDefined(packageError.error.stderr); - logIfDefined(packageError.error.stdout); - logIfDefined(packageError.error.stack); - }); - process.exit(1); - } - } - process.exit(0); -})().catch(err => { - utils.log(`Unexpected error: ${err.message}`); - process.exit(1); -}); - -async function testInstallPackageAsync( - monorepoRootPath: string, - registry: string, - installablePackage: Package, -): Promise { - const changelogPath = path.join(installablePackage.location, 'CHANGELOG.json'); - const lastChangelogVersion = utils.readJSONFile(changelogPath)[0].version; - const packageName = installablePackage.packageJson.name; - utils.log(`Testing ${packageName}@${lastChangelogVersion}`); - const packageDirName = path.join(...`${packageName}-test`.split('/')); - // NOTE(fabio): The `testDirectory` needs to be somewhere **outside** the monorepo root directory. - // Otherwise, it will have access to the hoisted `node_modules` directory and the TypeScript missing - // type errors will not be caught. - const testDirectory = path.join(monorepoRootPath, '..', '.installation-test', packageDirName); - await rimrafAsync(testDirectory); - await mkdirpAsync(testDirectory); - await execAsync('yarn init --yes', { cwd: testDirectory }); - const npmrcFilePath = path.join(testDirectory, '.npmrc'); - await writeFileAsync(npmrcFilePath, `registry=${registry}`); - utils.log(`Installing ${packageName}@${lastChangelogVersion}`); - await execAsync(`npm install --save ${packageName}@${lastChangelogVersion} --registry=${registry}`, { - cwd: testDirectory, - maxBuffer: FIVE_MB, - }); - const indexFilePath = path.join(testDirectory, 'index.ts'); - await writeFileAsync(indexFilePath, `import * as Package from '${packageName}';\nconsole.log(Package);\n`); - const tsConfig = { - compilerOptions: { - typeRoots: ['node_modules/@0x/typescript-typings/types', 'node_modules/@types'], - module: 'commonjs', - target: 'es5', - lib: ['es2017', 'dom'], - declaration: true, - noImplicitReturns: true, - pretty: true, - strict: true, - resolveJsonModule: true, - }, - include: ['index.ts'], - }; - const tsconfigFilePath = path.join(testDirectory, 'tsconfig.json'); - await writeFileAsync(tsconfigFilePath, JSON.stringify(tsConfig, null, '\t')); - utils.log(`Compiling ${packageName}`); - const tscBinaryPath = path.join(monorepoRootPath, './node_modules/typescript/bin/tsc'); - await execAsync(tscBinaryPath, { cwd: testDirectory }); - utils.log(`Successfully compiled with ${packageName} as a dependency`); - const isUnrunnablePkg = _.includes(UNRUNNABLE_PACKAGES, packageName); - if (!isUnrunnablePkg) { - const transpiledIndexFilePath = path.join(testDirectory, 'index.js'); - utils.log(`Running test script with ${packageName} imported`); - await execAsync(`node ${transpiledIndexFilePath}`, { maxBuffer: FIVE_MB }); - utils.log(`Successfully ran test script with ${packageName} imported`); - } - await rimrafAsync(testDirectory); -} diff --git a/packages/monorepo-scripts/src/types.ts b/packages/monorepo-scripts/src/types.ts deleted file mode 100644 index 6bacb76411..0000000000 --- a/packages/monorepo-scripts/src/types.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { PackageJSON } from '@0x/types'; - -export interface UpdatedPackage { - name: string; - version: string; - private: boolean; -} - -export interface Change { - note: string; - pr?: number; -} - -export type Changelog = VersionChangelog[]; - -export interface VersionChangelog { - timestamp?: number; - version: string; - changes: Change[]; -} - -export interface PackageToNextVersion { - [name: string]: string; -} - -export interface PackageRegistryJson { - versions: { - [version: string]: any; - }; - time: { - [version: string]: string; - }; -} - -export interface GitTagsByPackageName { - [packageName: string]: string[]; -} - -export interface Package { - location: string; - packageJson: PackageJSON; -} - -export interface DocGenConfigs { - DOC_JSON_VERSION: string; - EXTERNAL_TYPE_MAP: { [externalType: string]: boolean }; - 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[]; -} diff --git a/packages/monorepo-scripts/src/utils/changelog_utils.ts b/packages/monorepo-scripts/src/utils/changelog_utils.ts deleted file mode 100644 index 0373c05c0e..0000000000 --- a/packages/monorepo-scripts/src/utils/changelog_utils.ts +++ /dev/null @@ -1,102 +0,0 @@ -import * as fs from 'fs'; -import * as _ from 'lodash'; -import * as moment from 'moment'; -import * as path from 'path'; -import { exec as execAsync } from 'promisify-child-process'; -import semver = require('semver'); - -import { constants } from '../constants'; -import { Change, Changelog, VersionChangelog } from '../types'; - -const CHANGELOG_MD_HEADER = ` - - -CHANGELOG -`; - -export const changelogUtils = { - getChangelogMdTitle(versionChangelog: VersionChangelog): string { - // Use UTC rather than the local machines time (formatted date time is +0:00) - const date = moment.utc(`${versionChangelog.timestamp}`, 'X').format('MMMM D, YYYY'); - const title = `\n## v${versionChangelog.version} - _${date}_\n\n`; - return title; - }, - getChangelogMdChange(change: Change): string { - let line = ` * ${change.note}`; - if (change.pr !== undefined) { - line += ` (#${change.pr})`; - } - return line; - }, - generateChangelogMd(changelog: Changelog): string { - let changelogMd = CHANGELOG_MD_HEADER; - _.each(changelog, versionChangelog => { - const title = changelogUtils.getChangelogMdTitle(versionChangelog); - changelogMd += title; - const changelogVersionLines = _.map( - versionChangelog.changes, - changelogUtils.getChangelogMdChange.bind(changelogUtils), - ); - changelogMd += `${_.join(changelogVersionLines, '\n')}`; - }); - - return changelogMd; - }, - shouldAddNewChangelogEntry(packageName: string, currentVersion: string, changelog: Changelog): boolean { - if (_.isEmpty(changelog)) { - return true; - } - const lastEntry = changelog[0]; - if (semver.lt(lastEntry.version, currentVersion)) { - throw new Error( - `Found CHANGELOG version lower then current package version. ${packageName} current: ${currentVersion}, Changelog: ${ - lastEntry.version - }`, - ); - } - const isLastEntryCurrentVersion = lastEntry.version === currentVersion; - return isLastEntryCurrentVersion; - }, - getChangelogJSONIfExists(changelogPath: string): string | undefined { - try { - const changelogJSON = fs.readFileSync(changelogPath, 'utf-8'); - return changelogJSON; - } catch (err) { - return undefined; - } - }, - getChangelogOrCreateIfMissing(packageName: string, packageLocation: string): Changelog { - const changelogJSONPath = path.join(packageLocation, 'CHANGELOG.json'); - let changelogJsonIfExists = changelogUtils.getChangelogJSONIfExists(changelogJSONPath); - if (changelogJsonIfExists === undefined) { - // If none exists, create new, empty one. - changelogJsonIfExists = '[]'; - fs.writeFileSync(changelogJSONPath, changelogJsonIfExists); - } - let changelog: Changelog; - try { - changelog = JSON.parse(changelogJsonIfExists); - } catch (err) { - throw new Error(`${packageName}'s CHANGELOG.json contains invalid JSON. Please fix and try again.`); - } - return changelog; - }, - async writeChangelogJsonFileAsync(packageLocation: string, changelog: Changelog): Promise { - const changelogJSONPath = path.join(packageLocation, 'CHANGELOG.json'); - fs.writeFileSync(changelogJSONPath, JSON.stringify(changelog, null, '\t')); - await changelogUtils.prettifyAsync(changelogJSONPath, constants.monorepoRootPath); - }, - async writeChangelogMdFileAsync(packageLocation: string, changelogMdString: string): Promise { - const changelogMarkdownPath = path.join(packageLocation, 'CHANGELOG.md'); - fs.writeFileSync(changelogMarkdownPath, changelogMdString); - await changelogUtils.prettifyAsync(changelogMarkdownPath, constants.monorepoRootPath); - }, - async prettifyAsync(filePath: string, cwd: string): Promise { - await execAsync(`prettier --write ${filePath} --config .prettierrc`, { - cwd, - }); - }, -}; diff --git a/packages/monorepo-scripts/src/utils/configs.ts b/packages/monorepo-scripts/src/utils/configs.ts deleted file mode 100644 index 7d013fb61b..0000000000 --- a/packages/monorepo-scripts/src/utils/configs.ts +++ /dev/null @@ -1,11 +0,0 @@ -const IS_LOCAL_PUBLISH = process.env.IS_LOCAL_PUBLISH === 'true'; -const DIST_TAG = process.env.DIST_TAG || ''; -const LOCAL_NPM_REGISTRY_URL = 'http://localhost:4873'; -const REMOTE_NPM_REGISTRY_URL = 'https://registry.npmjs.org/'; - -export const configs = { - IS_LOCAL_PUBLISH, - DIST_TAG, - NPM_REGISTRY_URL: IS_LOCAL_PUBLISH ? LOCAL_NPM_REGISTRY_URL : REMOTE_NPM_REGISTRY_URL, - DOCKER_HUB_ORG: '0xorg', -}; diff --git a/packages/monorepo-scripts/src/utils/discord.ts b/packages/monorepo-scripts/src/utils/discord.ts deleted file mode 100644 index 3a04587699..0000000000 --- a/packages/monorepo-scripts/src/utils/discord.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { fetchAsync } from '@0x/utils'; - -import { constants } from '../constants'; - -import { utils } from './utils'; - -export const alertDiscordAsync = async (releaseNotes: string): Promise => { - const webhookUrl = constants.discordAlertWebhookUrl; - if (webhookUrl === undefined) { - throw new Error("No discord webhook url, can't alert"); - } - - utils.log('Alerting discord...'); - const payload = { - content: `New monorepo package released! View at ${constants.releasesUrl} \n\n ${releaseNotes}`, - }; - await fetchAsync(webhookUrl, { - method: 'POST', - headers: { - Accept: 'application/json', - 'Content-Type': 'application/json', - }, - body: JSON.stringify(payload), - }); - return; -}; diff --git a/packages/monorepo-scripts/src/utils/doc_generate_utils.ts b/packages/monorepo-scripts/src/utils/doc_generate_utils.ts deleted file mode 100644 index f9c9e49944..0000000000 --- a/packages/monorepo-scripts/src/utils/doc_generate_utils.ts +++ /dev/null @@ -1,469 +0,0 @@ -import { PackageJSON } from '@0x/types'; -import { existsSync, readFileSync, unlinkSync, 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 } from '../types'; - -import { utils } from './utils'; - -export class DocGenerateUtils { - private readonly _packageName: string; - private readonly _packageDir: string; - private readonly _omitExports: string[]; - private readonly _packagePath: string; - private readonly _exportPathToExportedItems: ExportPathToExportedItems; - 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 = DocGenerateUtils._getAllTypeNames(aNode, updatedTypeNames); - }); - } else if (_.isObject(nodeValue)) { - updatedTypeNames = DocGenerateUtils._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 ( - node.type !== undefined && - _.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 = DocGenerateUtils._getAllReferenceNames( - innerPropertyName, - aNode, - updatedReferenceNames, - ); - }); - } else if (_.isObject(nodeValue)) { - updatedReferenceNames = DocGenerateUtils._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 = omitExports === undefined ? [] : omitExports; - - processNode(sourceFile); - - function processNode(node: ts.Node): void { - switch (node.kind) { - case ts.SyntaxKind.ExportDeclaration: { - const exportClause = (node as any).exportClause; - if (exportClause === undefined) { - return; - } - const exportPath = exportClause.parent.moduleSpecifier.text; - _.each(exportClause.elements, element => { - const exportItem = element.name.escapedText; - if (!_.includes(exportsToOmit, exportItem)) { - exportPathToExportedItems[exportPath] = - exportPathToExportedItems[exportPath] === undefined - ? [exportItem] - : [...exportPathToExportedItems[exportPath], exportItem]; - } - }); - if (exportPathToExportedItems[exportPath] !== undefined) { - 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 = - _.get(foundNode, 'parent.moduleReference.expression.text') !== undefined; - if (isExportImportRequireStatement) { - exportPath = foundNode.parent.moduleReference.expression.text; - } - if (!_.includes(exportsToOmit, exportItem)) { - exportPathToExportedItems[exportPath] = - exportPathToExportedItems[exportPath] === undefined - ? [exportItem] - : [...exportPathToExportedItems[exportPath], exportItem]; - } - } - if ( - !_.includes(exportPathOrder, exportPath) && - exportPathToExportedItems[exportPath] !== undefined - ) { - exportPathOrder.push(exportPath); - } - break; - } - default: - // noop - break; - } - - ts.forEachChild(node, processNode); - } - const exportInfo = { - exportPathToExportedItems, - exportPathOrder, - }; - return exportInfo; - } - constructor(packageName: string) { - this._packageName = 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 (pkg === undefined) { - throw new Error(`No package found with name ${packageName}`); - } - this._packagePath = pkg.location; - this._packageDir = pkg.location.substring(pkg.location.lastIndexOf('/') + 1); - if (pkg === undefined) { - 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 = DocGenerateUtils._getExportPathToExportedItems(indexPath, this._omitExports); - this._exportPathToExportedItems = exportInfo.exportPathToExportedItems; - } - public async generateAndUploadDocsAsync(): Promise { - // 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 - // if it exists. - const globalTypeDefinitionsPath = path.join(this._packagePath, 'src', 'globals.d.ts'); - if (existsSync(globalTypeDefinitionsPath)) { - typeDocExtraFileIncludes.push(globalTypeDefinitionsPath); - } - - utils.log(`GENERATE_DOCS: Generating Typedoc JSON for ${this._packageName}...`); - const jsonFilePath = path.join(this._packagePath, 'generated_docs', 'index.json'); - const mdFileDir = path.join(this._packagePath, 'docs'); - const mdReferencePath = `${mdFileDir}/reference.mdx`; - const projectFiles = typeDocExtraFileIncludes.join(' '); - const cwd = this._packagePath; - // 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_DOCS: Generating Typedoc Markdown for ${this._packageName}...`); - await execAsync(`MD_FILE_DIR=${mdFileDir} PROJECT_FILES="${projectFiles}" yarn docs:md`, { - cwd, - }); - - utils.log('GENERATE_DOCS: Modifying Markdown To Exclude Unexported Items...'); - const typedocOutputString = readFileSync(jsonFilePath).toString(); - const markdownOutputString = readFileSync(mdReferencePath).toString(); - const typedocOutput = JSON.parse(typedocOutputString); - const standardizedTypedocOutput = this._standardizeTypedocOutputTopLevelChildNames(typedocOutput); - const { modifiedTypedocOutput, modifiedMarkdownOutput } = this._pruneTypedocOutput( - standardizedTypedocOutput, - markdownOutputString, - ); - - if (!_.includes(docGenConfigs.TYPES_ONLY_LIBRARIES, this._packageName)) { - const propertyName = ''; // Root has no property name - const referenceNames = DocGenerateUtils._getAllReferenceNames(propertyName, modifiedTypedocOutput, []); - this._lookForUnusedExportedTypesThrowIfExists(referenceNames, modifiedTypedocOutput); - this._lookForMissingReferenceExportsThrowIfExists(referenceNames); - } - - const exportPathToTypedocNames: ExportNameToTypedocNames = {}; - _.each(modifiedTypedocOutput.children, file => { - const exportPath = this._findExportPathGivenTypedocName(file.name); - exportPathToTypedocNames[exportPath] = - exportPathToTypedocNames[exportPath] === undefined - ? [file.name] - : [...exportPathToTypedocNames[exportPath], file.name]; - }); - - utils.log(`GENERATE_DOCS: Delete Doc JSON in: ${jsonFilePath}`); - unlinkSync(jsonFilePath); - utils.log(`GENERATE_DOCS: Saving Doc MD to: ${mdReferencePath}`); - writeFileSync(mdReferencePath, modifiedMarkdownOutput); - - utils.log(`GENERATE_DOCS: Doc generation done for ${this._packageName}`); - } - /** - * 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) && - docGenConfigs.EXTERNAL_TYPE_MAP[referenceName] === undefined - ) { - 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_MAP.`, - ); - } - } - /** - * Look for exported types that are not used by the package's public interface - */ - private _lookForUnusedExportedTypesThrowIfExists(referenceNames: string[], typedocOutput: any): void { - const exportedTypes = DocGenerateUtils._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 OR if we still want them exported (e.g error enum types), then add them to the IGNORED_EXCESSIVE_TYPES array.`, - ); - } - } - /** - * 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, markdownOutput: string): any { - const modifiedTypedocOutput = _.cloneDeep(typedocOutput); - let modifiedMarkdownOutput = markdownOutput; - _.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) { - const item = typedocOutput.children[i].children[j]; - let regexp; - switch (item.kindString) { - case 'Interface': - regexp = new RegExp(`(.*)# Interface: ${item.name}[\\s\\S]*?
`, 'g'); - modifiedMarkdownOutput = modifiedMarkdownOutput.replace(regexp, ''); - break; - - case 'Enumeration': - regexp = new RegExp(`(.*)# Enumeration: ${item.name}[\\s\\S]*?
`, 'g'); - modifiedMarkdownOutput = modifiedMarkdownOutput.replace(regexp, ''); - break; - - case 'Class': - regexp = new RegExp(`(.*)# Class: ${item.name}[\\s\\S]*?
`, 'g'); - modifiedMarkdownOutput = modifiedMarkdownOutput.replace(regexp, ''); - break; - - case 'Type alias': - regexp = new RegExp(`(.*)# ${item.name}[\\s\\S]*?(___|
)`, 'g'); - modifiedMarkdownOutput = modifiedMarkdownOutput.replace(regexp, ''); - break; - - default: - // Noop - } - delete modifiedTypedocOutput.children[i].children[j]; - return; - } - - const innerChildren = typedocOutput.children[i].children[j].children; - _.each(innerChildren, (innerChild, k) => { - const isPrivate = _.startsWith(innerChild.name, '_'); - if (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, - modifiedMarkdownOutput, - }; - } - /** - * 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._packageDir}/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 { - let typeDocNameWithoutQuotes = _.replace(typedocName, /"/g, ''); - if (typeDocNameWithoutQuotes.startsWith('contracts/')) { - // tslint:disable-next-line:custom-no-magic-numbers - typeDocNameWithoutQuotes = typeDocNameWithoutQuotes.substring(10); - } else if (typeDocNameWithoutQuotes.startsWith('packages/')) { - // tslint:disable-next-line:custom-no-magic-numbers - typeDocNameWithoutQuotes = typeDocNameWithoutQuotes.substring(9); - } - const sanitizedExportPathToExportPath: { [sanitizedName: string]: string } = {}; - const exportPaths = _.keys(this._exportPathToExportedItems); - const sanitizedExportPaths = _.map(exportPaths, exportPath => { - if (_.startsWith(exportPath, './')) { - const sanitizedExportPath = path.join(this._packageDir, 'src', exportPath); - sanitizedExportPathToExportPath[sanitizedExportPath] = exportPath; - return sanitizedExportPath; - } - const monorepoPrefix = '@0x/'; - if (_.startsWith(exportPath, monorepoPrefix)) { - let sanitizedExportPath = exportPath.split(monorepoPrefix)[1]; - if (sanitizedExportPath.startsWith('contracts-')) { - sanitizedExportPath = sanitizedExportPath.replace('contracts-', ''); - } - 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 (matchingSanitizedExportPathIfExists === undefined) { - throw new Error( - `Didn't find an exportPath for ${typeDocNameWithoutQuotes} ${sanitizedExportPathsSortedByLength}`, - ); - } - const matchingExportPath = sanitizedExportPathToExportPath[matchingSanitizedExportPathIfExists]; - return matchingExportPath; - } - 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 (pathIfExists === undefined) { - return; // It's an external package - } - - const typeDocSourceIncludes = new Set(); - const pathToIndex = `${pathIfExists}/src/index.ts`; - const exportInfo = DocGenerateUtils._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_DOCS: WARNING - ${ - this._packageName - } is exporting one of ${innerExportItems} from a package which is itself exporting from another\ - internal package ${innerExportPath}. To fix this, export the dependency directly from ${innerExportPath}\ - instead of the intermediate package.`, - ); - } else { - const absoluteSrcPath = path.join(pathIfExists, 'src', `${innerExportPath}.ts`); - typeDocSourceIncludes.add(absoluteSrcPath); - } - }); - }); - - // @0x/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; - } -} diff --git a/packages/monorepo-scripts/src/utils/docker_hub_utils.ts b/packages/monorepo-scripts/src/utils/docker_hub_utils.ts deleted file mode 100644 index 62215a5797..0000000000 --- a/packages/monorepo-scripts/src/utils/docker_hub_utils.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { fetchAsync } from '@0x/utils'; -import { exec as execAsync } from 'promisify-child-process'; - -import { utils } from './utils'; - -const API_ENDPOINT = 'https://hub.docker.com/v2'; -const HTTP_OK_STATUS = 200; - -export const dockerHubUtils = { - async getTokenAsync(): Promise { - const payload = { - username: process.env.DOCKER_USERNAME, - password: process.env.DOCKER_PASS, - }; - const response = await fetchAsync(`${API_ENDPOINT}/users/login`, { - method: 'POST', - headers: { - Accept: 'application/json', - 'Content-Type': 'application/json', - }, - body: JSON.stringify(payload), - }); - if (response.status !== HTTP_OK_STATUS) { - throw new Error( - `DockerHub user login failed (status code: ${ - response.status - }). Make sure you have environment variables 'DOCKER_USERNAME; and 'DOCKER_PASS' set`, - ); - } - const respPayload = await response.json(); - const token = respPayload.token; - return token; - }, - async checkUserAddedToOrganizationOrThrowAsync(organization: string): Promise { - utils.log('Checking that the user was added to the 0xorg DockerHub organization...'); - const token = await dockerHubUtils.getTokenAsync(); - const response = await fetchAsync(`${API_ENDPOINT}/repositories/${organization}/?page_size=10`, { - method: 'GET', - headers: { - Accept: 'application/json', - Authorization: `JWT ${token}`, - }, - }); - const respPayload = await response.json(); - if (response.status !== HTTP_OK_STATUS || respPayload.count === 0) { - throw new Error( - `Failed to fetch org: ${organization}'s list of repos (status code: ${ - response.status - }). Make sure your account has been added to the '${organization}' org on DockerHub`, - ); - } - }, - async loginUserToDockerCommandlineOrThrowAsync(): Promise { - try { - utils.log('Checking that the user is logged in to docker command...'); - await execAsync(`echo "$DOCKER_PASS" | docker login -u $DOCKER_USERNAME --password-stdin`); - } catch (err) { - throw new Error( - `Failed to log you into the 'docker' commandline tool. Make sure you have the 'docker' commandline tool installed. Full error: ${ - err.message - }`, - ); - } - }, -}; diff --git a/packages/monorepo-scripts/src/utils/github_release_utils.ts b/packages/monorepo-scripts/src/utils/github_release_utils.ts deleted file mode 100644 index 228f32ea92..0000000000 --- a/packages/monorepo-scripts/src/utils/github_release_utils.ts +++ /dev/null @@ -1,118 +0,0 @@ -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( - packagesToPublish: Package[], - isDryRun: boolean, -): Promise { - // 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(packagesToPublish, pkg => { - aggregateNotes += getReleaseNotesForPackage(pkg.location, pkg.packageJson.name); - - const packageAssets = _.get(pkg.packageJson, 'config.postpublish.assets'); - if (packageAssets !== undefined) { - 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); - - return aggregateNotes; -} - -// 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(packageLocation: string, packageName: string): string { - const changelogJSONPath = path.join(packageLocation, '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`; - }); - if (_.isEmpty(notes)) { - return ''; // don't include it - } - const releaseNotesSection = `### ${packageName}@${latestLog.version}\n${notes}\n\n`; - return releaseNotesSection; -} diff --git a/packages/monorepo-scripts/src/utils/npm_utils.ts b/packages/monorepo-scripts/src/utils/npm_utils.ts deleted file mode 100644 index 363e31fbbd..0000000000 --- a/packages/monorepo-scripts/src/utils/npm_utils.ts +++ /dev/null @@ -1,29 +0,0 @@ -import 'isomorphic-fetch'; -import * as _ from 'lodash'; - -import { PackageRegistryJson } from '../types'; - -import { configs } from './configs'; - -const SUCCESS_STATUS = 200; -const NOT_FOUND_STATUS = 404; - -export const npmUtils = { - async getPackageRegistryJsonIfExistsAsync(packageName: string): Promise { - const url = `${configs.NPM_REGISTRY_URL}/${packageName}`; - const response = await fetch(url); - - if (response.status === NOT_FOUND_STATUS) { - return undefined; - } else if (response.status !== SUCCESS_STATUS) { - throw new Error(`Request to ${url} failed. Check your internet connection and that npm registry is up.`); - } - const packageRegistryJson = await response.json(); - return packageRegistryJson; - }, - getPreviouslyPublishedVersions(packageRegistryJson: PackageRegistryJson): string[] { - const timeWithOnlyVersions = _.omit(packageRegistryJson.time, ['modified', 'created']); - const versions = _.keys(timeWithOnlyVersions); - return versions; - }, -}; diff --git a/packages/monorepo-scripts/src/utils/utils.ts b/packages/monorepo-scripts/src/utils/utils.ts deleted file mode 100644 index 0850060fcd..0000000000 --- a/packages/monorepo-scripts/src/utils/utils.ts +++ /dev/null @@ -1,187 +0,0 @@ -import { PackageJSON } from '@0x/types'; -import batchPackages = require('@lerna/batch-packages'); -import * as fs from 'fs'; -import * as _ from 'lodash'; -import { exec as execAsync } from 'promisify-child-process'; -import semver = require('semver'); - -import { constants } from '../constants'; -import { GitTagsByPackageName, Package, UpdatedPackage } from '../types'; - -import { changelogUtils } from './changelog_utils'; - -export const utils = { - log(...args: any[]): void { - console.log(...args); // tslint:disable-line:no-console - }, - readJSONFile(path: string): T { - const JSONString = fs.readFileSync(path, 'utf8'); - const parsed: T = JSON.parse(JSONString); - return parsed; - }, - getTopologicallySortedPackages(rootDir: string): Package[] { - const packages = utils.getPackages(rootDir); - const batchedPackages: PackageJSON[] = _.flatten(batchPackages(_.map(packages, pkg => pkg.packageJson), false)); - const topsortedPackages: Package[] = _.map( - batchedPackages, - (pkg: PackageJSON) => _.find(packages, pkg1 => pkg1.packageJson.name === pkg.name) as Package, - ); - return topsortedPackages; - }, - getPackages(rootDir: string): Package[] { - const rootPackageJson = utils.readJSONFile(`${rootDir}/package.json`); - if (rootPackageJson.workspaces === undefined) { - throw new Error(`Did not find 'workspaces' key in root package.json`); - } - const packages = []; - for (const workspace of rootPackageJson.workspaces) { - // HACK: Remove allowed wildcards from workspace entries. - // This might be entirely comprehensive. - const workspacePath = workspace.replace('*', '').replace('**/*', ''); - const subpackageNames = fs.readdirSync(`${rootDir}/${workspacePath}`); - for (const subpackageName of subpackageNames) { - if (_.startsWith(subpackageName, '.')) { - continue; - } - const pathToPackageJson = `${rootDir}/${workspacePath}${subpackageName}`; - try { - const packageJson = utils.readJSONFile(`${pathToPackageJson}/package.json`); - const pkg = { - location: pathToPackageJson, - packageJson, - }; - packages.push(pkg); - } catch (err) { - // Couldn't find a 'package.json' for package. Skipping. - } - } - } - return packages; - }, - async getPackagesByNameAsync(packageNames: string[]): Promise { - const allPackages = utils.getPackages(constants.monorepoRootPath); - const updatedPackages = _.filter(allPackages, pkg => { - return _.includes(packageNames, pkg.packageJson.name); - }); - return updatedPackages; - }, - async getPackagesToPublishAsync(shouldIncludePrivate: boolean): Promise { - const updatedPublicPackages = await utils.getLernaUpdatedPackagesAsync(shouldIncludePrivate); - const updatedPackageNames = _.map(updatedPublicPackages, pkg => pkg.name); - - const allPackages = utils.getPackages(constants.monorepoRootPath); - const updatedPackages = _.filter(allPackages, pkg => { - return _.includes(updatedPackageNames, pkg.packageJson.name); - }); - return updatedPackages; - }, - async getLernaUpdatedPackagesAsync(shouldIncludePrivate: boolean): Promise { - try { - const result = await execAsync( - `${constants.lernaExecutable} changed --json ${shouldIncludePrivate ? '--all' : ''}`, - { - cwd: constants.monorepoRootPath, - }, - ); - if (result.stdout === '') { - return []; - } - const updatedPackages = JSON.parse(result.stdout); - return updatedPackages; - } catch (err) { - return []; - } - }, - async getNextPackageVersionAsync( - currentVersion: string, - packageName: string, - packageLocation: string, - ): Promise { - let nextVersionIfValid; - const changelog = changelogUtils.getChangelogOrCreateIfMissing(packageName, packageLocation); - if (_.isEmpty(changelog)) { - nextVersionIfValid = semver.inc(currentVersion, 'patch'); - return nextVersionIfValid as string; - } - const lastEntry = changelog[0]; - if (semver.gt(currentVersion, lastEntry.version)) { - throw new Error(`Package.json version cannot be greater then last CHANGELOG entry. Check: ${packageName}`); - } - nextVersionIfValid = semver.eq(lastEntry.version, currentVersion) - ? semver.inc(currentVersion, 'patch') - : lastEntry.version; - if (nextVersionIfValid === null) { - throw new Error(`Encountered invalid semver: ${currentVersion} associated with ${packageName}`); - } - return nextVersionIfValid; - }, - async getRemoteGitTagsAsync(): Promise { - const TEN_MEGA_BYTES = 1024 * 1024 * 10; // tslint:disable-line custom-no-magic-numbers - const result = await execAsync(`git ls-remote --tags`, { - cwd: constants.monorepoRootPath, - maxBuffer: TEN_MEGA_BYTES, - }); - const tagsString = result.stdout; - const tagOutputs: string[] = tagsString.split('\n'); - const tags = _.compact( - _.map(tagOutputs, tagOutput => { - const tag = tagOutput.split('refs/tags/')[1]; - // Tags with `^{}` are duplicateous so we ignore them - // Source: https://stackoverflow.com/questions/15472107/when-listing-git-ls-remote-why-theres-after-the-tag-name - if (_.endsWith(tag, '^{}')) { - return undefined; - } - return tag; - }), - ); - return tags; - }, - async getLocalGitTagsAsync(): Promise { - const result = await execAsync(`git tag`, { - cwd: constants.monorepoRootPath, - }); - const tagsString = result.stdout; - const tags = tagsString.split('\n'); - return tags; - }, - async getGitTagsByPackageNameAsync(packageNames: string[], gitTags: string[]): Promise { - const tagVersionByPackageName: GitTagsByPackageName = {}; - _.each(gitTags, tag => { - const packageNameIfExists = _.find(packageNames, name => { - return _.includes(tag, `${name}@`); - }); - if (packageNameIfExists === undefined) { - return; // ignore tags not related to a package we care about. - } - const splitTag = tag.split(`${packageNameIfExists}@`); - if (splitTag.length !== 2) { - throw new Error(`Unexpected tag name found: ${tag}`); - } - const version = splitTag[1]; - (tagVersionByPackageName[packageNameIfExists] || (tagVersionByPackageName[packageNameIfExists] = [])).push( - version, - ); - }); - return tagVersionByPackageName; - }, - async removeLocalTagAsync(tagName: string): Promise { - try { - await execAsync(`git tag -d ${tagName}`, { - cwd: constants.monorepoRootPath, - }); - } catch (err) { - throw new Error(`Failed to delete local git tag. Got err: ${err}`); - } - utils.log(`Removed local tag: ${tagName}`); - }, - async removeRemoteTagAsync(tagName: string): Promise { - try { - await execAsync(`git push origin ${tagName}`, { - cwd: constants.monorepoRootPath, - }); - } catch (err) { - throw new Error(`Failed to delete remote git tag. Got err: ${err}`); - } - utils.log(`Removed remote tag: ${tagName}`); - }, -}; diff --git a/packages/monorepo-scripts/tsconfig.json b/packages/monorepo-scripts/tsconfig.json deleted file mode 100644 index c8b1d23e5a..0000000000 --- a/packages/monorepo-scripts/tsconfig.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "extends": "../../tsconfig", - "compilerOptions": { - "typeRoots": ["../../node_modules/@types", "node_modules/@types"], - "outDir": "lib", - "rootDir": "src" - }, - "include": ["./src/**/*"] -} diff --git a/packages/monorepo-scripts/tslint.json b/packages/monorepo-scripts/tslint.json deleted file mode 100644 index d67c2e4901..0000000000 --- a/packages/monorepo-scripts/tslint.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": ["../tslint-config"] -} diff --git a/packages/orderbook/CHANGELOG.json b/packages/orderbook/CHANGELOG.json deleted file mode 100644 index d43b2e95b9..0000000000 --- a/packages/orderbook/CHANGELOG.json +++ /dev/null @@ -1,209 +0,0 @@ -[ - { - "timestamp": 1594788383, - "version": "2.2.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1592969527, - "version": "2.2.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1583220306, - "version": "2.2.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1582837861, - "version": "2.2.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1582677073, - "version": "2.2.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1582623685, - "version": "2.2.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1581748629, - "version": "2.2.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.2.0", - "changes": [ - { - "note": "Use updated `order-utils` with non-async hash functions.", - "pr": 2462 - } - ], - "timestamp": 1581204851 - }, - { - "timestamp": 1580988106, - "version": "2.1.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1580811564, - "version": "2.1.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.1.0", - "changes": [ - { - "note": "Added `getBatchOrdersAsync` for fetching batches of orders", - "pr": 2427 - } - ], - "timestamp": 1579682890 - }, - { - "timestamp": 1578272714, - "version": "2.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.0", - "changes": [ - { - "note": "Change OrderStore functions to be async, allowing for Database adapters", - "pr": 2393 - } - ], - "timestamp": 1576540892 - }, - { - "timestamp": 1575931811, - "version": "1.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.0", - "changes": [ - { - "note": "Added dependency on @0x/contracts-dev-utils", - "pr": 2321 - }, - { - "note": "Update Mesh RPC logic to v6.0.1-beta", - "pr": 2325 - }, - { - "note": "All references to network ID have been removed, and references to chain ID have been introduced instead", - "pr": 2313 - } - ], - "timestamp": 1575296764 - }, - { - "version": "0.1.0-beta.4", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1575290197 - }, - { - "version": "0.1.0-beta.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1574238768 - }, - { - "version": "0.1.0-beta.2", - "changes": [ - { - "note": "Added dependency on @0x/contracts-dev-utils", - "pr": 2321 - }, - { - "note": "Update Mesh RPC logic to v6.0.1-beta", - "pr": 2325 - } - ], - "timestamp": 1574030254 - }, - { - "version": "0.1.0-beta.1", - "changes": [ - { - "note": "All references to network ID have been removed, and references to chain ID have been introduced instead", - "pr": 2313 - } - ], - "timestamp": 1573159180 - }, - { - "version": "0.1.0-beta.0", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1570135330 - }, - { - "timestamp": 1568744790, - "version": "0.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - } -] diff --git a/packages/orderbook/CHANGELOG.md b/packages/orderbook/CHANGELOG.md deleted file mode 100644 index cb9b01c844..0000000000 --- a/packages/orderbook/CHANGELOG.md +++ /dev/null @@ -1,93 +0,0 @@ - - -CHANGELOG - -## v2.2.7 - _July 15, 2020_ - - * Dependencies updated - -## v2.2.6 - _June 24, 2020_ - - * Dependencies updated - -## v2.2.5 - _March 3, 2020_ - - * Dependencies updated - -## v2.2.4 - _February 27, 2020_ - - * Dependencies updated - -## v2.2.3 - _February 26, 2020_ - - * Dependencies updated - -## v2.2.2 - _February 25, 2020_ - - * Dependencies updated - -## v2.2.1 - _February 15, 2020_ - - * Dependencies updated - -## v2.2.0 - _February 8, 2020_ - - * Use updated `order-utils` with non-async hash functions. (#2462) - -## v2.1.2 - _February 6, 2020_ - - * Dependencies updated - -## v2.1.1 - _February 4, 2020_ - - * Dependencies updated - -## v2.1.0 - _January 22, 2020_ - - * Added `getBatchOrdersAsync` for fetching batches of orders (#2427) - -## v2.0.1 - _January 6, 2020_ - - * Dependencies updated - -## v2.0.0 - _December 17, 2019_ - - * Change OrderStore functions to be async, allowing for Database adapters (#2393) - -## v1.0.1 - _December 9, 2019_ - - * Dependencies updated - -## v1.0.0 - _December 2, 2019_ - - * Added dependency on @0x/contracts-dev-utils (#2321) - * Update Mesh RPC logic to v6.0.1-beta (#2325) - * All references to network ID have been removed, and references to chain ID have been introduced instead (#2313) - -## v0.1.0-beta.4 - _December 2, 2019_ - - * Dependencies updated - -## v0.1.0-beta.3 - _November 20, 2019_ - - * Dependencies updated - -## v0.1.0-beta.2 - _November 17, 2019_ - - * Added dependency on @0x/contracts-dev-utils (#2321) - * Update Mesh RPC logic to v6.0.1-beta (#2325) - -## v0.1.0-beta.1 - _November 7, 2019_ - - * All references to network ID have been removed, and references to chain ID have been introduced instead (#2313) - -## v0.1.0-beta.0 - _October 3, 2019_ - - * Dependencies updated - -## v0.0.2 - _September 17, 2019_ - - * Dependencies updated diff --git a/packages/orderbook/README.md b/packages/orderbook/README.md deleted file mode 100644 index de4cda5928..0000000000 --- a/packages/orderbook/README.md +++ /dev/null @@ -1,114 +0,0 @@ -## @0x/orderbook - -Package to help fetch orders from a remote source ([Standard Relayer API](https://github.com/0xProject/standard-relayer-api), Mesh) and keep the local orderbook synced and up-to-date. - -Supported Order Providers: - -- SRA HTTP Polling -- SRA Websocket -- Mesh - -## Installation - -```bash -yarn add @0x/orderbook -``` - -**Import** - -```typescript -import { Orderbook } from '@0x/orderbook'; -``` - -or - -```javascript -var Orderbook = require('@0x/orderbook').Orderbook; -``` - -If your project is in [TypeScript](https://www.typescriptlang.org/), add the following to your `tsconfig.json`: - -```json -"compilerOptions": { - "typeRoots": ["node_modules/@0x/typescript-typings/types", "node_modules/@types"], -} -``` - -## Usage - -```typescript -// Create an orderbook for makerAssetData, takerAssetData using the SRA Polling Order Provider -// This Provider polls the SRA endpoint automatically every 5 seconds on the supplied asset pairs -const orderbook = Orderbook.getOrderbookForPollingProvider({ - httpEndpoint: 'https://sra.0x.org/v2', - pollingIntervalMs: 5000, -}); -const orders = await orderbook.getOrdersAsync(makerAssetData, takerAssetData); - -// Create an orderbook for makerAssetData, takerAssetData using the SRA Websocket Order Provider -// This provider subscribes via websocket to receive order updates on the supplied asset pairs -const orderbook = Orderbook.getOrderbookForWebsocketProvider({ - httpEndpoint: 'https://sra.0x.org/v2', - websocketEndpoint: 'wss://ws.sra.0x.org', -}); -const orders = await orderbook.getOrdersAsync(makerAssetData, takerAssetData); - -// Create an orderbook for makerAssetData, takerAssetData using the Mesh Order Provider -// This provider subscribes via websocket to receive order updates on all orders stored in Mesh -const orderbook = Orderbook.getOrderbookForMeshProvider({ - websocketEndpoint: 'wss://MESH_ENDPOINT', -}); -const orders = await orderbook.getOrdersAsync(makerAssetData, takerAssetData); -``` - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install dependencies - -If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: - -```bash -yarn config set workspaces-experimental true -``` - -Then install dependencies - -```bash -yarn install -``` - -### Build - -To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory: - -```bash -PKG=@0x/orderbook yarn build -``` - -Or continuously rebuild on change: - -```bash -PKG=@0x/orderbook yarn watch -``` - -### Clean - -```bash -yarn clean -``` - -### Lint - -```bash -yarn lint -``` - -### Run Tests - -```bash -yarn test -``` diff --git a/packages/orderbook/jest.config.js b/packages/orderbook/jest.config.js deleted file mode 100644 index fc209080f6..0000000000 --- a/packages/orderbook/jest.config.js +++ /dev/null @@ -1,10 +0,0 @@ -module.exports = { - roots: ['/test'], - coverageDirectory: 'coverage', - transform: { - '.*.ts?$': 'ts-jest', - }, - testRegex: '(/__test__/.*|(\\.|/)(test|spec))\\.(js|ts)$', - moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], - collectCoverageFrom: ['src/**/*.{ts,tsx}', '!src/index.tsx'], -}; diff --git a/packages/orderbook/package.json b/packages/orderbook/package.json deleted file mode 100644 index efb2f7eaa5..0000000000 --- a/packages/orderbook/package.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "name": "@0x/orderbook", - "version": "2.2.7", - "description": "Library for retrieving and syncing a remote orderbook locally", - "main": "lib/src/index.js", - "types": "lib/src/index.d.ts", - "bugs": { - "url": "https://github.com/0xProject/0x-monorepo/issues" - }, - "homepage": "https://github.com/0xProject/0x-monorepo/packages/orderbook/README.md", - "repository": { - "type": "git", - "url": "https://github.com/0xProject/0x-monorepo.git" - }, - "publishConfig": { - "access": "public" - }, - "scripts": { - "clean": "shx rm -rf lib generated_docs", - "test": "jest", - "test:coverage": "jest --coverage", - "build": "tsc -p tsconfig.json", - "build:ci": "yarn build", - "watch": "tsc -w -p tsconfig.json", - "prettier": "prettier --write 'src/**/*.ts' --config .prettierrc", - "test:circleci": "yarn test:coverage", - "lint": "tslint --project . --format stylish", - "docs:md": "ts-doc-gen --sourceDir='$PROJECT_FILES' --output=$MD_FILE_DIR --fileExtension=mdx --tsconfig=./typedoc-tsconfig.json", - "docs:json": "typedoc --excludePrivate --excludeExternals --excludeProtected --ignoreCompilerErrors --target ES5 --tsconfig typedoc-tsconfig.json --json $JSON_FILE_PATH $PROJECT_FILES" - }, - "author": "Jacob Evans", - "license": "Apache-2.0", - "devDependencies": { - "@0x/ts-doc-gen": "^0.0.22", - "@0x/tslint-config": "^4.1.0", - "@0x/types": "^3.2.0", - "@types/jest": "^24.0.17", - "@types/sinon": "^2.2.2", - "@types/websocket": "^0.0.39", - "jest": "^24.8.0", - "shx": "^0.2.2", - "sinon": "^4.0.0", - "ts-jest": "^24.0.2", - "typedoc": "^0.15.0", - "typescript": "3.0.1", - "websocket": "^1.0.26" - }, - "dependencies": { - "@0x/assert": "^3.0.9", - "@0x/connect": "^6.0.9", - "@0x/contracts-dev-utils": "^1.3.5", - "@0x/mesh-rpc-client": "^7.0.4-beta-0xv3", - "@0x/order-utils": "^10.3.0", - "@0x/utils": "^5.5.1" - }, - "gitHead": "4f91bfd907996b2f4dd383778b50c479c2602b56" -} diff --git a/packages/orderbook/src/index.ts b/packages/orderbook/src/index.ts deleted file mode 100644 index de81aaac03..0000000000 --- a/packages/orderbook/src/index.ts +++ /dev/null @@ -1,18 +0,0 @@ -export { Orderbook } from './orderbook'; -export { OrderStore } from './order_store'; -export { OrderSet } from './order_set'; -export { SRAWebsocketOrderProvider } from './order_provider/sra_websocket_order_provider'; -export { SRAPollingOrderProvider } from './order_provider/sra_polling_order_provider'; -export { MeshOrderProvider } from './order_provider/mesh_order_provider'; -export { BaseOrderProvider } from './order_provider/base_order_provider'; -export { - MeshOrderProviderOpts, - SRAPollingOrderProviderOpts, - SRAWebsocketOrderProviderOpts, - AcceptedRejectedOrders, - AddedRemovedOrders, - RejectedOrder, -} from './types'; -export { SignedOrder, AssetPairsItem, APIOrder, Asset } from '@0x/types'; - -export { WSOpts } from '@0x/mesh-rpc-client'; diff --git a/packages/orderbook/src/order_provider/base_order_provider.ts b/packages/orderbook/src/order_provider/base_order_provider.ts deleted file mode 100644 index ffa596be8c..0000000000 --- a/packages/orderbook/src/order_provider/base_order_provider.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { AssetPairsItem, SignedOrder } from '@0x/types'; - -import { OrderStore } from '../order_store'; -import { AcceptedRejectedOrders, AddedRemovedOrders } from '../types'; - -// AssetPairItem requires precision but some OrderProviders may not -// enforce any precision. This is not the token decimal but the -// maximum precision for an orderbook. -export const DEFAULT_TOKEN_PRECISION = 18; - -export abstract class BaseOrderProvider { - public readonly _orderStore: OrderStore; - - constructor(orderStore: OrderStore) { - this._orderStore = orderStore; - } - - public abstract async createSubscriptionForAssetPairAsync( - makerAssetData: string, - takerAssetData: string, - ): Promise; - - public abstract async getAvailableAssetDatasAsync(): Promise; - - public abstract async destroyAsync(): Promise; - - public abstract async addOrdersAsync(orders: SignedOrder[]): Promise; - - protected async _updateStoreAsync(addedRemoved: AddedRemovedOrders): Promise { - await this._orderStore.updateAsync(addedRemoved); - } -} diff --git a/packages/orderbook/src/order_provider/base_sra_order_provider.ts b/packages/orderbook/src/order_provider/base_sra_order_provider.ts deleted file mode 100644 index 0aa2c37ed9..0000000000 --- a/packages/orderbook/src/order_provider/base_sra_order_provider.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { APIOrder, HttpClient } from '@0x/connect'; -import { AssetPairsItem, PaginatedCollection, SignedOrder } from '@0x/types'; - -import { OrderStore } from '../order_store'; -import { AcceptedRejectedOrders, RejectedOrder } from '../types'; -import { utils } from '../utils'; - -import { BaseOrderProvider } from './base_order_provider'; -export const PER_PAGE_DEFAULT = 100; - -export abstract class BaseSRAOrderProvider extends BaseOrderProvider { - protected readonly _httpClient: HttpClient; - protected readonly _perPage: number; - - /** - * This is an internal class for Websocket and Polling Order Providers - */ - constructor(orderStore: OrderStore, httpEndpoint: string, perPage: number = PER_PAGE_DEFAULT) { - super(orderStore); - this._httpClient = new HttpClient(httpEndpoint); - this._perPage = perPage; - } - - /** - * Returns the availale Asset pairs from the SRA endpoint. This response is direct from the endpoint - * so this call blocks until the response arrives. - */ - public async getAvailableAssetDatasAsync(): Promise { - const requestOpts = { - perPage: this._perPage, - }; - let recordsToReturn: AssetPairsItem[] = []; - - let hasMorePages = true; - let page = 1; - - while (hasMorePages) { - const { total, records, perPage } = await utils.attemptAsync>(() => - this._httpClient.getAssetPairsAsync(requestOpts), - ); - - recordsToReturn = [...recordsToReturn, ...records]; - - page += 1; - const lastPage = Math.ceil(total / perPage); - hasMorePages = page <= lastPage; - } - return recordsToReturn; - } - - /** - * Submits the SignedOrder to the SRA endpoint - * @param orders the set of signed orders to add - */ - public async addOrdersAsync(orders: SignedOrder[]): Promise { - const accepted: SignedOrder[] = []; - const rejected: RejectedOrder[] = []; - for (const order of orders) { - try { - await this._httpClient.submitOrderAsync(order); - accepted.push(order); - } catch (e) { - rejected.push({ order, message: e.message }); - } - } - return { accepted, rejected }; - } - - protected async _fetchLatestOrdersAsync(makerAssetData: string, takerAssetData: string): Promise { - const [latestSellOrders, latestBuyOrders] = await Promise.all([ - this._getAllPaginatedOrdersAsync(makerAssetData, takerAssetData), - this._getAllPaginatedOrdersAsync(takerAssetData, makerAssetData), - ]); - return [...latestSellOrders, ...latestBuyOrders]; - } - - protected async _getAllPaginatedOrdersAsync(makerAssetData: string, takerAssetData: string): Promise { - let recordsToReturn: APIOrder[] = []; - const requestOpts = { - makerAssetData, - takerAssetData, - perPage: this._perPage, - }; - - let hasMorePages = true; - let page = 1; - - while (hasMorePages) { - const { total, records, perPage } = await utils.attemptAsync(() => - this._httpClient.getOrdersAsync({ - ...requestOpts, - page, - }), - ); - - recordsToReturn = [...recordsToReturn, ...records]; - - page += 1; - const lastPage = Math.ceil(total / perPage); - hasMorePages = page <= lastPage; - } - return recordsToReturn; - } -} diff --git a/packages/orderbook/src/order_provider/custom_order_provider.ts b/packages/orderbook/src/order_provider/custom_order_provider.ts deleted file mode 100644 index d3ea380ac8..0000000000 --- a/packages/orderbook/src/order_provider/custom_order_provider.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { Asset, AssetPairsItem, SignedOrder } from '@0x/types'; -import { BigNumber } from '@0x/utils'; - -import { OrderStore } from '../order_store'; -import { AcceptedRejectedOrders } from '../types'; -import { utils } from '../utils'; - -import { BaseOrderProvider, DEFAULT_TOKEN_PRECISION } from './base_order_provider'; - -export class CustomOrderProvider extends BaseOrderProvider { - constructor(orders: SignedOrder[], orderStore: OrderStore) { - super(orderStore); - void this.addOrdersAsync(orders); - } - - // tslint:disable-next-line:prefer-function-over-method - public async createSubscriptionForAssetPairAsync(_makerAssetData: string, _takerAssetData: string): Promise { - // Do nothing - } - - public async getAvailableAssetDatasAsync(): Promise { - const assetPairsItems: AssetPairsItem[] = []; - const minAmount = new BigNumber(0); - const maxAmount = new BigNumber(2).pow(256).minus(1); - const precision = DEFAULT_TOKEN_PRECISION; - for (const assetPairKey of await this._orderStore.keysAsync()) { - const [assetA, assetB] = OrderStore.assetPairKeyToAssets(assetPairKey); - const assetDataA: Asset = { assetData: assetA, minAmount, maxAmount, precision }; - const assetDataB: Asset = { assetData: assetB, minAmount, maxAmount, precision }; - assetPairsItems.push({ assetDataA, assetDataB }); - assetPairsItems.push({ assetDataA: assetDataB, assetDataB: assetDataA }); - } - return assetPairsItems; - } - - // tslint:disable-next-line:prefer-function-over-method - public async destroyAsync(): Promise { - // Do nothing - } - - public async addOrdersAsync(orders: SignedOrder[]): Promise { - for (const order of orders) { - const assetPairKey = OrderStore.getKeyForAssetPair(order.makerAssetData, order.takerAssetData); - await this._orderStore.updateAsync({ - added: [ - { - order, - metaData: { - remainingFillableTakerAssetAmount: order.takerAssetAmount, - orderHash: utils.getOrderHash(order), - }, - }, - ], - removed: [], - assetPairKey, - }); - } - return { accepted: orders, rejected: [] }; - } -} diff --git a/packages/orderbook/src/order_provider/mesh_order_provider.ts b/packages/orderbook/src/order_provider/mesh_order_provider.ts deleted file mode 100644 index 42d742df82..0000000000 --- a/packages/orderbook/src/order_provider/mesh_order_provider.ts +++ /dev/null @@ -1,210 +0,0 @@ -import { APIOrder } from '@0x/connect'; -import { - AcceptedOrderInfo, - OrderEvent, - OrderEventEndState, - OrderInfo, - RejectedOrderInfo, - WSClient, -} from '@0x/mesh-rpc-client'; -import { Asset, AssetPairsItem, SignedOrder } from '@0x/types'; -import { BigNumber } from '@0x/utils'; - -import { OrderStore } from '../order_store'; -import { AcceptedRejectedOrders, AddedRemovedOrders, MeshOrderProviderOpts } from '../types'; -import { utils } from '../utils'; - -import { BaseOrderProvider, DEFAULT_TOKEN_PRECISION } from './base_order_provider'; - -export class MeshOrderProvider extends BaseOrderProvider { - private readonly _wsClient: WSClient; - private _wsSubscriptionId?: string; - - /** - * Converts the OrderEvent or OrderInfo from Mesh into an APIOrder. - * If the OrderInfo is a RejectedOrderInfo the remainingFillableTakerAssetAmount is - * assumed to be 0. - * @param orderEvent The `OrderEvent` from a Mesh subscription update - */ - private static _orderInfoToAPIOrder( - orderEvent: OrderEvent | AcceptedOrderInfo | RejectedOrderInfo | OrderInfo, - ): APIOrder { - const remainingFillableTakerAssetAmount = (orderEvent as OrderEvent).fillableTakerAssetAmount - ? (orderEvent as OrderEvent).fillableTakerAssetAmount - : new BigNumber(0); - // TODO(dekz): Remove the any hack when mesh is published v3 - return { - // tslint:disable:no-unnecessary-type-assertion - order: orderEvent.signedOrder as any, - metaData: { - orderHash: orderEvent.orderHash, - remainingFillableTakerAssetAmount, - }, - }; - } - - /** - * Instantiates a [Mesh](https://github.com/0xProject/0x-mesh) Order Provider. This provider writes - * all orders stored in Mesh to the OrderStore and subscribes all Mesh updates. - * @param opts `MeshOrderProviderOpts` containing the websocketEndpoint and additional Mesh options - * @param orderStore The `OrderStore` where orders are added and removed from - */ - constructor(opts: MeshOrderProviderOpts, orderStore: OrderStore) { - super(orderStore); - this._wsClient = new WSClient(opts.websocketEndpoint, opts.wsOpts); - } - - /** - * Returns the available asset pairs. If no subscription to Mesh exists (and therefore no orders) it is - * created and awaited on. Once the connection has been initialized the orders in the store are returned - * as asset pairs. - */ - public async getAvailableAssetDatasAsync(): Promise { - await this._initializeIfRequiredAsync(); - const assetPairsItems: AssetPairsItem[] = []; - const minAmount = new BigNumber(0); - const maxAmount = new BigNumber(2).pow(256).minus(1); - const precision = DEFAULT_TOKEN_PRECISION; - for (const assetPairKey of await this._orderStore.keysAsync()) { - const [assetA, assetB] = OrderStore.assetPairKeyToAssets(assetPairKey); - const assetDataA: Asset = { assetData: assetA, minAmount, maxAmount, precision }; - const assetDataB: Asset = { assetData: assetB, minAmount, maxAmount, precision }; - assetPairsItems.push({ assetDataA, assetDataB }); - assetPairsItems.push({ assetDataA: assetDataB, assetDataB: assetDataA }); - } - return assetPairsItems; - } - - /** - * Creates a subscription for all asset pairs in Mesh. - * @param makerAssetData the Maker Asset Data - * @param takerAssetData the Taker Asset Data - */ - public async createSubscriptionForAssetPairAsync(_makerAssetData: string, _takerAssetData: string): Promise { - // Create the subscription first to get any updates while waiting for the request - await this._initializeIfRequiredAsync(); - } - - /** - * Submits the SignedOrder to the Mesh node - * @param orders the set of signed orders to add - */ - public async addOrdersAsync(orders: SignedOrder[]): Promise { - const { accepted, rejected } = await utils.attemptAsync(() => this._wsClient.addOrdersAsync(orders)); - // TODO(dekz): Remove the any hack when mesh is published v3 - return { - accepted: accepted.map(o => o.signedOrder) as any, - rejected: rejected.map(o => ({ order: o.signedOrder, message: o.status.message })) as any, - }; - } - - /** - * Destroys the order provider, removing any subscriptions - */ - public async destroyAsync(): Promise { - this._wsClient.destroy(); - } - - /** - * Creates the order subscription unless one already exists. If one does not exist - * it also handles the reconnection logic. - */ - private async _initializeIfRequiredAsync(): Promise { - if (this._wsSubscriptionId) { - return; - } - this._wsSubscriptionId = await this._wsClient.subscribeToOrdersAsync(this._handleOrderUpdatesAsync.bind(this)); - await this._fetchOrdersAndStoreAsync(); - // On Reconnnect sync all of the orders currently stored - this._wsClient.onReconnected(() => { - void this._syncOrdersInOrderStoreAsync(); - }); - } - - /** - * Syncs the orders currently stored in the OrderStore. This is used when the connection to mesh - * has reconnected. During this outage there are missed OrderEvents so all orders are re-validated - * for every known asset pair. - */ - private async _syncOrdersInOrderStoreAsync(): Promise { - for (const assetPairKey of await this._orderStore.keysAsync()) { - const currentOrders = await this._orderStore.getOrderSetForAssetPairAsync(assetPairKey); - const { rejected } = await utils.attemptAsync(() => - this._wsClient.addOrdersAsync(Array.from(currentOrders.values()).map(o => o.order)), - ); - // Remove any rejected orders - await this._updateStoreAsync({ - assetPairKey, - added: [], - removed: rejected.map(o => MeshOrderProvider._orderInfoToAPIOrder(o)), - }); - } - await this._fetchOrdersAndStoreAsync(); - } - - /** - * Fetches all of the Orders available in Mesh. All orders are then stored in the - * OrderStore. - */ - private async _fetchOrdersAndStoreAsync(): Promise { - const ordersByAssetPairKey: { [assetPairKey: string]: APIOrder[] } = {}; - // Fetch all orders in Mesh - const orders = await utils.attemptAsync(() => this._wsClient.getOrdersAsync()); - for (const order of orders) { - const { makerAssetData, takerAssetData } = order.signedOrder; - const assetPairKey = OrderStore.getKeyForAssetPair(makerAssetData, takerAssetData); - if (!ordersByAssetPairKey[assetPairKey]) { - ordersByAssetPairKey[assetPairKey] = []; - } - ordersByAssetPairKey[assetPairKey].push(MeshOrderProvider._orderInfoToAPIOrder(order)); - } - for (const assetPairKey of Object.keys(ordersByAssetPairKey)) { - await this._updateStoreAsync({ - added: ordersByAssetPairKey[assetPairKey], - removed: [], - assetPairKey, - }); - } - } - - /** - * Handles the order events converting to APIOrders and either adding or removing based on its kind. - * @param orderEvents The set of `OrderEvents` returned from a mesh subscription update - */ - private async _handleOrderUpdatesAsync(orderEvents: OrderEvent[]): Promise { - const addedRemovedByAssetPairKey: { [assetPairKey: string]: AddedRemovedOrders } = {}; - for (const event of orderEvents) { - const { makerAssetData, takerAssetData } = event.signedOrder; - const assetPairKey = OrderStore.getKeyForAssetPair(makerAssetData, takerAssetData); - if (!addedRemovedByAssetPairKey[assetPairKey]) { - addedRemovedByAssetPairKey[assetPairKey] = { added: [], removed: [], assetPairKey }; - } - const apiOrder = MeshOrderProvider._orderInfoToAPIOrder(event); - switch (event.endState) { - case OrderEventEndState.Added: - case OrderEventEndState.Unexpired: { - addedRemovedByAssetPairKey[assetPairKey].added.push(apiOrder); - break; - } - case OrderEventEndState.Cancelled: - case OrderEventEndState.Expired: - case OrderEventEndState.FullyFilled: - case OrderEventEndState.Unfunded: - case OrderEventEndState.StoppedWatching: { - addedRemovedByAssetPairKey[assetPairKey].removed.push(apiOrder); - break; - } - case OrderEventEndState.FillabilityIncreased: - case OrderEventEndState.Filled: { - addedRemovedByAssetPairKey[assetPairKey].added.push(apiOrder); - break; - } - default: - break; - } - } - for (const assetPairKey of Object.keys(addedRemovedByAssetPairKey)) { - await this._updateStoreAsync(addedRemovedByAssetPairKey[assetPairKey]); - } - } -} diff --git a/packages/orderbook/src/order_provider/sra_polling_order_provider.ts b/packages/orderbook/src/order_provider/sra_polling_order_provider.ts deleted file mode 100644 index 96d8133686..0000000000 --- a/packages/orderbook/src/order_provider/sra_polling_order_provider.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { assert } from '@0x/assert'; -import { intervalUtils } from '@0x/utils'; - -import { OrderSet } from '../order_set'; -import { OrderStore } from '../order_store'; -import { SRAPollingOrderProviderOpts } from '../types'; - -import { BaseSRAOrderProvider } from './base_sra_order_provider'; - -export class SRAPollingOrderProvider extends BaseSRAOrderProvider { - private readonly _assetPairKeyToPollingIntervalId: Map = new Map(); - private readonly _pollingIntervalMs: number; - - /** - * Instantiates a HTTP [Standard Relayer API](https://github.com/0xProject/standard-relayer-api) - * Polling Order Provider - * @param opts `SRAPollingOrderProviderOpts` containing the httpEndpoint to an SRA backend and polling options - * @param orderStore The `OrderStore` where orders are added and removed from - */ - constructor(opts: SRAPollingOrderProviderOpts, orderStore: OrderStore) { - super(orderStore, opts.httpEndpoint, opts.perPage); - assert.isNumber('pollingIntervalMs', opts.pollingIntervalMs); - this._pollingIntervalMs = opts.pollingIntervalMs; - } - - /** - * Creates a http polling subscription and fetches the current orders from SRA. - * @param makerAssetData the maker asset Data - * @param takerAssetData the taker asset Data - */ - public async createSubscriptionForAssetPairAsync(makerAssetData: string, takerAssetData: string): Promise { - const assetPairKey = OrderStore.getKeyForAssetPair(makerAssetData, takerAssetData); - // Do nothing if we already have a polling interval or websocket created for this asset pair - if (this._assetPairKeyToPollingIntervalId.has(assetPairKey)) { - return; - } - await this._fetchAndCreatePollingAsync(makerAssetData, takerAssetData); - } - - /** - * Destroys the order provider, removing any subscriptions - */ - public async destroyAsync(): Promise { - for (const [assetPairKey, id] of this._assetPairKeyToPollingIntervalId) { - clearInterval(id); - this._assetPairKeyToPollingIntervalId.delete(assetPairKey); - } - } - - /** - * Fetches all of the orders for both sides of the orderbook and stores them. A polling subscription - * is created performing this action every pollingIntervalMs - */ - private async _fetchAndCreatePollingAsync(makerAssetData: string, takerAssetData: string): Promise { - const assetPairKey = OrderStore.getKeyForAssetPair(makerAssetData, takerAssetData); - // first time we have had this request, preload the local storage - const orders = await this._fetchLatestOrdersAsync(makerAssetData, takerAssetData); - // Set the OrderSet for the polling to diff against - await this._updateStoreAsync({ added: orders, removed: [], assetPairKey }); - // Create a HTTP polling subscription - const pollingIntervalId = (this._createPollingSubscription(makerAssetData, takerAssetData) as any) as number; - this._assetPairKeyToPollingIntervalId.set(assetPairKey, pollingIntervalId); - } - - /** - * Creates the polling interval fetching the orders, calculating the diff and updating the store - */ - private _createPollingSubscription(makerAssetData: string, takerAssetData: string): NodeJS.Timer { - const assetPairKey = OrderStore.getKeyForAssetPair(makerAssetData, takerAssetData); - const pollingIntervalId = intervalUtils.setAsyncExcludingInterval( - async () => { - const previousOrderSet = await this._orderStore.getOrderSetForAssetPairAsync(assetPairKey); - const orders = await this._fetchLatestOrdersAsync(makerAssetData, takerAssetData); - const orderSet = new OrderSet(); - await orderSet.addManyAsync(orders); - const diff = await previousOrderSet.diffAsync(orderSet); - await this._updateStoreAsync({ ...diff, assetPairKey }); - }, - this._pollingIntervalMs, - (_: Error) => { - // TODO(dave4506) Add richer errors - throw new Error(`Fetching latest orders for asset pair ${makerAssetData}/${takerAssetData}`); - }, - ); - return pollingIntervalId; - } -} diff --git a/packages/orderbook/src/order_provider/sra_websocket_order_provider.ts b/packages/orderbook/src/order_provider/sra_websocket_order_provider.ts deleted file mode 100644 index 1dd123289c..0000000000 --- a/packages/orderbook/src/order_provider/sra_websocket_order_provider.ts +++ /dev/null @@ -1,179 +0,0 @@ -import { assert } from '@0x/assert'; -import { - APIOrder, - OrdersChannel, - ordersChannelFactory, - OrdersChannelHandler, - OrdersChannelSubscriptionOpts, -} from '@0x/connect'; -import { BigNumber } from '@0x/utils'; - -import { OrderSet } from '../order_set'; -import { OrderStore } from '../order_store'; -import { AddedRemovedOrders, SRAWebsocketOrderProviderOpts } from '../types'; -import { utils } from '../utils'; - -import { BaseSRAOrderProvider, PER_PAGE_DEFAULT } from './base_sra_order_provider'; - -export class SRAWebsocketOrderProvider extends BaseSRAOrderProvider { - private readonly _websocketEndpoint: string; - private readonly _wsSubscriptions: Map = new Map(); - private _ordersChannel?: OrdersChannel; - private _isDestroyed = false; - private _isConnecting = false; - - /** - * Instantiates a HTTP and WS [Standard Relayer API](https://github.com/0xProject/standard-relayer-api) Order Provider - * @param opts `SRAWebsocketOrderProviderOpts` containing the websocketEndpoint and the httpEndpoint to an SRA backend. - * @param orderStore The `OrderStore` where orders are added and removed from - */ - constructor(opts: SRAWebsocketOrderProviderOpts, orderStore: OrderStore) { - super(orderStore, opts.httpEndpoint, PER_PAGE_DEFAULT); - assert.isUri('websocketEndpoint', opts.websocketEndpoint); - this._websocketEndpoint = opts.websocketEndpoint; - } - - /** - * Creates a websocket subscription and fetches the current orders from SRA. If a websocket - * connection already exists this function is a noop. - * @param makerAssetData the Maker Asset Data - * @param takerAssetData the Taker Asset Data - */ - public async createSubscriptionForAssetPairAsync(makerAssetData: string, takerAssetData: string): Promise { - // If we've previously been destroyed then reset - this._isDestroyed = false; - const assetPairKey = OrderStore.getKeyForAssetPair(makerAssetData, takerAssetData); - if (this._wsSubscriptions.has(assetPairKey)) { - return; - } - return this._fetchAndCreateSubscriptionAsync(makerAssetData, takerAssetData); - } - - /** - * Destroys the order provider, removing any subscriptions - */ - public async destroyAsync(): Promise { - this._isDestroyed = true; - this._wsSubscriptions.clear(); - if (this._ordersChannel) { - this._ordersChannel.close(); - this._ordersChannel = undefined; - } - } - - /** - * Creates a websocket subscription. If the inital websocket connnection - * does not exist, it is created. - * @param makerAssetData the Maker Asset Data - * @param takerAssetData the Taker Asset Data - */ - private async _createWebsocketSubscriptionAsync(makerAssetData: string, takerAssetData: string): Promise { - // Prevent creating multiple channels - while (this._isConnecting && !this._ordersChannel) { - await utils.delayAsync(100); - } - if (!this._ordersChannel) { - this._isConnecting = true; - try { - this._ordersChannel = await this._createOrdersChannelAsync(); - } finally { - this._isConnecting = false; - } - } - const assetPairKey = OrderStore.getKeyForAssetPair(makerAssetData, takerAssetData); - const subscriptionOpts = { - makerAssetData, - takerAssetData, - }; - this._wsSubscriptions.set(assetPairKey, subscriptionOpts); - // Subscribe to both sides of the book - this._ordersChannel.subscribe(subscriptionOpts); - this._ordersChannel.subscribe({ - ...subscriptionOpts, - makerAssetData: takerAssetData, - takerAssetData: makerAssetData, - }); - } - - private async _fetchAndCreateSubscriptionAsync(makerAssetData: string, takerAssetData: string): Promise { - // Create the subscription first to get any updates while waiting for the request - await this._createWebsocketSubscriptionAsync(makerAssetData, takerAssetData); - // first time we have had this request, preload the local storage - const orders = await this._fetchLatestOrdersAsync(makerAssetData, takerAssetData); - const assetPairKey = OrderStore.getKeyForAssetPair(makerAssetData, takerAssetData); - const currentOrders = await this._orderStore.getOrderSetForAssetPairAsync(assetPairKey); - const newOrders = new OrderSet(); - await newOrders.addManyAsync(orders); - const diff = await currentOrders.diffAsync(newOrders); - await this._updateStoreAsync({ - added: diff.added, - removed: diff.removed, - assetPairKey, - }); - } - - private async _syncOrdersInOrderStoreAsync(): Promise { - for (const assetPairKey of await this._orderStore.keysAsync()) { - const [assetDataA, assetDataB] = OrderStore.assetPairKeyToAssets(assetPairKey); - await this._fetchAndCreateSubscriptionAsync(assetDataA, assetDataB); - } - } - - /** - * Creates a new websocket orders channel. - */ - private async _createOrdersChannelAsync(): Promise { - const ordersChannelHandler: OrdersChannelHandler = { - onUpdate: async (_channel, _opts, apiOrders) => this._handleOrderUpdatesAsync(apiOrders), - // tslint:disable-next-line:no-empty - onError: (_channel, _err) => {}, - onClose: async () => { - // Do not reconnect if destroyed - if (this._isDestroyed) { - return; - } - // Re-sync and create subscriptions - await utils.attemptAsync(async () => { - this._ordersChannel = undefined; - await this._syncOrdersInOrderStoreAsync(); - return true; - }); - }, - }; - try { - return await ordersChannelFactory.createWebSocketOrdersChannelAsync( - this._websocketEndpoint, - ordersChannelHandler, - ); - } catch (e) { - throw new Error(`Creating websocket connection to ${this._websocketEndpoint}`); - } - } - - /** - * Handles updates from the websocket, adding new orders and removing orders - * which have remainingFillableTakerAssetAmount as 0. - * @param orders the set of API Orders returned from the websocket channel - */ - private async _handleOrderUpdatesAsync(orders: APIOrder[]): Promise { - const addedRemovedByKey: { [assetPairKey: string]: AddedRemovedOrders } = {}; - for (const order of orders) { - const assetPairKey = OrderStore.getKeyForAssetPair(order.order.makerAssetData, order.order.takerAssetData); - if (!addedRemovedByKey[assetPairKey]) { - addedRemovedByKey[assetPairKey] = { added: [], removed: [], assetPairKey }; - } - const addedRemoved = addedRemovedByKey[assetPairKey]; - // If we have the metadata informing us that the order cannot be filled for any amount we don't add it - const remainingFillableTakerAssetAmount = (order.metaData as any).remainingFillableTakerAssetAmount; - if (remainingFillableTakerAssetAmount && new BigNumber(remainingFillableTakerAssetAmount).eq(0)) { - addedRemoved.removed.push(order); - } else { - addedRemoved.added.push(order); - } - } - - for (const assetPairKey of Object.keys(addedRemovedByKey)) { - await this._updateStoreAsync(addedRemovedByKey[assetPairKey]); - } - } -} diff --git a/packages/orderbook/src/order_set.ts b/packages/orderbook/src/order_set.ts deleted file mode 100644 index 38f330ee79..0000000000 --- a/packages/orderbook/src/order_set.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { APIOrder } from '@0x/connect'; - -import { utils } from './utils'; - -export class OrderSet { - private readonly _map: Map; - constructor() { - this._map = new Map(); - (this as any)[Symbol.iterator] = this.values; - } - - public size(): number { - return this._map.size; - } - - public async addAsync(item: APIOrder): Promise { - const orderHash = utils.getOrderHash(item); - (item.metaData as any).orderHash = orderHash; - this._map.set(orderHash, item); - } - - public async addManyAsync(items: APIOrder[]): Promise { - for (const item of items) { - await this.addAsync(item); - } - } - - public async hasAsync(order: APIOrder): Promise { - return this._map.has(utils.getOrderHash(order)); - } - - public async diffAsync(other: OrderSet): Promise<{ added: APIOrder[]; removed: APIOrder[] }> { - const added: APIOrder[] = []; - const removed: APIOrder[] = []; - for (const otherItem of other.values()) { - const doesContainItem = this._map.has(utils.getOrderHash(otherItem)); - if (!doesContainItem) { - added.push(otherItem); - } - } - for (const item of this.values()) { - const doesContainItem = other._map.has(utils.getOrderHash(item)); - if (!doesContainItem) { - removed.push(item); - } - } - return { added, removed }; - } - - public values(): IterableIterator { - return this._map.values(); - } - - public async deleteAsync(item: APIOrder): Promise { - return this._map.delete(utils.getOrderHash(item)); - } - - public async deleteManyAsync(items: APIOrder[]): Promise { - for (const item of items) { - await this.deleteAsync(item); - } - } -} diff --git a/packages/orderbook/src/order_store.ts b/packages/orderbook/src/order_store.ts deleted file mode 100644 index f3c4f59e6a..0000000000 --- a/packages/orderbook/src/order_store.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { APIOrder } from '@0x/connect'; - -import { OrderSet } from './order_set'; -import { AddedRemovedOrders } from './types'; - -export class OrderStore { - // Both bids and asks are stored together in one set - private readonly _orders: Map = new Map(); - public static getKeyForAssetPair(makerAssetData: string, takerAssetData: string): string { - return [makerAssetData, takerAssetData].sort().join('-'); - } - public static assetPairKeyToAssets(assetPairKey: string): string[] { - return assetPairKey.split('-'); - } - public async getOrderSetForAssetsAsync(makerAssetData: string, takerAssetData: string): Promise { - const assetPairKey = OrderStore.getKeyForAssetPair(makerAssetData, takerAssetData); - return this.getOrderSetForAssetPairAsync(assetPairKey); - } - public async getOrderSetForAssetPairAsync(assetPairKey: string): Promise { - const orderSet = this._orders.get(assetPairKey); - if (!orderSet) { - const newOrderSet = new OrderSet(); - this._orders.set(assetPairKey, newOrderSet); - return newOrderSet; - } - return orderSet; - } - public async getBatchOrderSetsForAssetsAsync( - makerAssetDatas: string[], - takerAssetDatas: string[], - ): Promise { - const orderSets: OrderSet[] = []; - for (const makerAssetData of makerAssetDatas) { - for (const takerAssetData of takerAssetDatas) { - const orderSet = await this.getOrderSetForAssetsAsync(makerAssetData, takerAssetData); - orderSets.push(orderSet); - } - } - return orderSets; - } - public async updateAsync(addedRemoved: AddedRemovedOrders): Promise { - const { added, removed, assetPairKey } = addedRemoved; - const orders = await this.getOrderSetForAssetPairAsync(assetPairKey); - await orders.addManyAsync(added); - await orders.deleteManyAsync(removed); - } - public async hasAsync(assetPairKey: string): Promise { - return this._orders.has(assetPairKey); - } - public async valuesAsync(assetPairKey: string): Promise { - return Array.from((await this.getOrderSetForAssetPairAsync(assetPairKey)).values()); - } - public async keysAsync(): Promise> { - return this._orders.keys(); - } -} diff --git a/packages/orderbook/src/orderbook.ts b/packages/orderbook/src/orderbook.ts deleted file mode 100644 index 5031e6c6db..0000000000 --- a/packages/orderbook/src/orderbook.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { assert } from '@0x/assert'; -import { APIOrder } from '@0x/connect'; -import { AssetPairsItem, SignedOrder } from '@0x/types'; - -import { BaseOrderProvider } from './order_provider/base_order_provider'; -import { CustomOrderProvider } from './order_provider/custom_order_provider'; -import { MeshOrderProvider } from './order_provider/mesh_order_provider'; -import { SRAPollingOrderProvider } from './order_provider/sra_polling_order_provider'; -import { SRAWebsocketOrderProvider } from './order_provider/sra_websocket_order_provider'; -import { OrderStore } from './order_store'; -import { - AcceptedRejectedOrders, - MeshOrderProviderOpts, - SRAPollingOrderProviderOpts, - SRAWebsocketOrderProviderOpts, -} from './types'; - -export class Orderbook { - private readonly _orderProvider: BaseOrderProvider; - private readonly _orderStore: OrderStore; - /** - * Creates an Orderbook with the provided orders. This provider simply stores the - * orders and allows querying. No validation or subscriptions occur. - * @param orders the set of SignedOrders - */ - public static getOrderbookForProvidedOrders(orders: SignedOrder[]): Orderbook { - const orderStore = new OrderStore(); - return new Orderbook(new CustomOrderProvider(orders, orderStore), orderStore); - } - /** - * Creates an Orderbook with the SRA Websocket Provider. This Provider fetches orders via - * the SRA http endpoint and then subscribes to the asset pair for future updates. - * @param opts the `SRAWebsocketOrderProviderOpts` - */ - public static getOrderbookForWebsocketProvider(opts: SRAWebsocketOrderProviderOpts): Orderbook { - const orderStore = new OrderStore(); - return new Orderbook(new SRAWebsocketOrderProvider(opts, orderStore), orderStore); - } - /** - * Creates an Orderbook with SRA Polling Provider. This Provider simply polls every interval. - * @param opts the `SRAPollingOrderProviderOpts` - */ - public static getOrderbookForPollingProvider(opts: SRAPollingOrderProviderOpts): Orderbook { - const orderStore = new OrderStore(); - return new Orderbook(new SRAPollingOrderProvider(opts, orderStore), orderStore); - } - /** - * Creates an Orderbook with a Mesh Order Provider. This Provider fetches ALL orders - * and subscribes to updates on ALL orders. - * @param opts the `MeshOrderProviderOpts` - */ - public static getOrderbookForMeshProvider(opts: MeshOrderProviderOpts): Orderbook { - const orderStore = new OrderStore(); - return new Orderbook(new MeshOrderProvider(opts, orderStore), orderStore); - } - /** - * Creates an Orderbook with the order provider. All order updates are stored - * in the `OrderStore`. - * @param orderProvider the order provider, e.g SRAWebbsocketOrderProvider - * @param orderStore the order store where orders are added and deleted - */ - constructor(orderProvider: BaseOrderProvider, orderStore: OrderStore) { - this._orderProvider = orderProvider; - this._orderStore = orderStore; - } - /** - * Returns all orders where the order.makerAssetData == makerAssetData and - * order.takerAssetData == takerAssetData. This pair is then subscribed to - * and all future updates will be stored. The first request - * to `getOrdersAsync` might fetch the orders from the Order Provider and create a subscription. - * Subsequent requests will be quick and up to date and synced with the Order Provider state. - * @param makerAssetData the maker asset data - * @param takerAssetData the taker asset data - */ - public async getOrdersAsync(makerAssetData: string, takerAssetData: string): Promise { - assert.isString('makerAssetData', makerAssetData); - assert.isString('takerAssetData', takerAssetData); - const assetPairKey = OrderStore.getKeyForAssetPair(makerAssetData, takerAssetData); - if (!(await this._orderStore.hasAsync(assetPairKey))) { - await this._orderProvider.createSubscriptionForAssetPairAsync(makerAssetData, takerAssetData); - } - const orders = await this._orderStore.valuesAsync(assetPairKey); - return orders.filter( - o => o.order.makerAssetData === makerAssetData && o.order.takerAssetData === takerAssetData, - ); - } - public async getBatchOrdersAsync(makerAssetDatas: string[], takerAssetDatas: string[]): Promise { - for (const [mi, makerAssetData] of makerAssetDatas.entries()) { - for (const [ti, takerAssetData] of makerAssetDatas.entries()) { - assert.isString(`makerAssetDatas[${mi}]`, makerAssetData); - assert.isString(`takerAssetDatas[${ti}]`, takerAssetData); - const assetPairKey = OrderStore.getKeyForAssetPair(makerAssetData, takerAssetData); - if (!(await this._orderStore.hasAsync(assetPairKey))) { - await this._orderProvider.createSubscriptionForAssetPairAsync(makerAssetData, takerAssetData); - } - } - } - const orderSets = await this._orderStore.getBatchOrderSetsForAssetsAsync(makerAssetDatas, takerAssetDatas); - return orderSets.map(orderSet => - Array.from(orderSet.values()).filter( - o => - makerAssetDatas.includes(o.order.makerAssetData) && - takerAssetDatas.includes(o.order.takerAssetData), - ), - ); - } - /** - * Returns all of the Available Asset Pairs for the provided Order Provider. - */ - public async getAvailableAssetDatasAsync(): Promise { - return this._orderProvider.getAvailableAssetDatasAsync(); - } - /** - * Adds the orders to the Order Provider. All accepted orders will be returned - * and rejected orders will be returned with an message indicating a reason for its rejection - * @param orders The set of Orders to add to the Order Provider - */ - public async addOrdersAsync(orders: SignedOrder[]): Promise { - return this._orderProvider.addOrdersAsync(orders); - } - /** - * Destroys any subscriptions or connections. - */ - public async destroyAsync(): Promise { - return this._orderProvider.destroyAsync(); - } -} diff --git a/packages/orderbook/src/types.ts b/packages/orderbook/src/types.ts deleted file mode 100644 index 15e508e22c..0000000000 --- a/packages/orderbook/src/types.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { APIOrder, SignedOrder } from '@0x/connect'; -import { WSOpts } from '@0x/mesh-rpc-client'; - -export interface AddedRemovedOrders { - assetPairKey: string; - added: APIOrder[]; - removed: APIOrder[]; -} - -export interface RejectedOrder { - message: string; - order: SignedOrder; -} -export interface AcceptedRejectedOrders { - accepted: SignedOrder[]; - rejected: RejectedOrder[]; -} - -export type AddedRemovedListeners = (addedRemoved: AddedRemovedOrders) => void; - -/** - * Constructor options for a SRA Websocket Order Provider - */ -export interface SRAWebsocketOrderProviderOpts { - // The http endpoint to the SRA service, e.g https://sra.0x.org/v3 - httpEndpoint: string; - // The websocket endpoint to the SRA service, e.g wss://ws.sra.0x.org/ - websocketEndpoint: string; -} - -/** - * Constructor options for a SRA Polling Order Provider - */ -export interface SRAPollingOrderProviderOpts { - // The http endpoint to the SRA service, e.g https://sra.0x.org/v3 - httpEndpoint: string; - // The interval between polling for each subscription - pollingIntervalMs: number; - // The amount of records to request per request to the SRA endpoint - perPage?: number; - // The chain Id - chainId?: number; -} - -/** - * Constructor options for a Mesh Order Provider - */ -export interface MeshOrderProviderOpts { - // The websocket endpoint for the Mesh service - websocketEndpoint: string; - // Additional options to configure the Mesh client, e.g reconnectAfter - wsOpts?: WSOpts; -} diff --git a/packages/orderbook/src/utils.ts b/packages/orderbook/src/utils.ts deleted file mode 100644 index 04610b1314..0000000000 --- a/packages/orderbook/src/utils.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { APIOrder, SignedOrder } from '@0x/connect'; -import { orderHashUtils } from '@0x/order-utils'; - -export const utils = { - getOrderHash(order: APIOrder | SignedOrder): string { - if ((order as APIOrder).metaData) { - const apiOrder = order as APIOrder; - const orderHash = (apiOrder.metaData as any).orderHash || orderHashUtils.getOrderHash(apiOrder.order); - return orderHash; - } else { - const signedOrder = order as SignedOrder; - const orderHash = orderHashUtils.getOrderHash(signedOrder); - return orderHash; - } - }, - async delayAsync(ms: number): Promise { - // tslint:disable:no-inferred-empty-object-type - return new Promise(resolve => setTimeout(resolve, ms)); - }, - async attemptAsync( - fn: () => Promise, - opts: { interval: number; maxRetries: number } = { interval: 1000, maxRetries: 10 }, - ): Promise { - let result: T | undefined; - let attempt = 0; - let error; - let isSuccess = false; - while (!result && attempt < opts.maxRetries) { - attempt++; - try { - result = await fn(); - isSuccess = true; - error = undefined; - } catch (err) { - error = err; - await utils.delayAsync(opts.interval); - } - } - if (!isSuccess) { - throw error; - } - return result as T; - }, -}; diff --git a/packages/orderbook/test/order_provider/mesh_order_provider.test.ts b/packages/orderbook/test/order_provider/mesh_order_provider.test.ts deleted file mode 100644 index ab9d8c5fcc..0000000000 --- a/packages/orderbook/test/order_provider/mesh_order_provider.test.ts +++ /dev/null @@ -1,279 +0,0 @@ -import { BigNumber, WSClient } from '@0x/mesh-rpc-client'; -import * as sinon from 'sinon'; - -import { MeshOrderProvider } from '../../src'; -import { BaseOrderProvider } from '../../src/order_provider/base_order_provider'; -import { OrderStore } from '../../src/order_store'; -import { utils } from '../../src/utils'; -import { createOrder } from '../utils'; - -import { SERVER_PORT, setupServerAsync, stopServer } from './mock_ws_server'; - -describe('MeshOrderProvider', () => { - let orderStore: OrderStore; - let provider: BaseOrderProvider; - const stubs: sinon.SinonStub[] = []; - - const websocketEndpoint = `ws://localhost:${SERVER_PORT}`; - const makerAssetData = '0xf47261b000000000000000000000000089d24a6b4ccb1b6faa2625fe562bdd9a23260359'; - const takerAssetData = '0xf47261b0000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2'; - const subscriptionId = 'subscriptionId'; - const addedResponse = { - jsonrpc: '2.0', - method: 'mesh_subscription', - params: { - subscription: subscriptionId, - result: [ - { - orderHash: '0xa452cc6e2c7756376f0f2379e7dd81aa9285b26515774d0ad8801a4c243a30a3', - signedOrder: { - chainId: 1337, - exchangeAddress: '0x4eacd0af335451709e1e7b570b8ea68edec8bc97', - makerAddress: '0x8c5c2671b71bad73d8b6fb7e8ef6fe5ec95ff661', - makerAssetData, - makerFeeAssetData: '0x', - makerAssetAmount: '19501674723', - makerFee: '0', - takerAddress: '0x0000000000000000000000000000000000000000', - takerAssetData, - takerFeeAssetData: '0x', - takerAssetAmount: '132880707765170593819', - takerFee: '0', - senderAddress: '0x0000000000000000000000000000000000000000', - feeRecipientAddress: '0x0000000000000000000000000000000000000000', - expirationTimeSeconds: '1574687060', - salt: '1574686820004', - signature: - '0x1b64e67271f10832485356d9ef203b7e2c855067c1253b4e66ee06e85cd46427b157fc4c60f86bd637291f971d1443f65f631b76b887b7f82ebb36499f2f9cf10d03', - }, - endState: 'ADDED', - fillableTakerAssetAmount: '132880707765170593819', - contractEvents: [], - }, - ], - }, - }; - const removedResponse = { - ...addedResponse, - ...{ - params: { - ...addedResponse.params, - result: [{ ...addedResponse.params.result[0], endState: 'CANCELLED', fillableTakerAssetAmount: '0' }], - }, - }, - }; - - let wsServer: any; - let connection: any; - afterEach(() => { - void provider.destroyAsync(); - stubs.forEach(s => s.restore()); - stopServer(); - }); - beforeEach(async () => { - orderStore = new OrderStore(); - stubs.push( - sinon - .stub(WSClient.prototype as any, '_startInternalLivenessCheckAsync') - .callsFake(async () => Promise.resolve()), - ); - }); - describe('#createSubscriptionForAssetPairAsync', () => { - beforeEach(async () => { - wsServer = await setupServerAsync(); - wsServer.on('connect', (conn: any) => { - connection = conn; - conn.on('message', (message: any) => { - const jsonRpcRequest = JSON.parse(message.utf8Data); - if (jsonRpcRequest.method === 'mesh_subscribe') { - connection.sendUTF( - JSON.stringify({ - id: jsonRpcRequest.id, - jsonrpc: '2.0', - result: subscriptionId, - }), - ); - } - }); - }); - }); - test('fetches order on first subscription', async () => { - const getOrdersStub = sinon - .stub(WSClient.prototype, 'getOrdersAsync') - .callsFake(async () => Promise.resolve([])); - stubs.push(getOrdersStub); - const subscriptionStub = sinon - .stub(WSClient.prototype, 'subscribeToOrdersAsync') - .callsFake(async () => Promise.resolve('suscriptionId')); - stubs.push(subscriptionStub); - provider = new MeshOrderProvider({ websocketEndpoint }, orderStore); - await provider.createSubscriptionForAssetPairAsync(makerAssetData, takerAssetData); - expect(getOrdersStub.callCount).toBe(1); - expect(subscriptionStub.callCount).toBe(1); - }); - test('fetches once when the same subscription is called', async () => { - const stub = sinon.stub(WSClient.prototype, 'getOrdersAsync').callsFake(async () => Promise.resolve([])); - stubs.push(stub); - stubs.push( - sinon - .stub(WSClient.prototype, 'subscribeToOrdersAsync') - .callsFake(async () => Promise.resolve(subscriptionId)), - ); - provider = new MeshOrderProvider({ websocketEndpoint }, orderStore); - await provider.createSubscriptionForAssetPairAsync(makerAssetData, takerAssetData); - await provider.createSubscriptionForAssetPairAsync(makerAssetData, takerAssetData); - await provider.createSubscriptionForAssetPairAsync(makerAssetData, takerAssetData); - expect(stub.callCount).toBe(1); - }); - test('stores the orders', async () => { - const order = createOrder(makerAssetData, takerAssetData); - const orderInfo = { - orderHash: '0x00', - signedOrder: order.order, - fillableTakerAssetAmount: new BigNumber(1), - }; - stubs.push( - sinon.stub(WSClient.prototype, 'getOrdersAsync').callsFake(async () => Promise.resolve([orderInfo])), - ); - stubs.push( - sinon - .stub(WSClient.prototype, 'subscribeToOrdersAsync') - .callsFake(async () => Promise.resolve(subscriptionId)), - ); - provider = new MeshOrderProvider({ websocketEndpoint }, orderStore); - await provider.createSubscriptionForAssetPairAsync(makerAssetData, takerAssetData); - const orders = await orderStore.getOrderSetForAssetsAsync(makerAssetData, takerAssetData); - expect(orders.size()).toBe(1); - }); - test('stores the orders from a subscription update', async () => { - const eventResponse = JSON.stringify(addedResponse); - stubs.push(sinon.stub(WSClient.prototype, 'getOrdersAsync').callsFake(async () => Promise.resolve([]))); - provider = new MeshOrderProvider({ websocketEndpoint }, orderStore); - await provider.createSubscriptionForAssetPairAsync(makerAssetData, takerAssetData); - connection.sendUTF(eventResponse); - await utils.delayAsync(100); - const orders = await orderStore.getOrderSetForAssetsAsync(makerAssetData, takerAssetData); - expect(orders.size()).toBe(1); - }); - test('removes orders on a subscription update', async () => { - const added = JSON.stringify(addedResponse); - const removed = JSON.stringify(removedResponse); - stubs.push(sinon.stub(WSClient.prototype, 'getOrdersAsync').callsFake(async () => Promise.resolve([]))); - provider = new MeshOrderProvider({ websocketEndpoint }, orderStore); - await provider.createSubscriptionForAssetPairAsync(makerAssetData, takerAssetData); - connection.sendUTF(added); - await utils.delayAsync(100); - const orders = await orderStore.getOrderSetForAssetsAsync(makerAssetData, takerAssetData); - expect(orders.size()).toBe(1); - connection.sendUTF(removed); - await utils.delayAsync(100); - expect(orders.size()).toBe(0); - }); - }); - describe('reconnnect', () => { - test.skip('revalidates all stored orders', async () => { - wsServer = await setupServerAsync(); - const orderInfoResponse = { - jsonrpc: '2.0', - result: { - accepted: [], - rejected: [{ ...addedResponse.params.result[0], kind: 'CANCELLED', fillableTakerAssetAmount: 0 }], - }, - }; - wsServer.on('connect', (conn: any) => { - connection = conn; - conn.on('message', (message: any) => { - const jsonRpcRequest = JSON.parse(message.utf8Data); - if (jsonRpcRequest.method === 'mesh_subscribe') { - connection.sendUTF( - JSON.stringify({ - id: jsonRpcRequest.id, - jsonrpc: '2.0', - result: subscriptionId, - }), - ); - } else if (jsonRpcRequest.method === 'mesh_addOrders') { - connection.sendUTF( - JSON.stringify({ - id: jsonRpcRequest.id, - ...orderInfoResponse, - }), - ); - } - }); - }); - - const getOrdersStub = sinon - .stub(WSClient.prototype, 'getOrdersAsync') - .callsFake(async () => Promise.resolve([])); - const addOrdersStub = sinon - .stub(WSClient.prototype, 'addOrdersAsync') - .callsFake(async () => Promise.resolve({ accepted: [], rejected: [] })); - stubs.push(getOrdersStub); - stubs.push(addOrdersStub); - provider = new MeshOrderProvider( - { - websocketEndpoint, - wsOpts: { - reconnectAfter: 1, - clientConfig: { - fragmentOutgoingMessages: false, - }, - }, - }, - orderStore, - ); - await provider.createSubscriptionForAssetPairAsync(makerAssetData, takerAssetData); - const orders = await orderStore.getOrderSetForAssetsAsync(makerAssetData, takerAssetData); - expect(getOrdersStub.callCount).toBe(1); - // Orders are not added on a subscription, only during reconnnect - expect(addOrdersStub.callCount).toBe(0); - const added = JSON.stringify(addedResponse); - connection.sendUTF(added); - await utils.delayAsync(100); - expect(orders.size()).toBe(1); - // Drop the connection and check orders are re-validated - connection.drop(); - await utils.delayAsync(100); - expect(addOrdersStub.callCount).toBe(1); - }); - }); - describe('#getAvailableAssetDatasAsync', () => { - test('stores the orders', async () => { - const order = createOrder(makerAssetData, takerAssetData); - const orderInfo = { - orderHash: '0x00', - signedOrder: order.order, - fillableTakerAssetAmount: new BigNumber(1), - }; - stubs.push( - sinon.stub(WSClient.prototype, 'getOrdersAsync').callsFake(async () => Promise.resolve([orderInfo])), - ); - stubs.push( - sinon - .stub(WSClient.prototype, 'subscribeToOrdersAsync') - .callsFake(async () => Promise.resolve(subscriptionId)), - ); - provider = new MeshOrderProvider({ websocketEndpoint }, orderStore); - await provider.createSubscriptionForAssetPairAsync(makerAssetData, takerAssetData); - const assetPairs = await provider.getAvailableAssetDatasAsync(); - expect(assetPairs.length).toBe(2); - const assetDataA = { - assetData: makerAssetData, - maxAmount: new BigNumber( - '115792089237316195423570985008687907853269984665640564039457584007913129639935', - ), - minAmount: new BigNumber('0'), - precision: 18, - }; - const assetDataB = { - ...assetDataA, - assetData: takerAssetData, - }; - expect(assetPairs).toMatchObject([ - { assetDataA, assetDataB }, - { assetDataA: assetDataB, assetDataB: assetDataA }, - ]); - }); - }); -}); diff --git a/packages/orderbook/test/order_provider/mock_ws_server.ts b/packages/orderbook/test/order_provider/mock_ws_server.ts deleted file mode 100644 index 54286f46cb..0000000000 --- a/packages/orderbook/test/order_provider/mock_ws_server.ts +++ /dev/null @@ -1,50 +0,0 @@ -import * as http from 'http'; -import * as WebSocket from 'websocket'; - -const DEFAULT_STATUS_CODE = 404; -export const SERVER_PORT = 64321; -// tslint:disable-next-line:custom-no-magic-numbers -const sixtyFourMB = 64 * 1024 * 1024; // 64MiB - -let server: http.Server; -let wsServer: WebSocket.server; - -/** - * Sets up a new test WS server - * @return A WS server - */ -export async function setupServerAsync(): Promise { - return new Promise((resolve, reject) => { - server = http.createServer((_request, response) => { - response.writeHead(DEFAULT_STATUS_CODE); - response.end(); - }); - - wsServer = new WebSocket.server({ - httpServer: server, - autoAcceptConnections: true, - maxReceivedFrameSize: sixtyFourMB, - maxReceivedMessageSize: sixtyFourMB, - fragmentOutgoingMessages: false, - keepalive: false, - disableNagleAlgorithm: false, - }); - - server.listen(SERVER_PORT, () => { - resolve(wsServer); - }); - }); -} - -/** - * Stops the test WS server - */ -export function stopServer(): void { - try { - wsServer.shutDown(); - server.close(); - } catch (e) { - // tslint:disable-next-line:no-console - console.log('stopServer threw', e); - } -} diff --git a/packages/orderbook/test/order_provider/sra_polling_order_provider.test.ts b/packages/orderbook/test/order_provider/sra_polling_order_provider.test.ts deleted file mode 100644 index a014778c41..0000000000 --- a/packages/orderbook/test/order_provider/sra_polling_order_provider.test.ts +++ /dev/null @@ -1,99 +0,0 @@ -import { HttpClient } from '@0x/connect'; -import * as sinon from 'sinon'; - -import { SRAPollingOrderProvider } from '../../src'; -import { BaseOrderProvider } from '../../src/order_provider/base_order_provider'; -import { OrderStore } from '../../src/order_store'; -import { utils } from '../../src/utils'; -import { createOrder } from '../utils'; - -describe('SRAPollingOrderProvider', () => { - let orderStore: OrderStore; - let provider: BaseOrderProvider; - const httpEndpoint = 'https://localhost'; - const makerAssetData = '0xf47261b000000000000000000000000089d24a6b4ccb1b6faa2625fe562bdd9a23260359'; - const takerAssetData = '0xf47261b0000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2'; - const stubs: sinon.SinonStub[] = []; - afterEach(() => { - void provider.destroyAsync(); - stubs.forEach(s => s.restore()); - }); - beforeEach(() => { - orderStore = new OrderStore(); - }); - describe('#createSubscriptionForAssetPairAsync', () => { - test('fetches order on first subscription', async () => { - const stub = sinon - .stub(HttpClient.prototype, 'getOrdersAsync') - .callsFake(async () => Promise.resolve({ records: [], total: 0, perPage: 0, page: 1 })); - stubs.push(stub); - provider = new SRAPollingOrderProvider({ httpEndpoint, pollingIntervalMs: 5 }, orderStore); - await provider.createSubscriptionForAssetPairAsync(makerAssetData, takerAssetData); - expect(stub.callCount).toBe(2); - }); - test('fetches once when the same subscription is created', async () => { - const stub = sinon - .stub(HttpClient.prototype, 'getOrdersAsync') - .callsFake(async () => Promise.resolve({ records: [], total: 0, perPage: 0, page: 1 })); - stubs.push(stub); - provider = new SRAPollingOrderProvider({ httpEndpoint, pollingIntervalMs: 5 }, orderStore); - await provider.createSubscriptionForAssetPairAsync(makerAssetData, takerAssetData); - await provider.createSubscriptionForAssetPairAsync(makerAssetData, takerAssetData); - await provider.createSubscriptionForAssetPairAsync(makerAssetData, takerAssetData); - expect(stub.callCount).toBe(2); - }); - test('periodically polls for orders', async () => { - const stub = sinon.stub(HttpClient.prototype, 'getOrdersAsync').callsFake(async () => - Promise.resolve({ - records: [createOrder(makerAssetData, takerAssetData)], - total: 1, - perPage: 1, - page: 1, - }), - ); - stubs.push(stub); - provider = new SRAPollingOrderProvider({ httpEndpoint, pollingIntervalMs: 1 }, orderStore); - await provider.createSubscriptionForAssetPairAsync(makerAssetData, takerAssetData); - await utils.delayAsync(5); - expect(stub.callCount).toBeGreaterThan(2); - }); - test('stores the orders returned from the API response', async () => { - const records = [createOrder(makerAssetData, takerAssetData)]; - stubs.push( - sinon.stub(HttpClient.prototype, 'getOrdersAsync').callsFake(async () => - Promise.resolve({ - records, - total: 1, - perPage: 1, - page: 1, - }), - ), - ); - provider = new SRAPollingOrderProvider({ httpEndpoint, pollingIntervalMs: 30000 }, orderStore); - await provider.createSubscriptionForAssetPairAsync(makerAssetData, takerAssetData); - const orders = await orderStore.getOrderSetForAssetsAsync(makerAssetData, takerAssetData); - expect(orders.size()).toBe(1); - }); - test('removes the order from the set when the API response no longer returns the order', async () => { - const records = [createOrder(makerAssetData, takerAssetData)]; - stubs.push( - sinon.stub(HttpClient.prototype, 'getOrdersAsync').callsFake(async () => - Promise.resolve({ - records, - total: 1, - perPage: 1, - page: 1, - }), - ), - ); - provider = new SRAPollingOrderProvider({ httpEndpoint, pollingIntervalMs: 1 }, orderStore); - await provider.createSubscriptionForAssetPairAsync(makerAssetData, takerAssetData); - const orders = await orderStore.getOrderSetForAssetsAsync(makerAssetData, takerAssetData); - expect(orders.size()).toBe(1); - // Delete the record from the API response - records.splice(0, 1); - await utils.delayAsync(5); - expect(orders.size()).toBe(0); - }); - }); -}); diff --git a/packages/orderbook/test/order_provider/sra_websocket_order_provider.test.ts b/packages/orderbook/test/order_provider/sra_websocket_order_provider.test.ts deleted file mode 100644 index 36e150df82..0000000000 --- a/packages/orderbook/test/order_provider/sra_websocket_order_provider.test.ts +++ /dev/null @@ -1,142 +0,0 @@ -import { APIOrder, HttpClient, ordersChannelFactory, OrdersChannelHandler } from '@0x/connect'; -import * as sinon from 'sinon'; - -import { SRAWebsocketOrderProvider } from '../../src'; -import { BaseOrderProvider } from '../../src/order_provider/base_order_provider'; -import { OrderStore } from '../../src/order_store'; -import { utils } from '../../src/utils'; -import { createOrder } from '../utils'; - -// tslint:disable-next-line:no-empty -const NOOP = () => {}; - -describe('SRAWebsocketOrderProvider', () => { - let orderStore: OrderStore; - let provider: BaseOrderProvider; - const httpEndpoint = 'https://localhost'; - const websocketEndpoint = 'wss://localhost'; - const makerAssetData = '0xf47261b000000000000000000000000089d24a6b4ccb1b6faa2625fe562bdd9a23260359'; - const takerAssetData = '0xf47261b0000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2'; - const stubs: sinon.SinonStub[] = []; - afterEach(() => { - void provider.destroyAsync(); - stubs.forEach(s => s.restore()); - }); - beforeEach(() => { - orderStore = new OrderStore(); - }); - describe('#createSubscriptionForAssetPairAsync', () => { - test('fetches order on first subscription', async () => { - const httpStub = sinon - .stub(HttpClient.prototype, 'getOrdersAsync') - .callsFake(async () => Promise.resolve({ records: [], total: 0, perPage: 0, page: 1 })); - stubs.push( - sinon - .stub(ordersChannelFactory, 'createWebSocketOrdersChannelAsync') - .callsFake(async () => Promise.resolve({ subscribe: NOOP, close: NOOP })), - ); - stubs.push(httpStub); - provider = new SRAWebsocketOrderProvider({ httpEndpoint, websocketEndpoint }, orderStore); - await provider.createSubscriptionForAssetPairAsync(makerAssetData, takerAssetData); - expect(httpStub.callCount).toBe(2); - }); - test('fetches once when the same subscription is called', async () => { - const stub = sinon - .stub(HttpClient.prototype, 'getOrdersAsync') - .callsFake(async () => Promise.resolve({ records: [], total: 0, perPage: 0, page: 1 })); - stubs.push( - sinon - .stub(ordersChannelFactory, 'createWebSocketOrdersChannelAsync') - .callsFake(async () => Promise.resolve({ subscribe: NOOP, close: NOOP })), - ); - stubs.push(stub); - provider = new SRAWebsocketOrderProvider({ httpEndpoint, websocketEndpoint }, orderStore); - await provider.createSubscriptionForAssetPairAsync(makerAssetData, takerAssetData); - await provider.createSubscriptionForAssetPairAsync(makerAssetData, takerAssetData); - await provider.createSubscriptionForAssetPairAsync(makerAssetData, takerAssetData); - expect(stub.callCount).toBe(2); - }); - test('adds orders from the subscription', async () => { - const orders: APIOrder[] = []; - const stub = sinon.stub(HttpClient.prototype, 'getOrdersAsync').callsFake(async () => - Promise.resolve({ - records: orders, - total: orders.length, - perPage: 1, - page: 1, - }), - ); - stubs.push(stub); - let handler: OrdersChannelHandler | undefined; - const wsStub = sinon - .stub(ordersChannelFactory, 'createWebSocketOrdersChannelAsync') - .callsFake(async (_url, updateHandler) => { - handler = updateHandler; - return Promise.resolve({ subscribe: NOOP, close: NOOP }); - }); - stubs.push(wsStub); - provider = new SRAWebsocketOrderProvider({ httpEndpoint, websocketEndpoint }, orderStore); - await provider.createSubscriptionForAssetPairAsync(makerAssetData, takerAssetData); - expect(handler).not.toBe(undefined); - if (handler) { - const channel = ''; - const subscriptionOpts = {}; - orders.push(createOrder(makerAssetData, takerAssetData)); - handler.onUpdate(channel as any, subscriptionOpts as any, orders); - } - expect(stub.callCount).toBe(2); - expect(wsStub.callCount).toBe(1); - await utils.delayAsync(5); - const storedOrders = await orderStore.getOrderSetForAssetsAsync(makerAssetData, takerAssetData); - expect(storedOrders.size()).toBe(1); - }); - test('stores the orders', async () => { - stubs.push( - sinon.stub(HttpClient.prototype, 'getOrdersAsync').callsFake(async () => - Promise.resolve({ - records: [createOrder(makerAssetData, takerAssetData)], - total: 1, - perPage: 1, - page: 1, - }), - ), - ); - stubs.push( - sinon - .stub(ordersChannelFactory, 'createWebSocketOrdersChannelAsync') - .callsFake(async () => Promise.resolve({ subscribe: NOOP, close: NOOP })), - ); - provider = new SRAWebsocketOrderProvider({ httpEndpoint, websocketEndpoint }, orderStore); - await provider.createSubscriptionForAssetPairAsync(makerAssetData, takerAssetData); - const orders = await orderStore.getOrderSetForAssetsAsync(makerAssetData, takerAssetData); - expect(orders.size()).toBe(1); - }); - test('reconnects on channel close', async () => { - stubs.push( - sinon.stub(HttpClient.prototype, 'getOrdersAsync').callsFake(async () => - Promise.resolve({ - records: [], - total: 0, - perPage: 1, - page: 1, - }), - ), - ); - let handler: OrdersChannelHandler | undefined; - const wsStub = sinon - .stub(ordersChannelFactory, 'createWebSocketOrdersChannelAsync') - .callsFake(async (_url, updateHandler) => { - handler = updateHandler; - return Promise.resolve({ subscribe: NOOP, close: NOOP }); - }); - stubs.push(wsStub); - provider = new SRAWebsocketOrderProvider({ httpEndpoint, websocketEndpoint }, orderStore); - await provider.createSubscriptionForAssetPairAsync(makerAssetData, takerAssetData); - expect(handler).not.toBe(undefined); - (handler as OrdersChannelHandler).onClose(undefined as any); - await utils.delayAsync(5); - // Creates the new connection - expect(wsStub.callCount).toBe(2); - }); - }); -}); diff --git a/packages/orderbook/test/orderbook.test.ts b/packages/orderbook/test/orderbook.test.ts deleted file mode 100644 index 4f17374259..0000000000 --- a/packages/orderbook/test/orderbook.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { HttpClient } from '@0x/connect'; -import * as sinon from 'sinon'; - -import { Orderbook } from '../src'; - -import { createOrder } from './utils'; - -describe('Orderbook', () => { - const httpEndpoint = 'https://localhost'; - const makerAssetData = '0xf47261b000000000000000000000000089d24a6b4ccb1b6faa2625fe562bdd9a23260359'; - const takerAssetData = '0xf47261b0000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2'; - const stubs: sinon.SinonStub[] = []; - afterEach(() => { - stubs.forEach(s => s.restore()); - }); - describe('#getOrdersAsync', () => { - test('returns the orders stored', async () => { - const records = [createOrder(makerAssetData, takerAssetData)]; - stubs.push( - sinon.stub(HttpClient.prototype, 'getOrdersAsync').callsFake(async () => - Promise.resolve({ - records, - total: 1, - perPage: 1, - page: 1, - }), - ), - ); - const orderbook = Orderbook.getOrderbookForPollingProvider({ httpEndpoint, pollingIntervalMs: 5 }); - const orders = await orderbook.getOrdersAsync(makerAssetData, takerAssetData); - expect(orders.length).toBe(1); - }); - }); - describe('#addOrdersAsync', () => { - test('propagates the order rejection', async () => { - stubs.push( - sinon - .stub(HttpClient.prototype, 'getOrdersAsync') - .callsFake(async () => Promise.resolve({ records: [], total: 0, perPage: 0, page: 1 })), - ); - stubs.push( - sinon - .stub(HttpClient.prototype, 'submitOrderAsync') - .callsFake(async () => Promise.reject('INVALID_ORDER')), - ); - const orderbook = Orderbook.getOrderbookForPollingProvider({ httpEndpoint, pollingIntervalMs: 5 }); - const result = await orderbook.addOrdersAsync([createOrder(makerAssetData, takerAssetData).order]); - expect(result.rejected.length).toBe(1); - expect(result.accepted.length).toBe(0); - }); - test('propagates the order accepted', async () => { - stubs.push( - sinon - .stub(HttpClient.prototype, 'getOrdersAsync') - .callsFake(async () => Promise.resolve({ records: [], total: 0, perPage: 0, page: 1 })), - ); - stubs.push(sinon.stub(HttpClient.prototype, 'submitOrderAsync').callsFake(async () => Promise.resolve())); - const orderbook = Orderbook.getOrderbookForPollingProvider({ httpEndpoint, pollingIntervalMs: 5 }); - const result = await orderbook.addOrdersAsync([createOrder(makerAssetData, takerAssetData).order]); - expect(result.rejected.length).toBe(0); - expect(result.accepted.length).toBe(1); - }); - }); - describe('#getAvailableAssetDatasAsync', () => { - test('gets the available assets', async () => { - stubs.push( - sinon - .stub(HttpClient.prototype, 'getAssetPairsAsync') - .callsFake(async () => Promise.resolve({ records: [], total: 0, perPage: 0, page: 1 })), - ); - const orderbook = Orderbook.getOrderbookForPollingProvider({ httpEndpoint, pollingIntervalMs: 5 }); - const result = await orderbook.getAvailableAssetDatasAsync(); - expect(result.length).toBe(0); - }); - }); -}); diff --git a/packages/orderbook/test/utils.test.ts b/packages/orderbook/test/utils.test.ts deleted file mode 100644 index 565de836f3..0000000000 --- a/packages/orderbook/test/utils.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { utils } from '../src/utils'; - -describe('Utils', () => { - describe('.getOrderHash', () => { - const order = { - makerAddress: '0x50f84bbee6fb250d6f49e854fa280445369d64d9', - makerAssetData: '0xf47261b00000000000000000000000000f5d2fb29fb7d3cfee444a200298f468908cc942', - makerAssetAmount: '4424020538752105500000', - makerFee: '0', - takerAddress: '0x0000000000000000000000000000000000000000', - takerAssetData: '0xf47261b0000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', - takerAssetAmount: '1000000000000000061', - makerFeeAssetData: '0xf47261b00000000000000000000000000f5d2fb29fb7d3cfee444a200298f468908cc942', - takerFeeAssetData: '0xf47261b0000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', - takerFee: '0', - senderAddress: '0x0000000000000000000000000000000000000000', - exchangeAddress: '0x4f833a24e1f95d70f028921e27040ca56e09ab0b', - feeRecipientAddress: '0xa258b39954cef5cb142fd567a46cddb31a670124', - expirationTimeSeconds: '1559422407', - salt: '1559422141994', - chainId: 1, - signature: - '0x1cf16c2f3a210965b5e17f51b57b869ba4ddda33df92b0017b4d8da9dacd3152b122a73844eaf50ccde29a42950239ba36a525ed7f1698a8a5e1896cf7d651aed203', - }; - test('calculates the orderhash if it does not exist', async () => { - const orderHash = utils.getOrderHash(order as any); - const calculatedOrderHash = utils.getOrderHash({ order: order as any, metaData: {} }); - expect(orderHash).toBe(calculatedOrderHash); - expect(orderHash).toBe('0x5a0f346c671a39b832a487d2d7eb63ca19301554cf1f8a98a19d478a3a8be32c'); - }); - }); - describe('.attemptAsync', () => { - test('attempts the operation multiple times if the operation throws', async () => { - const success = 'Success'; - const mock = jest - .fn() - .mockRejectedValueOnce(new Error('Async Error')) - .mockResolvedValue(success); - const result = await utils.attemptAsync(mock); - expect(result).toBe(success); - expect(mock.mock.calls.length).toBe(2); - }); - }); -}); diff --git a/packages/orderbook/test/utils.ts b/packages/orderbook/test/utils.ts deleted file mode 100644 index 83164db182..0000000000 --- a/packages/orderbook/test/utils.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { APIOrder } from '@0x/connect'; -import { BigNumber } from '@0x/utils'; - -export const createOrder = (makerAssetData: string, takerAssetData: string): APIOrder => { - return { - order: { - makerAddress: '0x00', - takerAddress: '0x00', - makerAssetData, - takerAssetData, - makerFeeAssetData: makerAssetData, - takerFeeAssetData: takerAssetData, - chainId: 0, - exchangeAddress: '0x00', - senderAddress: '0x00', - makerAssetAmount: new BigNumber(1), - takerAssetAmount: new BigNumber(1), - feeRecipientAddress: '0x00', - makerFee: new BigNumber(0), - takerFee: new BigNumber(0), - salt: new BigNumber(0), - expirationTimeSeconds: new BigNumber(0), - signature: '0xsig', - }, - metaData: { - orderHash: '0x12345', - remainingFillableTakerAssetAmount: new BigNumber(1), - }, - }; -}; diff --git a/packages/orderbook/tsconfig.json b/packages/orderbook/tsconfig.json deleted file mode 100644 index a879178929..0000000000 --- a/packages/orderbook/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../tsconfig", - "compilerOptions": { - "outDir": "lib", - "rootDir": "." - }, - "include": ["src", "test"] -} diff --git a/packages/orderbook/tslint.json b/packages/orderbook/tslint.json deleted file mode 100644 index 1bb3ac2a22..0000000000 --- a/packages/orderbook/tslint.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "extends": ["@0x/tslint-config"], - "rules": { - "custom-no-magic-numbers": false - } -} diff --git a/packages/orderbook/typedoc-tsconfig.json b/packages/orderbook/typedoc-tsconfig.json deleted file mode 100644 index c9b0af1ae6..0000000000 --- a/packages/orderbook/typedoc-tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "../../typedoc-tsconfig", - "compilerOptions": { - "outDir": "lib" - }, - "include": ["./src/**/*", "./test/**/*"] -} diff --git a/packages/sol-compiler/.npmignore b/packages/sol-compiler/.npmignore deleted file mode 100644 index 8bf011e330..0000000000 --- a/packages/sol-compiler/.npmignore +++ /dev/null @@ -1,13 +0,0 @@ -# Blacklist all files -.* -* -# Whitelist lib -!lib/**/* -# Blacklist tests and publish scripts -/lib/test/* -/lib/monorepo_scripts/ -# Package specific ignore -!bin/**/* -!solc_bin/.gitkeep -lib/solc_bin/* -!lib/solc_bin/.gitkeep diff --git a/packages/sol-compiler/CHANGELOG.json b/packages/sol-compiler/CHANGELOG.json deleted file mode 100644 index d971e5e93d..0000000000 --- a/packages/sol-compiler/CHANGELOG.json +++ /dev/null @@ -1,829 +0,0 @@ -[ - { - "version": "4.2.0", - "changes": [ - { - "note": "Add solidity 0.7.x support", - "pr": 2710 - } - ] - }, - { - "timestamp": 1594788383, - "version": "4.1.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "4.1.0", - "changes": [ - { - "note": "Refactor + add solidity 0.6 support", - "pr": 2532 - }, - { - "note": "Filter `receive` functions from 0.6 ABIs", - "pr": 2540 - }, - { - "note": "Fix `CompilerOptions` schema", - "pr": 2591 - } - ], - "timestamp": 1592969527 - }, - { - "timestamp": 1582623685, - "version": "4.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1581204851, - "version": "4.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1580988106, - "version": "4.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1580811564, - "version": "4.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1579682890, - "version": "4.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "4.0.3", - "changes": [ - { - "note": "More tolerant of AST-only compilation targets", - "pr": 2391 - } - ], - "timestamp": 1578272714 - }, - { - "timestamp": 1576540892, - "version": "4.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1575931811, - "version": "4.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "4.0.0", - "changes": [ - { - "note": "Add `shouldSaveStandardInput` config", - "pr": 2322 - }, - { - "note": "Output artifacts now include a 'chains' attribute rather than 'networks'", - "pr": 2313 - }, - { - "note": "Convert `getContractNamesToCompile` to public function of `Compiler` class", - "pr": 2055 - } - ], - "timestamp": 1575296764 - }, - { - "version": "3.2.0-beta.4", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1575290197 - }, - { - "version": "3.2.0-beta.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1574238768 - }, - { - "version": "3.2.0-beta.2", - "changes": [ - { - "note": "Add `shouldSaveStandardInput` config", - "pr": 2322 - } - ], - "timestamp": 1574030254 - }, - { - "version": "3.2.0-beta.1", - "changes": [ - { - "note": "Output artifacts now include a 'chains' attribute rather than 'networks'", - "pr": 2313 - } - ], - "timestamp": 1573159180 - }, - { - "version": "3.2.0-beta.0", - "changes": [ - { - "note": "Convert `getContractNamesToCompile` to public function of `Compiler` class", - "pr": 2055 - } - ], - "timestamp": 1570135330 - }, - { - "timestamp": 1568744790, - "version": "3.1.15", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1567521715, - "version": "3.1.14", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1566446343, - "version": "3.1.13", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1565296576, - "version": "3.1.12", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1564604963, - "version": "3.1.11", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.1.10", - "changes": [ - { - "note": "re-export new ethereum-types types, TupleDataItem", - "pr": 1919 - } - ], - "timestamp": 1563957393 - }, - { - "timestamp": 1563006338, - "version": "3.1.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1558712885, - "version": "3.1.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1557507213, - "version": "3.1.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.1.6", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1554997931 - }, - { - "timestamp": 1553183790, - "version": "3.1.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1553091633, - "version": "3.1.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551479279, - "version": "3.1.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.1.2", - "changes": [ - { - "note": "Remove redundant log message", - "pr": 1652 - } - ], - "timestamp": 1551299797 - }, - { - "version": "3.1.1", - "changes": [ - { - "note": "Fix a bug when combining compilerSettings from different sources", - "pr": 1652 - } - ], - "timestamp": 1551220833 - }, - { - "version": "3.1.0", - "changes": [ - { - "note": "Add `isOfflineMode` flag to sol-compiler`", - "pr": 1625 - } - ], - "timestamp": 1551130135 - }, - { - "timestamp": 1549733923, - "version": "3.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.0.2", - "changes": [ - { - "note": "Fix a bug when smart recompilation wasn't working because of remappings", - "pr": 1575 - }, - { - "note": "Fix a bug that made `opts` required instead of optional", - "pr": 1596 - }, - { - "note": "Remove `bin_paths` and fetch the list of Solidity compilers from Github", - "pr": 1596 - }, - { - "note": "Fix a bug causing `ast` and `legacyAST` to not be added to the artifacts even when requested", - "pr": 1596 - } - ], - "timestamp": 1549547375 - }, - { - "timestamp": 1549452781, - "version": "3.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.0.0", - "changes": [ - { - "note": "Upgrade the bignumber.js to v8.0.2", - "pr": 1517 - } - ], - "timestamp": 1549373905 - }, - { - "timestamp": 1547561734, - "version": "2.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547225310, - "version": "2.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.0", - "changes": [ - { - "note": "Add sol-compiler watch mode with -w flag", - "pr": 1461 - }, - { - "note": "Make error and warning colouring more visually pleasant and consistent with other compilers", - "pr": 1461 - }, - { - "note": "Add newest solidity versions from 0.4.25 to 0.5.2", - "pr": 1496 - } - ], - "timestamp": 1547040760 - }, - { - "version": "1.1.16", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544739608 - }, - { - "version": "1.1.15", - "changes": [ - { - "note": "Fix bug where we were appending base path to absolute imports (e.g NPM imports)", - "pr": 1311 - } - ], - "timestamp": 1544570656 - }, - { - "timestamp": 1543401373, - "version": "1.1.14", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542821676, - "version": "1.1.13", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542208198, - "version": "1.1.12", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542134075, - "version": "1.1.11", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542028948, - "version": "1.1.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.1.9", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1541740904 - }, - { - "timestamp": 1539871071, - "version": "1.1.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.1.7", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1538693146 - }, - { - "timestamp": 1538157789, - "version": "1.1.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537907159, - "version": "1.1.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537875740, - "version": "1.1.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537541580, - "version": "1.1.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1536142250, - "version": "1.1.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1535377027, - "version": "1.1.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.1.0", - "changes": [ - { - "note": "Quicken compilation by sending multiple contracts to the same solcjs invocation, batching them together based on compiler version requirements.", - "pr": 965 - }, - { - "note": "Stop exporting types: `ContractArtifact`, `ContractNetworks`", - "pr": 924 - }, - { - "note": "Export types: `CompilerSettings`, `OutputField`", - "pr": 924 - } - ], - "timestamp": 1535133899 - }, - { - "timestamp": 1534210131, - "version": "1.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532619515, - "version": "1.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532614997, - "version": "1.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532605697, - "version": "1.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532357734, - "version": "1.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532043000, - "version": "1.0.0", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1531919263, - "version": "0.5.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1531149657, - "version": "0.5.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1529397769, - "version": "0.5.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.5.1", - "changes": [ - { - "note": "Make `opts` constructor parameter optional", - "pr": 621 - }, - { - "note": "Add schema validation for compiler configuration", - "pr": 621 - } - ], - "timestamp": 1527009133 - }, - { - "version": "0.5.0", - "changes": [ - { - "note": "Properly export the executable binary", - "pr": 588 - }, - { - "note": "Add the ability to define a specific solidity version", - "pr": 589 - } - ], - "timestamp": 1527009133 - }, - { - "timestamp": 1525477860, - "version": "0.4.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.4.2", - "changes": [ - { - "note": "Add support for solidity 0.4.23", - "pr": 545 - } - ], - "timestamp": 1525428773 - }, - { - "version": "0.4.1", - "changes": [ - { - "note": "Add support for solidity 0.4.22", - "pr": 531 - } - ], - "timestamp": 1524044013 - }, - { - "version": "0.4.0", - "changes": [ - { - "note": "Changed the config key `web3Provider` to `provider` to be consistent with other tools", - "pr": 501 - } - ], - "timestamp": 1523462196 - }, - { - "version": "0.3.5", - "changes": [ - { - "note": "Don't try to write contract artifact if an error occured", - "pr": 485 - } - ], - "timestamp": 1522673609 - }, - { - "version": "0.3.4", - "changes": [ - { - "note": "Create solc_bin directory if does not exist before attempting to compile", - "pr": 491 - } - ], - "timestamp": 1522658513 - }, - { - "version": "0.3.1", - "changes": [ - { - "note": "Add TS types for `yargs`" - } - ], - "timestamp": 1521298800 - }, - { - "version": "0.3.0", - "changes": [ - { - "note": "Add support for Solidity 0.4.20 and 0.4.21" - }, - { - "note": "Replace `jsonrpcPort` config with `jsonrpcUrl`", - "pr": 426 - }, - { - "note": "Replace `jsonrpc-port` CLI option with `jsonrpc-url`", - "pr": 426 - }, - { - "note": "Export the `Compiler`", - "pr": 426 - }, - { - "note": "Load solc from remote source instead of having it locally", - "pr": 426 - }, - { - "note": "Add `bytecode`, `runtime_bytecode`, `source_map`, `source_map_runtime` and `sources` fields to artifacts", - "pr": 426 - }, - { - "note": "Remove 0x-specific `migrate` command", - "pr": 426 - }, - { - "note": "Allow deployer to accept a provider instead of port and host. This makes it possible to run it with in-process ganache-core", - "pr": 426 - }, - { - "note": "Consolidate all `console.log` calls into `logUtils` in the `@0xproject/utils` package", - "pr": 452 - }, - { - "note": "Add `#!/usr/bin/env node` pragma above `cli.ts` script to fix command-line error." - } - ], - "timestamp": 1521298800 - }, - { - "version": "0.2.0", - "changes": [ - { - "note": "Check dependencies when determining if contracts should be recompiled", - "pr": 408 - }, - { - "note": "Improve an error message for when deployer is supplied with an incorrect number of constructor arguments", - "pr": 419 - } - ], - "timestamp": 1520089200 - }, - { - "version": "0.1.0", - "changes": [ - { - "note": "Add the ability to pass in specific contracts to compile in CLI", - "pr": 400 - } - ], - "timestamp": 1518706800 - }, - { - "version": "0.0.8", - "changes": [ - { - "note": "Fix publishing issue where .npmignore was not properly excluding undesired content", - "pr": 389 - } - ], - "timestamp": 1518102000 - } -] diff --git a/packages/sol-compiler/CHANGELOG.md b/packages/sol-compiler/CHANGELOG.md deleted file mode 100644 index 0c3934eefc..0000000000 --- a/packages/sol-compiler/CHANGELOG.md +++ /dev/null @@ -1,341 +0,0 @@ - - -CHANGELOG - -## v4.1.1 - _July 15, 2020_ - - * Dependencies updated - -## v4.1.0 - _June 24, 2020_ - - * Refactor + add solidity 0.6 support (#2532) - * Filter `receive` functions from 0.6 ABIs (#2540) - * Fix `CompilerOptions` schema (#2591) - -## v4.0.8 - _February 25, 2020_ - - * Dependencies updated - -## v4.0.7 - _February 8, 2020_ - - * Dependencies updated - -## v4.0.6 - _February 6, 2020_ - - * Dependencies updated - -## v4.0.5 - _February 4, 2020_ - - * Dependencies updated - -## v4.0.4 - _January 22, 2020_ - - * Dependencies updated - -## v4.0.3 - _January 6, 2020_ - - * More tolerant of AST-only compilation targets (#2391) - -## v4.0.2 - _December 17, 2019_ - - * Dependencies updated - -## v4.0.1 - _December 9, 2019_ - - * Dependencies updated - -## v4.0.0 - _December 2, 2019_ - - * Add `shouldSaveStandardInput` config (#2322) - * Output artifacts now include a 'chains' attribute rather than 'networks' (#2313) - * Convert `getContractNamesToCompile` to public function of `Compiler` class (#2055) - -## v3.2.0-beta.4 - _December 2, 2019_ - - * Dependencies updated - -## v3.2.0-beta.3 - _November 20, 2019_ - - * Dependencies updated - -## v3.2.0-beta.2 - _November 17, 2019_ - - * Add `shouldSaveStandardInput` config (#2322) - -## v3.2.0-beta.1 - _November 7, 2019_ - - * Output artifacts now include a 'chains' attribute rather than 'networks' (#2313) - -## v3.2.0-beta.0 - _October 3, 2019_ - - * Convert `getContractNamesToCompile` to public function of `Compiler` class (#2055) - -## v3.1.15 - _September 17, 2019_ - - * Dependencies updated - -## v3.1.14 - _September 3, 2019_ - - * Dependencies updated - -## v3.1.13 - _August 22, 2019_ - - * Dependencies updated - -## v3.1.12 - _August 8, 2019_ - - * Dependencies updated - -## v3.1.11 - _July 31, 2019_ - - * Dependencies updated - -## v3.1.10 - _July 24, 2019_ - - * re-export new ethereum-types types, TupleDataItem (#1919) - -## v3.1.9 - _July 13, 2019_ - - * Dependencies updated - -## v3.1.8 - _May 24, 2019_ - - * Dependencies updated - -## v3.1.7 - _May 10, 2019_ - - * Dependencies updated - -## v3.1.6 - _April 11, 2019_ - - * Dependencies updated - -## v3.1.5 - _March 21, 2019_ - - * Dependencies updated - -## v3.1.4 - _March 20, 2019_ - - * Dependencies updated - -## v3.1.3 - _March 1, 2019_ - - * Dependencies updated - -## v3.1.2 - _February 27, 2019_ - - * Remove redundant log message (#1652) - -## v3.1.1 - _February 26, 2019_ - - * Fix a bug when combining compilerSettings from different sources (#1652) - -## v3.1.0 - _February 25, 2019_ - - * Add `isOfflineMode` flag to sol-compiler` (#1625) - -## v3.0.3 - _February 9, 2019_ - - * Dependencies updated - -## v3.0.2 - _February 7, 2019_ - - * Fix a bug when smart recompilation wasn't working because of remappings (#1575) - * Fix a bug that made `opts` required instead of optional (#1596) - * Remove `bin_paths` and fetch the list of Solidity compilers from Github (#1596) - * Fix a bug causing `ast` and `legacyAST` to not be added to the artifacts even when requested (#1596) - -## v3.0.1 - _February 6, 2019_ - - * Dependencies updated - -## v3.0.0 - _February 5, 2019_ - - * Upgrade the bignumber.js to v8.0.2 (#1517) - -## v2.0.2 - _January 15, 2019_ - - * Dependencies updated - -## v2.0.1 - _January 11, 2019_ - - * Dependencies updated - -## v2.0.0 - _January 9, 2019_ - - * Add sol-compiler watch mode with -w flag (#1461) - * Make error and warning colouring more visually pleasant and consistent with other compilers (#1461) - * Add newest solidity versions from 0.4.25 to 0.5.2 (#1496) - -## v1.1.16 - _December 13, 2018_ - - * Dependencies updated - -## v1.1.15 - _December 11, 2018_ - - * Fix bug where we were appending base path to absolute imports (e.g NPM imports) (#1311) - -## v1.1.14 - _November 28, 2018_ - - * Dependencies updated - -## v1.1.13 - _November 21, 2018_ - - * Dependencies updated - -## v1.1.12 - _November 14, 2018_ - - * Dependencies updated - -## v1.1.11 - _November 13, 2018_ - - * Dependencies updated - -## v1.1.10 - _November 12, 2018_ - - * Dependencies updated - -## v1.1.9 - _November 9, 2018_ - - * Dependencies updated - -## v1.1.8 - _October 18, 2018_ - - * Dependencies updated - -## v1.1.7 - _October 4, 2018_ - - * Dependencies updated - -## v1.1.6 - _September 28, 2018_ - - * Dependencies updated - -## v1.1.5 - _September 25, 2018_ - - * Dependencies updated - -## v1.1.4 - _September 25, 2018_ - - * Dependencies updated - -## v1.1.3 - _September 21, 2018_ - - * Dependencies updated - -## v1.1.2 - _September 5, 2018_ - - * Dependencies updated - -## v1.1.1 - _August 27, 2018_ - - * Dependencies updated - -## v1.1.0 - _August 24, 2018_ - - * Quicken compilation by sending multiple contracts to the same solcjs invocation, batching them together based on compiler version requirements. (#965) - * Stop exporting types: `ContractArtifact`, `ContractNetworks` (#924) - * Export types: `CompilerSettings`, `OutputField` (#924) - -## v1.0.5 - _August 14, 2018_ - - * Dependencies updated - -## v1.0.4 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.3 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.2 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.1 - _July 23, 2018_ - - * Dependencies updated - -## v1.0.0 - _July 19, 2018_ - - * Dependencies updated - -## v0.5.4 - _July 18, 2018_ - - * Dependencies updated - -## v0.5.3 - _July 9, 2018_ - - * Dependencies updated - -## v0.5.2 - _June 19, 2018_ - - * Dependencies updated - -## v0.5.1 - _May 22, 2018_ - - * Make `opts` constructor parameter optional (#621) - * Add schema validation for compiler configuration (#621) - -## v0.5.0 - _May 22, 2018_ - - * Properly export the executable binary (#588) - * Add the ability to define a specific solidity version (#589) - -## v0.4.3 - _May 4, 2018_ - - * Dependencies updated - -## v0.4.2 - _May 4, 2018_ - - * Add support for solidity 0.4.23 (#545) - -## v0.4.1 - _April 18, 2018_ - - * Add support for solidity 0.4.22 (#531) - -## v0.4.0 - _April 11, 2018_ - - * Changed the config key `web3Provider` to `provider` to be consistent with other tools (#501) - -## v0.3.5 - _April 2, 2018_ - - * Don't try to write contract artifact if an error occured (#485) - -## v0.3.4 - _April 2, 2018_ - - * Create solc_bin directory if does not exist before attempting to compile (#491) - -## v0.3.1 - _March 17, 2018_ - - * Add TS types for `yargs` - -## v0.3.0 - _March 17, 2018_ - - * Add support for Solidity 0.4.20 and 0.4.21 - * Replace `jsonrpcPort` config with `jsonrpcUrl` (#426) - * Replace `jsonrpc-port` CLI option with `jsonrpc-url` (#426) - * Export the `Compiler` (#426) - * Load solc from remote source instead of having it locally (#426) - * Add `bytecode`, `runtime_bytecode`, `source_map`, `source_map_runtime` and `sources` fields to artifacts (#426) - * Remove 0x-specific `migrate` command (#426) - * Allow deployer to accept a provider instead of port and host. This makes it possible to run it with in-process ganache-core (#426) - * Consolidate all `console.log` calls into `logUtils` in the `@0xproject/utils` package (#452) - * Add `#!/usr/bin/env node` pragma above `cli.ts` script to fix command-line error. - -## v0.2.0 - _March 3, 2018_ - - * Check dependencies when determining if contracts should be recompiled (#408) - * Improve an error message for when deployer is supplied with an incorrect number of constructor arguments (#419) - -## v0.1.0 - _February 15, 2018_ - - * Add the ability to pass in specific contracts to compile in CLI (#400) - -## v0.0.8 - _February 8, 2018_ - - * Fix publishing issue where .npmignore was not properly excluding undesired content (#389) diff --git a/packages/sol-compiler/README.md b/packages/sol-compiler/README.md deleted file mode 100644 index c8e837a3ab..0000000000 --- a/packages/sol-compiler/README.md +++ /dev/null @@ -1,97 +0,0 @@ -## @0x/sol-compiler - -Sol-compiler is a wrapper around [solc-js](https://www.npmjs.com/package/solc) that adds: - -- Smart re-compilation: Only recompiles when smart contracts have changed -- Ability to compile an entire project instead of only individual `.sol` files -- Compilation using the Solidity version specified at the top of each individual `.sol` file -- Proper parsing of Solidity version ranges -- Support for the standard [input description](https://solidity.readthedocs.io/en/develop/using-the-compiler.html#input-description) for what information you'd like added to the resulting `artifacts` file (i.e 100% configurable artifacts content). - -### Read the [Documentation](https://0x.org/docs/tools/sol-compiler). - -## Installation - -#### CLI Installation - -```bash -yarn global add @0x/sol-compiler -``` - -#### API Installation - -```bash -yarn add @0x/sol-compiler -``` - -If your project is in [TypeScript](https://www.typescriptlang.org/), add the following to your `tsconfig.json`: - -```json -"compilerOptions": { - "typeRoots": ["node_modules/@0x/typescript-typings/types", "node_modules/@types"], -} -``` - -**Import** - -```typescript -import { Compiler } from '@0x/sol-compiler'; -``` - -or - -```javascript -var Compiler = require('@0x/sol-compiler').Compiler; -``` - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install dependencies - -If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: - -```bash -yarn config set workspaces-experimental true -``` - -Then install dependencies - -```bash -yarn install -``` - -### Build - -To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory: - -```bash -PKG=@0x/sol-compiler yarn build -``` - -Or continuously rebuild on change: - -```bash -PKG=@0x/sol-compiler yarn watch -``` - -### Clean - -```bash -yarn clean -``` - -### Lint - -```bash -yarn lint -``` - -### Run Tests - -```bash -yarn test -``` diff --git a/packages/sol-compiler/bin/sol-compiler.js b/packages/sol-compiler/bin/sol-compiler.js deleted file mode 100755 index 0e5b69af0e..0000000000 --- a/packages/sol-compiler/bin/sol-compiler.js +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/env node -require('../lib/src/cli.js') diff --git a/packages/sol-compiler/coverage/.gitkeep b/packages/sol-compiler/coverage/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/sol-compiler/docs/reference.mdx b/packages/sol-compiler/docs/reference.mdx deleted file mode 100644 index e8a35867b9..0000000000 --- a/packages/sol-compiler/docs/reference.mdx +++ /dev/null @@ -1,957 +0,0 @@ - - - - - - - - - - - - -
- - - - - - - - - - - - - -# Interface: CompilerOptions - -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. -useDockerisedSolc: If set to true - sol-compiler will try calling a dockerized installations of solc to achieve faster compilation times. Otherwise and by default - solcjs will be used. Defaults to false. -isOfflineMode: If set to true - sol-compiler will not fetch the list of solc releases from github. It will use the hardcoded list. Defaults to false. -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. -shouldSaveStandardInput: Write the standard JSON input in ${contractsDir}/${contractName}.input.json - - -## Properties - -### `Optional` artifactsDir - -• **artifactsDir**? : *undefined | string* - -*Defined in [ethereum-types/src/index.ts:733](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L733)* - -___ - -### `Optional` compilerSettings - -• **compilerSettings**? : *[CompilerSettings](#class-compilersettings)* - -*Defined in [ethereum-types/src/index.ts:734](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L734)* - -___ - -### `Optional` contracts - -• **contracts**? : *string[] | "*"* - -*Defined in [ethereum-types/src/index.ts:735](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L735)* - -___ - -### `Optional` contractsDir - -• **contractsDir**? : *undefined | string* - -*Defined in [ethereum-types/src/index.ts:732](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L732)* - -___ - -### `Optional` isOfflineMode - -• **isOfflineMode**? : *undefined | false | true* - -*Defined in [ethereum-types/src/index.ts:737](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L737)* - -___ - -### `Optional` shouldSaveStandardInput - -• **shouldSaveStandardInput**? : *undefined | false | true* - -*Defined in [ethereum-types/src/index.ts:739](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L739)* - -___ - -### `Optional` solcVersion - -• **solcVersion**? : *undefined | string* - -*Defined in [ethereum-types/src/index.ts:738](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L738)* - -___ - -### `Optional` useDockerisedSolc - -• **useDockerisedSolc**? : *undefined | false | true* - -*Defined in [ethereum-types/src/index.ts:736](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L736)* - -
- - - -# Interface: CompilerSettings - - -## Properties - -### `Optional` evmVersion - -• **evmVersion**? : *"homestead" | "tangerineWhistle" | "spuriousDragon" | "byzantium" | "constantinople"* - -*Defined in [ethereum-types/src/index.ts:690](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L690)* - -___ - -### `Optional` libraries - -• **libraries**? : *undefined | object* - -*Defined in [ethereum-types/src/index.ts:692](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L692)* - -___ - -### `Optional` metadata - -• **metadata**? : *[CompilerSettingsMetadata](#class-compilersettingsmetadata)* - -*Defined in [ethereum-types/src/index.ts:691](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L691)* - -___ - -### `Optional` optimizer - -• **optimizer**? : *[OptimizerSettings](#class-optimizersettings)* - -*Defined in [ethereum-types/src/index.ts:689](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L689)* - -___ - -### outputSelection - -• **outputSelection**: *object* - -*Defined in [ethereum-types/src/index.ts:697](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L697)* - -#### Type declaration: - -● \[▪ **fileName**: *string*\]: object - -● \[▪ **contractName**: *string*\]: [OutputField](#outputfield)[] - -___ - -### `Optional` remappings - -• **remappings**? : *string[]* - -*Defined in [ethereum-types/src/index.ts:688](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L688)* - -
- -# Interface: CompilerSettingsMetadata - - -## Properties - -### useLiteralContent - -• **useLiteralContent**: *true* - -*Defined in [ethereum-types/src/index.ts:705](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L705)* - -
- -# Interface: ConstructorAbi - - -## Properties - -### inputs - -• **inputs**: *[DataItem](#class-dataitem)[]* - -*Defined in [ethereum-types/src/index.ts:103](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L103)* - -___ - -### payable - -• **payable**: *boolean* - -*Defined in [ethereum-types/src/index.ts:104](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L104)* - -___ - -### stateMutability - -• **stateMutability**: *[ConstructorStateMutability](#constructorstatemutability)* - -*Defined in [ethereum-types/src/index.ts:105](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L105)* - -___ - -### type - -• **type**: *string* - -*Defined in [ethereum-types/src/index.ts:102](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L102)* - -
- - - - - - - -# Interface: DataItem - - -## Properties - -### `Optional` components - -• **components**? : *[DataItem](#class-dataitem)[]* - -*Defined in [ethereum-types/src/index.ts:138](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L138)* - -___ - -### `Optional` internalType - -• **internalType**? : *undefined | string* - -*Defined in [ethereum-types/src/index.ts:137](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L137)* - -___ - -### name - -• **name**: *string* - -*Defined in [ethereum-types/src/index.ts:135](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L135)* - -___ - -### type - -• **type**: *string* - -*Defined in [ethereum-types/src/index.ts:136](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L136)* - -
- - - - - -# Interface: DevdocOutput - - -## Properties - -### `Optional` author - -• **author**? : *undefined | string* - -*Defined in [ethereum-types/src/index.ts:629](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L629)* - -___ - -### methods - -• **methods**: *object* - -*Defined in [ethereum-types/src/index.ts:630](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L630)* - -#### Type declaration: - -● \[▪ **signature**: *string*\]: object - -___ - -### `Optional` title - -• **title**? : *undefined | string* - -*Defined in [ethereum-types/src/index.ts:628](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L628)* - -
- - - -# Interface: EventAbi - - -## Properties - -### anonymous - -• **anonymous**: *boolean* - -*Defined in [ethereum-types/src/index.ts:131](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L131)* - -___ - -### inputs - -• **inputs**: *[EventParameter](#class-eventparameter)[]* - -*Defined in [ethereum-types/src/index.ts:130](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L130)* - -___ - -### name - -• **name**: *string* - -*Defined in [ethereum-types/src/index.ts:129](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L129)* - -___ - -### type - -• **type**: *string* - -*Defined in [ethereum-types/src/index.ts:128](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L128)* - -
- -# Interface: EventParameter - - -## Properties - -### `Optional` components - -• **components**? : *[DataItem](#class-dataitem)[]* - -*Inherited from [DataItem](#interface-dataitem).[components](#optional-components)* - -*Defined in [ethereum-types/src/index.ts:138](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L138)* - -___ - -### indexed - -• **indexed**: *boolean* - -*Defined in [ethereum-types/src/index.ts:116](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L116)* - -___ - -### `Optional` internalType - -• **internalType**? : *undefined | string* - -*Inherited from [DataItem](#interface-dataitem).[internalType](#optional-internaltype)* - -*Defined in [ethereum-types/src/index.ts:137](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L137)* - -___ - -### name - -• **name**: *string* - -*Inherited from [DataItem](#interface-dataitem).[name](#name)* - -*Defined in [ethereum-types/src/index.ts:135](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L135)* - -___ - -### type - -• **type**: *string* - -*Inherited from [DataItem](#interface-dataitem).[type](#type)* - -*Defined in [ethereum-types/src/index.ts:136](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L136)* - -
- -# Interface: EvmBytecodeOutput - - -## Properties - -### object - -• **object**: *string* - -*Defined in [ethereum-types/src/index.ts:623](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L623)* - -___ - -### sourceMap - -• **sourceMap**: *string* - -*Defined in [ethereum-types/src/index.ts:624](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L624)* - -
- -# Interface: EvmOutput - - -## Properties - -### bytecode - -• **bytecode**: *[EvmBytecodeOutput](#class-evmbytecodeoutput)* - -*Defined in [ethereum-types/src/index.ts:618](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L618)* - -___ - -### deployedBytecode - -• **deployedBytecode**: *[EvmBytecodeOutput](#class-evmbytecodeoutput)* - -*Defined in [ethereum-types/src/index.ts:619](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L619)* - -
- -# Interface: FallbackAbi - - -## Properties - -### payable - -• **payable**: *boolean* - -*Defined in [ethereum-types/src/index.ts:112](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L112)* - -___ - -### type - -• **type**: *string* - -*Defined in [ethereum-types/src/index.ts:111](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L111)* - -
- - - -# Class: Compiler - -The Compiler facilitates compiling Solidity smart contracts and saves the results -to artifact files. - - -## Constructors - - - -\+ **new Compiler**(`opts?`: [CompilerOptions](#interface-compileroptions)): *[Compiler](#class-compiler)* - -*Defined in [sol-compiler/src/compiler.ts:100](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-compiler/src/compiler.ts#L100)* - -Instantiates a new instance of the Compiler class. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`opts?` | [CompilerOptions](#interface-compileroptions) | Optional compiler options | - -**Returns:** *[Compiler](#class-compiler)* - -An instance of the Compiler class. - -## Methods - -### compileAsync - -▸ **compileAsync**(): *`Promise`* - -*Defined in [sol-compiler/src/compiler.ts:143](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-compiler/src/compiler.ts#L143)* - -Compiles selected Solidity files found in `contractsDir` and writes JSON artifacts to `artifactsDir`. - -**Returns:** *`Promise`* - -___ - -### getCompilerOutputsAsync - -▸ **getCompilerOutputsAsync**(): *`Promise`* - -*Defined in [sol-compiler/src/compiler.ts:156](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-compiler/src/compiler.ts#L156)* - -Compiles Solidity files specified during instantiation, and returns the -compiler output given by solc. Return value is an array of outputs: -Solidity modules are batched together by version required, and each -element of the returned array corresponds to a compiler version, and -each element contains the output for all of the modules compiled with -that version. - -**Returns:** *`Promise`* - -___ - -### getContractNamesToCompile - -▸ **getContractNamesToCompile**(): *string[]* - -*Defined in [sol-compiler/src/compiler.ts:197](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-compiler/src/compiler.ts#L197)* - -Gets a list of contracts to compile. - -**Returns:** *string[]* - -___ - -### watchAsync - -▸ **watchAsync**(): *`Promise`* - -*Defined in [sol-compiler/src/compiler.ts:160](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-compiler/src/compiler.ts#L160)* - -**Returns:** *`Promise`* - -
- - - - - - - - - - - - - - - -# Interface: MethodAbi - - -## Properties - -### constant - -• **constant**: *boolean* - -*Defined in [ethereum-types/src/index.ts:94](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L94)* - -___ - -### inputs - -• **inputs**: *[DataItem](#class-dataitem)[]* - -*Defined in [ethereum-types/src/index.ts:92](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L92)* - -___ - -### name - -• **name**: *string* - -*Defined in [ethereum-types/src/index.ts:91](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L91)* - -___ - -### outputs - -• **outputs**: *[DataItem](#class-dataitem)[]* - -*Defined in [ethereum-types/src/index.ts:93](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L93)* - -___ - -### payable - -• **payable**: *boolean* - -*Defined in [ethereum-types/src/index.ts:96](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L96)* - -___ - -### stateMutability - -• **stateMutability**: *[StateMutability](#statemutability)* - -*Defined in [ethereum-types/src/index.ts:95](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L95)* - -___ - -### type - -• **type**: *string* - -*Defined in [ethereum-types/src/index.ts:90](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L90)* - -
- -# Interface: OptimizerSettings - - -## Properties - -### enabled - -• **enabled**: *boolean* - -*Defined in [ethereum-types/src/index.ts:709](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L709)* - -___ - -### `Optional` runs - -• **runs**? : *undefined | number* - -*Defined in [ethereum-types/src/index.ts:710](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L710)* - -
- - - - - -# Interface: RevertErrorAbi - - -## Properties - -### `Optional` arguments - -• **arguments**? : *[DataItem](#class-dataitem)[]* - -*Defined in [ethereum-types/src/index.ts:122](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L122)* - -___ - -### name - -• **name**: *string* - -*Defined in [ethereum-types/src/index.ts:121](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L121)* - -___ - -### type - -• **type**: *"error"* - -*Defined in [ethereum-types/src/index.ts:120](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L120)* - -
- -# Interface: SolcError - - -## Properties - -### component - -• **component**: *"general" | "ewasm"* - -*Defined in [ethereum-types/src/index.ts:605](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L605)* - -___ - -### `Optional` formattedMessage - -• **formattedMessage**? : *undefined | string* - -*Defined in [ethereum-types/src/index.ts:608](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L608)* - -___ - -### message - -• **message**: *string* - -*Defined in [ethereum-types/src/index.ts:607](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L607)* - -___ - -### severity - -• **severity**: *[ErrorSeverity](#errorseverity)* - -*Defined in [ethereum-types/src/index.ts:606](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L606)* - -___ - -### `Optional` sourceLocation - -• **sourceLocation**? : *[SourceLocation](#class-sourcelocation)* - -*Defined in [ethereum-types/src/index.ts:603](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L603)* - -___ - -### type - -• **type**: *[ErrorType](#errortype)* - -*Defined in [ethereum-types/src/index.ts:604](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L604)* - -
- - - - - -# Interface: StandardContractOutput - - -## Properties - -### abi - -• **abi**: *[ContractAbi](#contractabi)* - -*Defined in [ethereum-types/src/index.ts:565](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L565)* - -___ - -### `Optional` devdoc - -• **devdoc**? : *[DevdocOutput](#class-devdocoutput)* - -*Defined in [ethereum-types/src/index.ts:567](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L567)* - -___ - -### evm - -• **evm**: *[EvmOutput](#class-evmoutput)* - -*Defined in [ethereum-types/src/index.ts:566](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L566)* - -
- -# Interface: StandardOutput - - -## Properties - -### contracts - -• **contracts**: *object* - -*Defined in [ethereum-types/src/index.ts:579](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L579)* - -#### Type declaration: - -● \[▪ **fileName**: *string*\]: object - -● \[▪ **contractName**: *string*\]: [StandardContractOutput](#class-standardcontractoutput) - -___ - -### errors - -• **errors**: *[SolcError](#class-solcerror)[]* - -*Defined in [ethereum-types/src/index.ts:571](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L571)* - -___ - -### sources - -• **sources**: *object* - -*Defined in [ethereum-types/src/index.ts:572](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L572)* - -#### Type declaration: - -● \[▪ **fileName**: *string*\]: object - -
- - - - - - - - - - - - - -# Interface: TupleDataItem - - -## Properties - -### components - -• **components**: *[DataItem](#class-dataitem)[]* - -*Overrides [DataItem](_ethereum_types_src_index_.dataitem.md).[components](#optional-components)* - -*Defined in [ethereum-types/src/index.ts:142](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L142)* - -___ - -### `Optional` internalType - -• **internalType**? : *undefined | string* - -*Inherited from [DataItem](#interface-dataitem).[internalType](#optional-internaltype)* - -*Defined in [ethereum-types/src/index.ts:137](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L137)* - -___ - -### name - -• **name**: *string* - -*Inherited from [DataItem](#interface-dataitem).[name](#name)* - -*Defined in [ethereum-types/src/index.ts:135](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L135)* - -___ - -### type - -• **type**: *string* - -*Inherited from [DataItem](#interface-dataitem).[type](#type)* - -*Defined in [ethereum-types/src/index.ts:136](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L136)* - -
- - - - - - - - - - - - - - - - -## Type aliases - -### AbiDefinition - -Ƭ **AbiDefinition**: *[FunctionAbi](_ethereum_types_src_index_.md#functionabi) | [EventAbi](#interface-eventabi) | [RevertErrorAbi](#interface-reverterrorabi)* - -*Defined in [ethereum-types/src/index.ts:80](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L80)* - -___ - - - -### ConstructorStateMutability - -Ƭ **ConstructorStateMutability**: *"nonpayable" | "payable"* - -*Defined in [ethereum-types/src/index.ts:84](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L84)* - -___ - -### ContractAbi - -Ƭ **ContractAbi**: *[AbiDefinition](#abidefinition)[]* - -*Defined in [ethereum-types/src/index.ts:78](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L78)* - -___ - - - - - - - -### ErrorSeverity - -Ƭ **ErrorSeverity**: *"error" | "warning"* - -*Defined in [ethereum-types/src/index.ts:600](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L600)* - -___ - -### ErrorType - -Ƭ **ErrorType**: *"JSONError" | "IOError" | "ParserError" | "DocstringParsingError" | "SyntaxError" | "DeclarationError" | "TypeError" | "UnimplementedFeatureError" | "InternalCompilerError" | "Exception" | "CompilerError" | "FatalError" | "Warning"* - -*Defined in [ethereum-types/src/index.ts:586](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L586)* - -___ - -### FunctionAbi - -Ƭ **FunctionAbi**: *[MethodAbi](#interface-methodabi) | [ConstructorAbi](#interface-constructorabi) | [FallbackAbi](#interface-fallbackabi)* - -*Defined in [ethereum-types/src/index.ts:82](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L82)* - -___ - - - - - -### OutputField - -Ƭ **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"* - -*Defined in [ethereum-types/src/index.ts:526](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L526)* - -___ - -### ParamDescription - -Ƭ **ParamDescription**: *string* - -*Defined in [ethereum-types/src/index.ts:562](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L562)* - -___ - - - -### StateMutability - -Ƭ **StateMutability**: *"pure" | "view" | [ConstructorStateMutability](#constructorstatemutability)* - -*Defined in [ethereum-types/src/index.ts:85](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L85)* - -___ - - - - - - - - - diff --git a/packages/sol-compiler/package.json b/packages/sol-compiler/package.json deleted file mode 100644 index 0b7905d65b..0000000000 --- a/packages/sol-compiler/package.json +++ /dev/null @@ -1,103 +0,0 @@ -{ - "name": "@0x/sol-compiler", - "version": "4.1.1", - "engines": { - "node": ">=6.12" - }, - "description": "Solidity compiler wrapper and artifactor", - "main": "lib/src/index.js", - "types": "lib/src/index.d.ts", - "scripts": { - "build": "yarn pre_build && tsc -b", - "build:ci": "yarn build", - "pre_build": "run-s update_contract_fixtures", - "update_contract_fixtures": "copyfiles 'test/fixtures/contracts/**/*' ./lib", - "test": "yarn run_mocha", - "rebuild_and_test": "run-s build test", - "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 generated_docs", - "migrate": "npm run build; node lib/src/cli.js migrate", - "lint": "tslint --format stylish --project .", - "fix": "tslint --fix --format stylish --project .", - "test:circleci": "yarn test:coverage", - "diff_docs": "git diff --exit-code ./docs", - "s3:sync_md_docs": "aws s3 sync ./docs s3://docs-markdown/${npm_package_name}/v${npm_package_version} --profile 0xproject --region us-east-1 --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers", - "docs:md": "ts-doc-gen --sourceDir='$PROJECT_FILES' --output=$MD_FILE_DIR --fileExtension=mdx --tsconfig=./typedoc-tsconfig.json", - "docs:json": "typedoc --excludePrivate --excludeExternals --excludeProtected --ignoreCompilerErrors --target ES5 --tsconfig typedoc-tsconfig.json --json $JSON_FILE_PATH $PROJECT_FILES" - }, - "config": { - "postpublish": { - "assets": [] - } - }, - "bin": { - "sol-compiler": "bin/sol-compiler.js" - }, - "repository": { - "type": "git", - "url": "https://github.com/0xProject/0x-monorepo.git" - }, - "author": "Amir Bandeali", - "license": "Apache-2.0", - "bugs": { - "url": "https://github.com/0xProject/0x-monorepo/issues" - }, - "homepage": "https://github.com/0xProject/0x-monorepo/packages/sol-compiler/README.md", - "devDependencies": { - "@0x/dev-utils": "^3.3.0", - "@0x/ts-doc-gen": "^0.0.22", - "@0x/tslint-config": "^4.1.0", - "@types/mkdirp": "^0.5.2", - "@types/mocha": "^5.2.7", - "@types/pluralize": "^0.0.29", - "@types/require-from-string": "^1.2.0", - "@types/semver": "5.5.0", - "@types/web3-provider-engine": "^14.0.0", - "chai": "^4.0.1", - "chai-as-promised": "^7.1.0", - "chai-bignumber": "^3.0.0", - "copyfiles": "^2.0.0", - "dirty-chai": "^2.0.1", - "make-promises-safe": "^1.1.0", - "mocha": "^6.2.0", - "npm-run-all": "^4.1.2", - "nyc": "^11.0.1", - "shx": "^0.2.2", - "tslint": "5.11.0", - "typedoc": "^0.15.0", - "types-bn": "^0.0.1", - "typescript": "3.0.1", - "web3-provider-engine": "14.0.6", - "web3-typescript-typings": "^0.10.2", - "zeppelin-solidity": "1.8.0" - }, - "dependencies": { - "@0x/assert": "^3.0.9", - "@0x/json-schemas": "^5.1.0", - "@0x/sol-resolver": "^3.1.0", - "@0x/types": "^3.2.0", - "@0x/typescript-typings": "^5.1.1", - "@0x/utils": "^5.5.1", - "@0x/web3-wrapper": "^7.2.0", - "@types/yargs": "^11.0.0", - "chalk": "^2.3.0", - "chokidar": "^3.0.2", - "ethereum-types": "^3.2.0", - "ethereumjs-util": "^5.1.1", - "lodash": "^4.17.11", - "mkdirp": "^0.5.1", - "pluralize": "^7.0.0", - "require-from-string": "^2.0.1", - "semver": "5.5.0", - "solc": "^0.5.5", - "source-map-support": "^0.5.0", - "web3-eth-abi": "^1.0.0-beta.24", - "yargs": "^10.0.3" - }, - "publishConfig": { - "access": "public" - }, - "gitHead": "4f91bfd907996b2f4dd383778b50c479c2602b56" -} diff --git a/packages/sol-compiler/solc_bin/.gitkeep b/packages/sol-compiler/solc_bin/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/sol-compiler/src/cli.ts b/packages/sol-compiler/src/cli.ts deleted file mode 100644 index c76a083396..0000000000 --- a/packages/sol-compiler/src/cli.ts +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env node -// We need the above pragma since this script will be run as a command-line tool. - -import { logUtils } from '@0x/utils'; -import * as _ from 'lodash'; -import 'source-map-support/register'; -import * as yargs from 'yargs'; - -import { Compiler } from './compiler'; - -const DEFAULT_CONTRACTS_LIST = '*'; -const SEPARATOR = ','; - -(async () => { - const argv = yargs - .option('contracts-dir', { - type: 'string', - description: 'path of contracts directory to compile', - }) - .option('artifacts-dir', { - type: 'string', - description: 'path to write contracts artifacts to', - }) - .option('contracts', { - type: 'string', - description: 'comma separated list of contracts to compile', - }) - .option('watch', { - alias: 'w', - default: false, - }) - .help().argv; - const contracts = - argv.contracts === undefined - ? undefined - : argv.contracts === DEFAULT_CONTRACTS_LIST - ? DEFAULT_CONTRACTS_LIST - : argv.contracts.split(SEPARATOR); - const opts = _.omitBy( - { - contractsDir: argv.contractsDir, - artifactsDir: argv.artifactsDir, - contracts, - isOfflineMode: process.env.SOLC_OFFLINE ? true : undefined, - }, - v => v === undefined, - ); - const compiler = new Compiler(await Compiler.getCompilerOptionsAsync(opts)); - if (argv.watch) { - await compiler.watchAsync(); - } else { - await compiler.compileAsync(); - } -})().catch(err => { - logUtils.log(err); - process.exit(1); -}); diff --git a/packages/sol-compiler/src/compiler.ts b/packages/sol-compiler/src/compiler.ts deleted file mode 100644 index b345fc69aa..0000000000 --- a/packages/sol-compiler/src/compiler.ts +++ /dev/null @@ -1,449 +0,0 @@ -import { assert } from '@0x/assert'; -import { - ContractSource, - FallthroughResolver, - FSResolver, - NameResolver, - NPMResolver, - RelativeFSResolver, - Resolver, - SpyResolver, - URLResolver, -} from '@0x/sol-resolver'; -import { logUtils } from '@0x/utils'; -import * as chokidar from 'chokidar'; -import { CompilerOptions, ContractArtifact, ContractVersionData, StandardOutput } from 'ethereum-types'; -import * as fs from 'fs'; -import * as _ from 'lodash'; -import * as path from 'path'; -import * as pluralize from 'pluralize'; -import * as semver from 'semver'; -import { StandardInput } from 'solc'; -import { promisify } from 'util'; - -import { compilerOptionsSchema } from './schemas/compiler_options_schema'; -import { - CompiledSources, - createDirIfDoesNotExistAsync, - getContractArtifactIfExistsAsync, - getDependencyNameToPackagePath, - getSolcJSReleasesAsync, - getSolcJSVersionFromPath, - getSourcesWithDependencies, - getSourceTreeHash, - normalizeSolcVersion, - parseSolidityVersionRange, -} from './utils/compiler'; -import { constants } from './utils/constants'; -import { fsWrapper } from './utils/fs_wrapper'; -import { utils } from './utils/utils'; - -import { ContractContentsByPath, ImportPrefixRemappings, SolcWrapper } from './solc_wrapper'; -import { SolcWrapperV04 } from './solc_wrapper_v04'; -import { SolcWrapperV05 } from './solc_wrapper_v05'; -import { SolcWrapperV06 } from './solc_wrapper_v06'; -import { SolcWrapperV07 } from './solc_wrapper_v07'; - -export type TYPE_ALL_FILES_IDENTIFIER = '*'; -export const ALL_CONTRACTS_IDENTIFIER = '*'; -export const ALL_FILES_IDENTIFIER = '*'; - -const DEFAULT_COMPILER_OPTS: CompilerOptions = { - contractsDir: path.resolve('contracts'), - artifactsDir: path.resolve('artifacts'), - contracts: ALL_CONTRACTS_IDENTIFIER as TYPE_ALL_FILES_IDENTIFIER, - useDockerisedSolc: false, - isOfflineMode: false, - shouldSaveStandardInput: false, -}; - -interface ContractsByVersion { - [solcVersion: string]: ContractContentsByPath; -} - -interface ContractPathToData { - [contractPath: string]: ContractData; -} - -interface ContractData { - currentArtifactIfExists: ContractArtifact | void; - sourceTreeHashHex: string; - contractName: string; -} - -// tslint:disable no-non-null-assertion -/** - * The Compiler facilitates compiling Solidity smart contracts and saves the results - * to artifact files. - */ -export class Compiler { - private readonly _opts: CompilerOptions; - private readonly _resolver: Resolver; - private readonly _nameResolver: NameResolver; - private readonly _contractsDir: string; - private readonly _artifactsDir: string; - private readonly _solcVersionIfExists: string | undefined; - private readonly _specifiedContracts: string[] | TYPE_ALL_FILES_IDENTIFIER; - private readonly _isOfflineMode: boolean; - private readonly _shouldSaveStandardInput: boolean; - private readonly _solcWrappersByVersion: { [version: string]: SolcWrapper } = {}; - - public static async getCompilerOptionsAsync( - overrides: Partial = {}, - file: string = 'compiler.json', - ): Promise { - const fileConfig: CompilerOptions = (await promisify(fs.stat)(file)).isFile - ? JSON.parse((await promisify(fs.readFile)(file, 'utf8')).toString()) - : {}; - assert.doesConformToSchema('compiler.json', fileConfig, compilerOptionsSchema); - return { - ...fileConfig, - ...overrides, - }; - } - - private static _createDefaultResolver( - contractsDir: string, - // tslint:disable-next-line: trailing-comma - ...appendedResolvers: Resolver[] - ): Resolver { - const resolver = new FallthroughResolver(); - resolver.appendResolver(new URLResolver()); - resolver.appendResolver(new NPMResolver(contractsDir)); - resolver.appendResolver(new RelativeFSResolver(contractsDir)); - resolver.appendResolver(new FSResolver()); - for (const appendedResolver of appendedResolvers) { - resolver.appendResolver(appendedResolver); - } - return resolver; - } - - /** - * Instantiates a new instance of the Compiler class. - * @param opts Optional compiler options - * @return An instance of the Compiler class. - */ - constructor(opts: CompilerOptions = {}) { - this._opts = { ...DEFAULT_COMPILER_OPTS, ...opts }; - assert.doesConformToSchema('opts', this._opts, compilerOptionsSchema); - this._contractsDir = path.resolve(this._opts.contractsDir!); - this._solcVersionIfExists = - process.env.SOLCJS_PATH !== undefined - ? getSolcJSVersionFromPath(process.env.SOLCJS_PATH) - : this._opts.solcVersion; - this._artifactsDir = this._opts.artifactsDir!; - this._specifiedContracts = this._opts.contracts!; - this._isOfflineMode = this._opts.isOfflineMode!; - this._shouldSaveStandardInput = this._opts.shouldSaveStandardInput!; - this._nameResolver = new NameResolver(this._contractsDir); - this._resolver = Compiler._createDefaultResolver(this._contractsDir, this._nameResolver); - } - - /** - * Compiles selected Solidity files found in `contractsDir` and writes JSON artifacts to `artifactsDir`. - */ - public async compileAsync(): Promise { - await createDirIfDoesNotExistAsync(this._artifactsDir); - await createDirIfDoesNotExistAsync(constants.SOLC_BIN_DIR); - await this._compileContractsAsync(this.getContractNamesToCompile(), true); - } - - /** - * Compiles Solidity files specified during instantiation, and returns the - * compiler output given by solc. Return value is an array of outputs: - * Solidity modules are batched together by version required, and each - * element of the returned array corresponds to a compiler version, and - * each element contains the output for all of the modules compiled with - * that version. - */ - public async getCompilerOutputsAsync(): Promise { - const promisedOutputs = this._compileContractsAsync(this.getContractNamesToCompile(), false); - return promisedOutputs; - } - - /** - * Watch contracts in the current project directory and recompile on changes. - */ - public async watchAsync(): Promise { - console.clear(); // tslint:disable-line:no-console - logUtils.logWithTime('Starting compilation in watch mode...'); - const MATCH_NOTHING_REGEX = '^$'; - const IGNORE_DOT_FILES_REGEX = /(^|[\/\\])\../; - // Initially we watch nothing. We'll add the paths later. - const watcher = chokidar.watch(MATCH_NOTHING_REGEX, { ignored: IGNORE_DOT_FILES_REGEX }); - const onFileChangedAsync = async () => { - watcher.unwatch('*'); // Stop watching - try { - await this.compileAsync(); - logUtils.logWithTime('Found 0 errors. Watching for file changes.'); - } catch (err) { - if (err.typeName === 'CompilationError') { - logUtils.logWithTime( - `Found ${err.errorsCount} ${pluralize('error', err.errorsCount)}. Watching for file changes.`, - ); - } else { - logUtils.logWithTime('Found errors. Watching for file changes.'); - } - } - - const pathsToWatch = this._getPathsToWatch(); - watcher.add(pathsToWatch); - }; - await onFileChangedAsync(); - watcher.on('change', () => { - console.clear(); // tslint:disable-line:no-console - logUtils.logWithTime('File change detected. Starting incremental compilation...'); - // NOTE: We can't await it here because that's a callback. - // Instead we stop watching inside of it and start it again when we're finished. - onFileChangedAsync(); // tslint:disable-line no-floating-promises - }); - } - - /** - * Gets a list of contracts to compile. - */ - public getContractNamesToCompile(): string[] { - let contractNamesToCompile; - if (this._specifiedContracts === ALL_CONTRACTS_IDENTIFIER) { - const allContracts = this._nameResolver.getAll(); - contractNamesToCompile = _.map(allContracts, contractSource => - path.basename(contractSource.path, constants.SOLIDITY_FILE_EXTENSION), - ); - } else { - return this._specifiedContracts; - } - return contractNamesToCompile; - } - - private _getPathsToWatch(): string[] { - const contractNames = this.getContractNamesToCompile(); - const spyResolver = new SpyResolver(this._resolver); - for (const contractName of contractNames) { - const contractSource = spyResolver.resolve(contractName); - // NOTE: We ignore the return value here. We don't want to compute the source tree hash. - // We just want to call a SpyResolver on each contracts and it's dependencies and - // this is a convenient way to reuse the existing code that does that. - // We can then get all the relevant paths from the `spyResolver` below. - getSourceTreeHash(spyResolver, contractSource.path); - } - const pathsToWatch = _.uniq(spyResolver.resolvedContractSources.map(cs => cs.absolutePath)); - return pathsToWatch; - } - - /** - * Compiles contracts, and, if `shouldPersist` is true, saves artifacts to artifactsDir. - * @param fileName Name of contract with '.sol' extension. - * @return an array of compiler outputs, where each element corresponds to a different version of solc-js. - */ - private async _compileContractsAsync(contractNames: string[], shouldPersist: boolean): Promise { - // batch input contracts together based on the version of the compiler that they require. - const contractsByVersion: ContractsByVersion = {}; - // map contract paths to data about them for later verification and persistence - const contractPathToData: ContractPathToData = {}; - - const solcJSReleases = await getSolcJSReleasesAsync(this._isOfflineMode); - const resolvedContractSources: ContractSource[] = []; - for (const contractName of contractNames) { - const spyResolver = new SpyResolver(this._resolver); - const contractSource = spyResolver.resolve(contractName); - const sourceTreeHashHex = getSourceTreeHash(spyResolver, contractSource.path).toString('hex'); - const contractData = { - contractName: path.basename(contractName, constants.SOLIDITY_FILE_EXTENSION), - currentArtifactIfExists: await getContractArtifactIfExistsAsync(this._artifactsDir, contractName), - sourceTreeHashHex: `0x${sourceTreeHashHex}`, - }; - if (!this._shouldCompile(contractData)) { - continue; - } - contractPathToData[contractSource.absolutePath] = contractData; - let solcVersion: string | undefined; - if (this._solcVersionIfExists) { - solcVersion = this._solcVersionIfExists; - } else { - const solidityVersion = semver.maxSatisfying( - _.keys(solcJSReleases), - parseSolidityVersionRange(contractSource.source), - ); - if (solidityVersion) { - solcVersion = normalizeSolcVersion(solcJSReleases[solidityVersion]); - } - } - if (solcVersion === undefined) { - throw new Error( - `Couldn't find any solidity version satisfying the constraint ${parseSolidityVersionRange( - contractSource.source, - )}`, - ); - } - // add input to the right version batch - for (const resolvedContractSource of spyResolver.resolvedContractSources) { - contractsByVersion[solcVersion] = contractsByVersion[solcVersion] || {}; - contractsByVersion[solcVersion][resolvedContractSource.absolutePath] = resolvedContractSource.source; - resolvedContractSources.push(resolvedContractSource); - } - } - - const importRemappings = getDependencyNameToPackagePath(resolvedContractSources); - const versions = Object.keys(contractsByVersion); - - const compilationResults = await Promise.all( - versions.map(async solcVersion => { - const contracts = contractsByVersion[solcVersion]; - logUtils.warn( - `Compiling ${Object.keys(contracts).length} contracts (${Object.keys(contracts).map(p => - path.basename(p), - )}) with Solidity ${solcVersion}...`, - ); - return this._getSolcWrapperForVersion(solcVersion).compileAsync(contracts, importRemappings); - }), - ); - - if (shouldPersist) { - await Promise.all( - versions.map(async (solcVersion, i) => { - const compilationResult = compilationResults[i]; - const contracts = contractsByVersion[solcVersion]; - // tslint:disable-next-line: forin - await Promise.all( - Object.keys(contracts).map(async contractPath => { - const contractData = contractPathToData[contractPath]; - if (contractData === undefined) { - return; - } - const { contractName } = contractData; - const compiledContract = compilationResult.output.contracts[contractPath][contractName]; - if (compiledContract === undefined) { - throw new Error( - `Contract ${contractName} not found in ${contractPath}. Please make sure your contract has the same name as it's file name`, - ); - } - await this._persistCompiledContractAsync( - contractPath, - contractPathToData[contractPath].currentArtifactIfExists, - contractPathToData[contractPath].sourceTreeHashHex, - contractName, - solcVersion, - contracts, - compilationResult.input, - compilationResult.output, - importRemappings, - ); - }), - ); - }), - ); - } - return compilationResults.map(r => r.output); - } - - private _shouldCompile(contractData: ContractData): boolean { - if (contractData.currentArtifactIfExists === undefined) { - return true; - } else { - const currentArtifact = contractData.currentArtifactIfExists as ContractArtifact; - const solc = this._getSolcWrapperForVersion(currentArtifact.compiler.version); - const isUserOnLatestVersion = currentArtifact.schemaVersion === constants.LATEST_ARTIFACT_VERSION; - const didCompilerSettingsChange = solc.areCompilerSettingsDifferent(currentArtifact.compiler.settings); - const didSourceChange = currentArtifact.sourceTreeHashHex !== contractData.sourceTreeHashHex; - return !isUserOnLatestVersion || didCompilerSettingsChange || didSourceChange; - } - } - - private _getSolcWrapperForVersion(solcVersion: string): SolcWrapper { - const normalizedVersion = normalizeSolcVersion(solcVersion); - return ( - this._solcWrappersByVersion[normalizedVersion] || - (this._solcWrappersByVersion[normalizedVersion] = this._createSolcInstance(normalizedVersion)) - ); - } - - private _createSolcInstance(solcVersion: string): SolcWrapper { - if (solcVersion.startsWith('0.4.')) { - return new SolcWrapperV04(solcVersion, this._opts); - } - if (solcVersion.startsWith('0.5.')) { - return new SolcWrapperV05(solcVersion, this._opts); - } - if (solcVersion.startsWith('0.6')) { - return new SolcWrapperV06(solcVersion, this._opts); - } - if (solcVersion.startsWith('0.7')) { - return new SolcWrapperV07(solcVersion, this._opts); - } - throw new Error(`Missing Solc wrapper implementation for version ${solcVersion}`); - } - - private async _persistCompiledContractAsync( - contractPath: string, - currentArtifactIfExists: ContractArtifact | void, - sourceTreeHashHex: string, - contractName: string, - solcVersion: string, - sourcesByPath: ContractContentsByPath, - compilerInput: StandardInput, - compilerOutput: StandardOutput, - importRemappings: ImportPrefixRemappings, - ): Promise { - const compiledContract = compilerOutput.contracts[contractPath][contractName]; - // need to gather sourceCodes for this artifact, but compilerOutput.sources (the list of contract modules) - // contains listings for every contract compiled during the compiler invocation that compiled the contract - // to be persisted, which could include many that are irrelevant to the contract at hand. So, gather up only - // the relevant sources: - const allSources: CompiledSources = {}; - // tslint:disable-next-line: forin - for (const sourceContractPath in sourcesByPath) { - const content = sourcesByPath[sourceContractPath]; - const { id } = compilerOutput.sources[sourceContractPath]; - allSources[sourceContractPath] = { id, content }; - } - const usedSources = getSourcesWithDependencies(contractPath, allSources, importRemappings); - - const contractVersion: ContractVersionData = { - compilerOutput: compiledContract, - sourceTreeHashHex, - sources: _.mapValues(usedSources, ({ id }) => ({ id })), - sourceCodes: _.mapValues(usedSources, ({ content }) => content), - compiler: { - name: 'solc', - version: solcVersion, - settings: compilerInput.settings, - }, - }; - - let newArtifact: ContractArtifact; - if (currentArtifactIfExists !== undefined) { - const currentArtifact = currentArtifactIfExists as ContractArtifact; - newArtifact = { - ...currentArtifact, - ...contractVersion, - }; - } else { - newArtifact = { - schemaVersion: constants.LATEST_ARTIFACT_VERSION, - contractName, - ...contractVersion, - chains: {}, - }; - } - - const artifactString = utils.stringifyWithFormatting(newArtifact); - const currentArtifactPath = `${this._artifactsDir}/${contractName}.json`; - await fsWrapper.writeFileAsync(currentArtifactPath, artifactString); - logUtils.warn(`${contractName} artifact saved!`); - - if (this._shouldSaveStandardInput) { - await fsWrapper.writeFileAsync( - `${this._artifactsDir}/${contractName}.input.json`, - utils.stringifyWithFormatting({ - ...compilerInput, - // Insert solcVersion into input. - settings: { - ...compilerInput.settings, - version: solcVersion, - }, - }), - ); - logUtils.warn(`${contractName} input artifact saved!`); - } - } -} diff --git a/packages/sol-compiler/src/globals.d.ts b/packages/sol-compiler/src/globals.d.ts deleted file mode 100644 index 94e63a32de..0000000000 --- a/packages/sol-compiler/src/globals.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -declare module '*.json' { - const json: any; - /* tslint:disable */ - export default json; - /* tslint:enable */ -} diff --git a/packages/sol-compiler/src/index.ts b/packages/sol-compiler/src/index.ts deleted file mode 100644 index 38e3b15987..0000000000 --- a/packages/sol-compiler/src/index.ts +++ /dev/null @@ -1,32 +0,0 @@ -export { Compiler } from './compiler'; -export { - AbiDefinition, - CompilerOptions, - CompilerSettings, - DataItem, - TupleDataItem, - DevdocOutput, - ErrorSeverity, - ErrorType, - EventAbi, - EventParameter, - EvmBytecodeOutput, - EvmBytecodeOutputLinkReferences, - EvmOutput, - FallbackAbi, - FunctionAbi, - MethodAbi, - ConstructorAbi, - ConstructorStateMutability, - ContractAbi, - OutputField, - CompilerSettingsMetadata, - OptimizerSettings, - ParamDescription, - SolcError, - StandardContractOutput, - StandardOutput, - StateMutability, - SourceLocation, - RevertErrorAbi, -} from 'ethereum-types'; diff --git a/packages/sol-compiler/src/schemas/compiler_options_schema.ts b/packages/sol-compiler/src/schemas/compiler_options_schema.ts deleted file mode 100644 index 12b655cf68..0000000000 --- a/packages/sol-compiler/src/schemas/compiler_options_schema.ts +++ /dev/null @@ -1,29 +0,0 @@ -export const compilerOptionsSchema = { - id: '/CompilerOptions', - properties: { - contractsDir: { type: 'string' }, - artifactsDir: { type: 'string' }, - solcVersion: { type: 'string', pattern: '^\\d+.\\d+.\\d+\\+commit\\.[a-f0-9]{8}$' }, - compilerSettings: { type: 'object' }, - contracts: { - oneOf: [ - { - type: 'string', - pattern: '^\\*$', - }, - { - type: 'array', - items: { - type: 'string', - }, - }, - ], - }, - useDockerisedSolc: { type: 'boolean' }, - isOfflineMode: { type: 'boolean' }, - shouldSaveStandardInput: { type: 'boolean' }, - }, - type: 'object', - required: [], - additionalProperties: false, -}; diff --git a/packages/sol-compiler/src/solc_wrapper.ts b/packages/sol-compiler/src/solc_wrapper.ts deleted file mode 100644 index 4ad2a337df..0000000000 --- a/packages/sol-compiler/src/solc_wrapper.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { StandardOutput } from 'ethereum-types'; -import { StandardInput } from 'solc'; - -export interface ContractContentsByPath { - [path: string]: string; -} - -export interface ImportPrefixRemappings { - [prefix: string]: string; -} - -export interface CompilationResult { - input: StandardInput; - output: StandardOutput; -} - -export abstract class SolcWrapper { - /** - * Get the solc version. - */ - public abstract get version(): string; - - /** - * Check if the configured compiler settings is different from another. - */ - public abstract areCompilerSettingsDifferent(settings: any): boolean; - - /** - * Compile contracts, returning standard input and output. - */ - public abstract compileAsync( - contractsByPath: ContractContentsByPath, - dependencies: ImportPrefixRemappings, - ): Promise; -} diff --git a/packages/sol-compiler/src/solc_wrapper_v04.ts b/packages/sol-compiler/src/solc_wrapper_v04.ts deleted file mode 100644 index f0ad4b0538..0000000000 --- a/packages/sol-compiler/src/solc_wrapper_v04.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { SolcWrapperV05 } from './solc_wrapper_v05'; - -export const SolcWrapperV04 = SolcWrapperV05; diff --git a/packages/sol-compiler/src/solc_wrapper_v05.ts b/packages/sol-compiler/src/solc_wrapper_v05.ts deleted file mode 100644 index bc49346d48..0000000000 --- a/packages/sol-compiler/src/solc_wrapper_v05.ts +++ /dev/null @@ -1,102 +0,0 @@ -import { CompilerOptions, StandardOutput } from 'ethereum-types'; -import * as _ from 'lodash'; -import solc = require('solc'); - -import { - addHexPrefixToContractBytecode, - compileDockerAsync, - compileSolcJSAsync, - getSolcJSAsync, - getSolidityVersionFromSolcVersion, - printCompilationErrorsAndWarnings, -} from './utils/compiler'; - -import { CompilationResult, ContractContentsByPath, ImportPrefixRemappings, SolcWrapper } from './solc_wrapper'; - -// Solc compiler settings cannot be configured from the commandline. -// If you need this configured, please create a `compiler.json` config file -// with your desired configurations. -export const DEFAULT_COMPILER_SETTINGS: solc.CompilerSettings = { - optimizer: { - enabled: false, - }, - outputSelection: { - '*': { - '*': ['abi', 'evm.bytecode.object'], - }, - }, -}; - -// tslint:disable no-non-null-assertion - -export class SolcWrapperV05 extends SolcWrapper { - protected readonly _compilerSettings: solc.CompilerSettings; - - constructor(protected readonly _solcVersion: string, protected readonly _opts: CompilerOptions) { - super(); - this._compilerSettings = { - ...DEFAULT_COMPILER_SETTINGS, - ..._opts.compilerSettings, - }; - } - - public get version(): string { - return this._solcVersion; - } - - public get solidityVersion(): string { - return getSolidityVersionFromSolcVersion(this._solcVersion); - } - - public areCompilerSettingsDifferent(settings: any): boolean { - return !_.isEqual(_.omit(settings, 'remappings'), _.omit(this._compilerSettings, 'remappings')); - } - - public async compileAsync( - contractsByPath: ContractContentsByPath, - importRemappings: ImportPrefixRemappings, - ): Promise { - const input: solc.StandardInput = { - language: 'Solidity', - sources: {}, - settings: { - remappings: [], - ...this._compilerSettings, - }, - }; - for (const [contractPath, contractContent] of Object.entries(contractsByPath)) { - input.sources[contractPath] = { content: contractContent }; - } - for (const [prefix, _path] of Object.entries(importRemappings)) { - input.settings.remappings!.push(`${prefix}=${_path}`); - } - const output = await this._compileInputAsync(input); - if (output.errors !== undefined) { - printCompilationErrorsAndWarnings(output.errors); - } - return { - input, - output: this._normalizeOutput(output), - }; - } - - protected async _compileInputAsync(input: solc.StandardInput): Promise { - if (this._opts.useDockerisedSolc) { - return compileDockerAsync(this.solidityVersion, input); - } - const solcInstance = await getSolcJSAsync(this.solidityVersion, !!this._opts.isOfflineMode); - return compileSolcJSAsync(solcInstance, input); - } - - // tslint:disable-next-line: prefer-function-over-method - protected _normalizeOutput(output: StandardOutput): StandardOutput { - const _output = _.cloneDeep(output); - // tslint:disable-next-line forin - for (const contractPath in _output.contracts) { - for (const contract of Object.values(_output.contracts[contractPath])) { - addHexPrefixToContractBytecode(contract); - } - } - return _output; - } -} diff --git a/packages/sol-compiler/src/solc_wrapper_v06.ts b/packages/sol-compiler/src/solc_wrapper_v06.ts deleted file mode 100644 index 625c76b1eb..0000000000 --- a/packages/sol-compiler/src/solc_wrapper_v06.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { CompilerOptions, StandardOutput } from 'ethereum-types'; -import solc = require('solc'); - -import { compileSolcJSAsync, getSolcJSAsync } from './utils/compiler'; - -import { SolcWrapperV05 } from './solc_wrapper_v05'; - -// 0.6.x has a `compile()` function in lieu of `compileStandardWrapper`. -type SolcV06 = solc.SolcInstance & { compile(input: string): string }; - -export class SolcWrapperV06 extends SolcWrapperV05 { - constructor(solcVersion: string, opts: CompilerOptions) { - super(solcVersion, opts); - } - - protected async _compileInputAsync(input: solc.StandardInput): Promise { - if (this._opts.useDockerisedSolc) { - return super._compileInputAsync(input); - } - // Shim the old `compileStandardWrapper` function. - const solcInstance = (await getSolcJSAsync(this.solidityVersion, !!this._opts.isOfflineMode)) as SolcV06; - solcInstance.compileStandardWrapper = solcInstance.compile; - return compileSolcJSAsync(solcInstance, input); - } - - protected _normalizeOutput(output: StandardOutput): StandardOutput { - const _output = super._normalizeOutput(output); - // Filter out 'receive' ABI item types until ethers supports it. - for (const contracts of Object.values(_output.contracts)) { - for (const contract of Object.values(contracts)) { - contract.abi = contract.abi.filter(v => v.type !== 'receive'); - } - } - return _output; - } -} diff --git a/packages/sol-compiler/src/solc_wrapper_v07.ts b/packages/sol-compiler/src/solc_wrapper_v07.ts deleted file mode 100644 index 4acdc9b587..0000000000 --- a/packages/sol-compiler/src/solc_wrapper_v07.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { SolcWrapperV06 } from './solc_wrapper_v06'; - -export const SolcWrapperV07 = SolcWrapperV06; diff --git a/packages/sol-compiler/src/utils/compiler.ts b/packages/sol-compiler/src/utils/compiler.ts deleted file mode 100644 index 317a520fe0..0000000000 --- a/packages/sol-compiler/src/utils/compiler.ts +++ /dev/null @@ -1,517 +0,0 @@ -import { ContractSource, Resolver } from '@0x/sol-resolver'; -import { fetchAsync, logUtils } from '@0x/utils'; -import chalk from 'chalk'; -import { exec, spawn } from 'child_process'; -import { ContractArtifact } from 'ethereum-types'; -import * as ethUtil from 'ethereumjs-util'; -import * as _ from 'lodash'; -import * as path from 'path'; -import * as requireFromString from 'require-from-string'; -import * as solc from 'solc'; -import { promisify } from 'util'; - -import { constants } from './constants'; -import { fsWrapper } from './fs_wrapper'; -import { BinaryPaths, CompilationError } from './types'; - -/** - * Gets contract data or returns if an artifact does not exist. - * @param artifactsDir Path to the artifacts directory. - * @param contractName Name of contract. - * @return Contract data or undefined. - */ -export async function getContractArtifactIfExistsAsync( - artifactsDir: string, - contractName: string, -): Promise { - let contractArtifact; - const currentArtifactPath = `${artifactsDir}/${path.basename( - contractName, - constants.SOLIDITY_FILE_EXTENSION, - )}.json`; - try { - const opts = { - encoding: 'utf8', - }; - const contractArtifactString = await fsWrapper.readFileAsync(currentArtifactPath, opts); - contractArtifact = JSON.parse(contractArtifactString); - return contractArtifact; - } catch (err) { - return undefined; - } -} - -/** - * Creates a directory if it does not already exist. - * @param artifactsDir Path to the directory. - */ -export async function createDirIfDoesNotExistAsync(dirPath: string): Promise { - if (!fsWrapper.doesPathExistSync(dirPath)) { - logUtils.warn(`Creating directory at ${dirPath}...`); - await fsWrapper.mkdirpAsync(dirPath); - } -} - -/** - * Searches Solidity source code for compiler version range. - * @param source Source code of contract. - * @return Solc compiler version range. - */ -export function parseSolidityVersionRange(source: string): string { - const SOLIDITY_VERSION_RANGE_REGEX = /pragma\s+solidity\s+(.*);/; - const solcVersionRangeMatch = source.match(SOLIDITY_VERSION_RANGE_REGEX); - if (solcVersionRangeMatch === null) { - throw new Error('Could not find Solidity version range in source'); - } - const solcVersionRange = solcVersionRangeMatch[1]; - return solcVersionRange; -} - -/** - * Normalizes the path found in the error message. If it cannot be normalized - * the original error message is returned. - * Example: converts 'base/Token.sol:6:46: Warning: Unused local variable' - * to 'Token.sol:6:46: Warning: Unused local variable' - * This is used to prevent logging the same error multiple times. - * @param errMsg An error message from the compiled output. - * @return The error message with directories truncated from the contract path. - */ -export function getNormalizedErrMsg(errMsg: string): string { - const SOLIDITY_FILE_EXTENSION_REGEX = /(.*\.sol):/; - const errPathMatch = errMsg.match(SOLIDITY_FILE_EXTENSION_REGEX); - if (errPathMatch === null) { - // This can occur if solidity outputs a general warning, e.g - // Warning: This is a pre-release compiler version, please do not use it in production. - return errMsg; - } - const errPath = errPathMatch[0]; - const baseContract = path.basename(errPath); - const normalizedErrMsg = errMsg.replace(errPath, baseContract); - return normalizedErrMsg; -} - -/** - * Parses the contract source code and extracts the dendencies - * @param source Contract source code - * @return List of dependendencies - */ -export function parseDependencies(contractSource: ContractSource): string[] { - // TODO: Use a proper parser - const source = contractSource.source; - const IMPORT_REGEX = /(import\s)/; - const DEPENDENCY_PATH_REGEX = /"([^"]+)"/; // Source: https://github.com/BlockChainCompany/soljitsu/blob/master/lib/shared.js - const dependencies: string[] = []; - const lines = source.split('\n'); - _.forEach(lines, line => { - if (line.match(IMPORT_REGEX) !== null) { - const dependencyMatch = line.match(DEPENDENCY_PATH_REGEX); - if (dependencyMatch !== null) { - let dependencyPath = dependencyMatch[1]; - if (dependencyPath.startsWith('.')) { - dependencyPath = path.join(path.dirname(contractSource.path), dependencyPath); - } - dependencies.push(dependencyPath); - } - } - }); - return dependencies; -} - -let solcJSReleasesCache: BinaryPaths | undefined; - -/** - * Fetches the list of available solidity compilers - * @param isOfflineMode Offline mode flag - */ -export async function getSolcJSReleasesAsync(isOfflineMode: boolean): Promise { - if (isOfflineMode) { - return constants.SOLC_BIN_PATHS; - } - if (solcJSReleasesCache === undefined) { - const versionList = await fetch('https://ethereum.github.io/solc-bin/bin/list.json'); - const versionListJSON = await versionList.json(); - solcJSReleasesCache = versionListJSON.releases; - } - return solcJSReleasesCache as BinaryPaths; -} - -/** - * Compiles the contracts and prints errors/warnings - * @param solcInstance Instance of a solc compiler - * @param standardInput Solidity standard JSON input - * @param isOfflineMode Offline mode flag - */ -export async function compileSolcJSAsync( - solcInstance: solc.SolcInstance, - standardInput: solc.StandardInput, -): Promise { - const standardInputStr = JSON.stringify(standardInput); - const standardOutputStr = solcInstance.compileStandardWrapper(standardInputStr); - const compiled: solc.StandardOutput = JSON.parse(standardOutputStr); - return compiled; -} - -/** - * Compiles the contracts and prints errors/warnings - * @param solidityVersion Solidity version - * @param standardInput Solidity standard JSON input - */ -export async function compileDockerAsync( - solidityVersion: string, - standardInput: solc.StandardInput, -): Promise { - const standardInputStr = JSON.stringify(standardInput, null, 2); - // prettier-ignore - const dockerArgs = [ - 'run', - '-i', - '-a', 'stdin', - '-a', 'stdout', - '-a', 'stderr', - `ethereum/solc:${solidityVersion}`, - 'solc', '--standard-json', - ]; - return new Promise((accept, reject) => { - const p = spawn('docker', dockerArgs, { shell: true, stdio: ['pipe', 'pipe', 'inherit'] }); - p.stdin.write(standardInputStr); - p.stdin.end(); - let fullOutput = ''; - p.stdout.on('data', (chunk: string) => { - fullOutput += chunk; - }); - p.on('close', code => { - if (code !== 0) { - reject('Compilation failed'); - } - accept(JSON.parse(fullOutput)); - }); - }); -} - -/** - * Example "relative" paths: - * /user/leo/0x-monorepo/contracts/extensions/contracts/extension.sol -> extension.sol - * /user/leo/0x-monorepo/node_modules/@0x/contracts-protocol/contracts/exchange.sol -> @0x/contracts-protocol/contracts/exchange.sol - */ -function makeContractPathRelative( - absolutePath: string, - contractsDir: string, - dependencyNameToPath: { [dependencyName: string]: string }, -): string { - let contractPath = absolutePath.replace(`${contractsDir}/`, ''); - _.map(dependencyNameToPath, (packagePath: string, dependencyName: string) => { - contractPath = contractPath.replace(packagePath, dependencyName); - }); - return contractPath; -} - -/** - * Makes the path relative removing all system-dependent data. Converts absolute paths to a format suitable for artifacts. - * @param absolutePathToSmth Absolute path to contract or source - * @param contractsDir Current package contracts directory location - * @param dependencyNameToPath Mapping of dependency name to package path - */ -export function makeContractPathsRelative( - absolutePathToSmth: { [absoluteContractPath: string]: any }, - contractsDir: string, - dependencyNameToPath: { [dependencyName: string]: string }, -): { [contractPath: string]: any } { - return _.mapKeys(absolutePathToSmth, (_val: any, absoluteContractPath: string) => - makeContractPathRelative(absoluteContractPath, contractsDir, dependencyNameToPath), - ); -} - -/** - * Separates errors from warnings, formats the messages and prints them. Throws if there is any compilation error (not warning). - * @param solcErrors The errors field of standard JSON output that contains errors and warnings. - */ -export function printCompilationErrorsAndWarnings(solcErrors: solc.SolcError[]): void { - const SOLIDITY_WARNING = 'warning'; - const errors = _.filter(solcErrors, entry => entry.severity !== SOLIDITY_WARNING); - const warnings = _.filter(solcErrors, entry => entry.severity === SOLIDITY_WARNING); - if (!_.isEmpty(errors)) { - errors.forEach(error => { - const normalizedErrMsg = getNormalizedErrMsg(error.formattedMessage || error.message); - logUtils.log(chalk.red('error'), normalizedErrMsg); - }); - throw new CompilationError(errors.length); - } else { - warnings.forEach(warning => { - const normalizedWarningMsg = getNormalizedErrMsg(warning.formattedMessage || warning.message); - logUtils.log(chalk.yellow('warning'), normalizedWarningMsg); - }); - } -} - -/** - * Gets the source tree hash for a file and its dependencies. - * @param fileName Name of contract file. - */ -export function getSourceTreeHash(resolver: Resolver, importPath: string): Buffer { - const contractSource = resolver.resolve(importPath); - const dependencies = parseDependencies(contractSource); - const sourceHash = ethUtil.sha3(contractSource.source); - if (dependencies.length === 0) { - return sourceHash; - } else { - const dependencySourceTreeHashes = _.map(dependencies, (dependency: string) => { - try { - return getSourceTreeHash(resolver, dependency); - } catch (e) { - if (/Error when trying to resolve dependencies for/.test((e as Error).message)) { - throw e; - } else { - throw Error(`Error when trying to resolve dependencies for ${importPath}: ${(e as Error).message}`); - } - } - }); - const sourceTreeHashesBuffer = Buffer.concat([sourceHash, ...dependencySourceTreeHashes]); - const sourceTreeHash = ethUtil.sha3(sourceTreeHashesBuffer); - return sourceTreeHash; - } -} - -/** - * Mapping of absolute contract path to compilation ID and source code. - */ -export interface CompiledSources { - [sourcePath: string]: { id: number; content: string }; -} - -/** - * Contract sources by import path. - */ -export interface CompiledImports { - [importPath: string]: { id: number; content: string }; -} - -/** - * Recursively parses imports from sources starting from `contractPath`. - * @return Sources required by imports. - */ -export function getSourcesWithDependencies( - contractPath: string, - sourcesByAbsolutePath: CompiledSources, - importRemappings: { [prefix: string]: string }, -): CompiledImports { - const compiledImports = { [`./${path.basename(contractPath)}`]: sourcesByAbsolutePath[contractPath] }; - recursivelyGatherDependencySources( - contractPath, - path.dirname(contractPath), - sourcesByAbsolutePath, - importRemappings, - compiledImports, - ); - return compiledImports; -} - -function recursivelyGatherDependencySources( - contractPath: string, - rootDir: string, - sourcesByAbsolutePath: CompiledSources, - importRemappings: { [prefix: string]: string }, - compiledImports: CompiledImports, - visitedAbsolutePaths: { [absPath: string]: boolean } = {}, - importRootDir?: string, -): void { - if (visitedAbsolutePaths[contractPath]) { - return; - } else { - visitedAbsolutePaths[contractPath] = true; - } - const contractSource = sourcesByAbsolutePath[contractPath].content; - const importStatementMatches = contractSource.match(/\nimport[^;]*;/g); - if (importStatementMatches === null) { - return; - } - const lastPathSeparatorPos = contractPath.lastIndexOf('/'); - const contractFolder = lastPathSeparatorPos === -1 ? '' : contractPath.slice(0, lastPathSeparatorPos + 1); - for (const importStatementMatch of importStatementMatches) { - const importPathMatches = importStatementMatch.match(/\"([^\"]*)\"/); - if (importPathMatches === null || importPathMatches.length === 0) { - continue; - } - - let importPath = importPathMatches[1]; - let absPath = importPath; - let _importRootDir = importRootDir; - if (importPath.startsWith('.')) { - absPath = path.join(contractFolder, importPath); - if (_importRootDir) { - // If there's an `_importRootDir`, we're in a package, so express - // the import path as within the package. - importPath = path.join(_importRootDir, importPath); - } else { - // Express relative imports paths as paths from the root directory. - importPath = path.relative(rootDir, absPath); - if (!importPath.startsWith('.')) { - importPath = `./${importPath}`; - } - } - } else { - for (const [prefix, replacement] of Object.entries(importRemappings)) { - if (importPath.startsWith(prefix)) { - absPath = `${replacement}${importPath.substr(prefix.length)}`; - _importRootDir = path.dirname(importPath); - break; - } - } - } - compiledImports[importPath] = sourcesByAbsolutePath[absPath]; - recursivelyGatherDependencySources( - absPath, - rootDir, - sourcesByAbsolutePath, - importRemappings, - compiledImports, - visitedAbsolutePaths, - _importRootDir, - ); - } -} - -/** - * Gets the solidity compiler instance. If the compiler is already cached - gets it from FS, - * otherwise - fetches it and caches it. - * @param solidityVersion The solidity version. e.g. 0.5.0 - * @param isOfflineMode Offline mode flag - */ -export async function getSolcJSAsync(solidityVersion: string, isOfflineMode: boolean): Promise { - const solcJSReleases = await getSolcJSReleasesAsync(isOfflineMode); - const fullSolcVersion = solcJSReleases[solidityVersion]; - if (fullSolcVersion === undefined) { - throw new Error(`${solidityVersion} is not a known compiler version`); - } - const compilerBinFilename = path.join(constants.SOLC_BIN_DIR, fullSolcVersion); - let solcjs: string; - if (await fsWrapper.doesFileExistAsync(compilerBinFilename)) { - solcjs = (await fsWrapper.readFileAsync(compilerBinFilename)).toString(); - } else { - logUtils.warn(`Downloading ${fullSolcVersion}...`); - const url = `${constants.BASE_COMPILER_URL}${fullSolcVersion}`; - const response = await fetchAsync(url); - const SUCCESS_STATUS = 200; - if (response.status !== SUCCESS_STATUS) { - throw new Error(`Failed to load ${fullSolcVersion}`); - } - solcjs = await response.text(); - await fsWrapper.writeFileAsync(compilerBinFilename, solcjs); - } - if (solcjs.length === 0) { - throw new Error('No compiler available'); - } - const solcInstance = solc.setupMethods(requireFromString(solcjs, compilerBinFilename)); - return solcInstance; -} - -/** - * Gets the solidity compiler instance from a module path. - * @param path The path to the solc module. - */ -export function getSolcJSFromPath(modulePath: string): solc.SolcInstance { - return require(modulePath); -} - -/** - * Gets the solidity compiler version from a module path. - * @param path The path to the solc module. - */ -export function getSolcJSVersionFromPath(modulePath: string): string { - return normalizeSolcVersion(require(modulePath).version()); -} - -/** - * Solidity compiler emits the bytecode without a 0x prefix for a hex. This function fixes it if bytecode is present. - * @param compiledContract The standard JSON output section for a contract. Geth modified in place. - */ -export function addHexPrefixToContractBytecode(compiledContract: solc.StandardContractOutput): void { - if (compiledContract.evm !== undefined) { - if (compiledContract.evm.bytecode !== undefined && compiledContract.evm.bytecode.object !== undefined) { - compiledContract.evm.bytecode.object = ethUtil.addHexPrefix(compiledContract.evm.bytecode.object); - } - if ( - compiledContract.evm.deployedBytecode !== undefined && - compiledContract.evm.deployedBytecode.object !== undefined - ) { - compiledContract.evm.deployedBytecode.object = ethUtil.addHexPrefix( - compiledContract.evm.deployedBytecode.object, - ); - } - } -} - -/** - * Takes the list of resolved contract sources from `SpyResolver` and produces a mapping from dependency name - * to package path used in `remappings` later, as well as in generating the "relative" source paths saved to the artifact files. - * @param contractSources The list of resolved contract sources - */ -export function getDependencyNameToPackagePath( - contractSources: ContractSource[], -): { [dependencyName: string]: string } { - const allTouchedFiles = contractSources.map(contractSource => `${contractSource.absolutePath}`); - const NODE_MODULES = 'node_modules'; - const allTouchedDependencies = _.filter(allTouchedFiles, filePath => filePath.includes(NODE_MODULES)); - const dependencyNameToPath: { [dependencyName: string]: string } = {}; - _.map(allTouchedDependencies, dependencyFilePath => { - const lastNodeModulesStart = dependencyFilePath.lastIndexOf(NODE_MODULES); - const lastNodeModulesEnd = lastNodeModulesStart + NODE_MODULES.length; - const importPath = dependencyFilePath.substr(lastNodeModulesEnd + 1); - let packageName; - let packageScopeIfExists; - let dependencyName; - if (_.startsWith(importPath, '@')) { - [packageScopeIfExists, packageName] = importPath.split('/'); - dependencyName = `${packageScopeIfExists}/${packageName}`; - } else { - [packageName] = importPath.split('/'); - dependencyName = `${packageName}`; - } - const dependencyPackagePath = path.join(dependencyFilePath.substr(0, lastNodeModulesEnd), dependencyName); - dependencyNameToPath[dependencyName] = dependencyPackagePath; - }); - return dependencyNameToPath; -} - -/** - * Extract the solidity version (e.g., '0.5.9') from a solc version (e.g., `0.5.9+commit.34d3134f`). - */ -export function getSolidityVersionFromSolcVersion(solcVersion: string): string { - const m = /(\d+\.\d+\.\d+)\+commit\.[a-fA-F0-9]{8}/.exec(solcVersion); - if (!m) { - throw new Error(`Unable to parse solc version string "${solcVersion}"`); - } - return m[1]; -} - -/** - * Strips any extra characters before and after the version + commit hash of a solc version string. - */ -export function normalizeSolcVersion(fullSolcVersion: string): string { - const m = /\d+\.\d+\.\d+\+commit\.[a-fA-F0-9]{8}/.exec(fullSolcVersion); - if (!m) { - throw new Error(`Unable to parse solc version string "${fullSolcVersion}"`); - } - return m[0]; -} - -/** - * Gets the full version string of a dockerized solc. - */ -export async function getDockerFullSolcVersionAsync(solidityVersion: string): Promise { - const dockerCommand = `docker run ethereum/solc:${solidityVersion} --version`; - const versionCommandOutput = (await promisify(exec)(dockerCommand)).stdout.toString(); - const versionCommandOutputParts = versionCommandOutput.split(' '); - return normalizeSolcVersion(versionCommandOutputParts[versionCommandOutputParts.length - 1].trim()); -} - -/** - * Gets the full version string of a JS module solc. - */ -export async function getJSFullSolcVersionAsync( - solidityVersion: string, - isOfflineMode: boolean = false, -): Promise { - return normalizeSolcVersion((await getSolcJSAsync(solidityVersion, isOfflineMode)).version()); -} - -// tslint:disable-next-line: max-file-line-count diff --git a/packages/sol-compiler/src/utils/constants.ts b/packages/sol-compiler/src/utils/constants.ts deleted file mode 100644 index f7bb91d42a..0000000000 --- a/packages/sol-compiler/src/utils/constants.ts +++ /dev/null @@ -1,67 +0,0 @@ -import * as path from 'path'; - -export const constants = { - SOLIDITY_FILE_EXTENSION: '.sol', - BASE_COMPILER_URL: 'https://ethereum.github.io/solc-bin/bin/', - LATEST_ARTIFACT_VERSION: '2.0.0', - SOLC_BIN_DIR: path.join(__dirname, '..', '..', '..', 'solc_bin'), - SOLC_BIN_PATHS: { - '0.5.12': 'soljson-v0.5.12+commit.7709ece9.js', - '0.5.11': 'soljson-v0.5.11+commit.c082d0b4.js', - '0.5.10': 'soljson-v0.5.10+commit.5a6ea5b1.js', - '0.5.9': 'soljson-v0.5.9+commit.e560f70d.js', - '0.5.8': 'soljson-v0.5.8+commit.23d335f2.js', - '0.5.7': 'soljson-v0.5.7+commit.6da8b019.js', - '0.5.6': 'soljson-v0.5.6+commit.b259423e.js', - '0.5.5': 'soljson-v0.5.5+commit.47a71e8f.js', - '0.5.4': 'soljson-v0.5.4+commit.9549d8ff.js', - '0.5.3': 'soljson-v0.5.3+commit.10d17f24.js', - '0.5.2': 'soljson-v0.5.2+commit.1df8f40c.js', - '0.5.1': 'soljson-v0.5.1+commit.c8a2cb62.js', - '0.5.0': 'soljson-v0.5.0+commit.1d4f565a.js', - '0.4.26': 'soljson-v0.4.26+commit.4563c3fc.js', - '0.4.25': 'soljson-v0.4.25+commit.59dbf8f1.js', - '0.4.24': 'soljson-v0.4.24+commit.e67f0147.js', - '0.4.23': 'soljson-v0.4.23+commit.124ca40d.js', - '0.4.22': 'soljson-v0.4.22+commit.4cb486ee.js', - '0.4.21': 'soljson-v0.4.21+commit.dfe3193c.js', - '0.4.20': 'soljson-v0.4.20+commit.3155dd80.js', - '0.4.19': 'soljson-v0.4.19+commit.c4cbbb05.js', - '0.4.18': 'soljson-v0.4.18+commit.9cf6e910.js', - '0.4.17': 'soljson-v0.4.17+commit.bdeb9e52.js', - '0.4.16': 'soljson-v0.4.16+commit.d7661dd9.js', - '0.4.15': 'soljson-v0.4.15+commit.bbb8e64f.js', - '0.4.14': 'soljson-v0.4.14+commit.c2215d46.js', - '0.4.13': 'soljson-v0.4.13+commit.fb4cb1a.js', - '0.4.12': 'soljson-v0.4.12+commit.194ff033.js', - '0.4.11': 'soljson-v0.4.11+commit.68ef5810.js', - '0.4.10': 'soljson-v0.4.10+commit.f0d539ae.js', - '0.4.9': 'soljson-v0.4.9+commit.364da425.js', - '0.4.8': 'soljson-v0.4.8+commit.60cc1668.js', - '0.4.7': 'soljson-v0.4.7+commit.822622cf.js', - '0.4.6': 'soljson-v0.4.6+commit.2dabbdf0.js', - '0.4.5': 'soljson-v0.4.5+commit.b318366e.js', - '0.4.4': 'soljson-v0.4.4+commit.4633f3de.js', - '0.4.3': 'soljson-v0.4.3+commit.2353da71.js', - '0.4.2': 'soljson-v0.4.2+commit.af6afb04.js', - '0.4.1': 'soljson-v0.4.1+commit.4fc6fc2c.js', - '0.4.0': 'soljson-v0.4.0+commit.acd334c9.js', - '0.3.6': 'soljson-v0.3.6+commit.3fc68da.js', - '0.3.5': 'soljson-v0.3.5+commit.5f97274.js', - '0.3.4': 'soljson-v0.3.4+commit.7dab890.js', - '0.3.3': 'soljson-v0.3.3+commit.4dc1cb1.js', - '0.3.2': 'soljson-v0.3.2+commit.81ae2a7.js', - '0.3.1': 'soljson-v0.3.1+commit.c492d9b.js', - '0.3.0': 'soljson-v0.3.0+commit.11d6736.js', - '0.2.2': 'soljson-v0.2.2+commit.ef92f56.js', - '0.2.1': 'soljson-v0.2.1+commit.91a6b35.js', - '0.2.0': 'soljson-v0.2.0+commit.4dc2445.js', - '0.1.7': 'soljson-v0.1.7+commit.b4e666c.js', - '0.1.6': 'soljson-v0.1.6+commit.d41f8b7.js', - '0.1.5': 'soljson-v0.1.5+commit.23865e3.js', - '0.1.4': 'soljson-v0.1.4+commit.5f6c3cd.js', - '0.1.3': 'soljson-v0.1.3+commit.28f561.js', - '0.1.2': 'soljson-v0.1.2+commit.d0d36e3.js', - '0.1.1': 'soljson-v0.1.1+commit.6ff4cd6.js', - }, -}; diff --git a/packages/sol-compiler/src/utils/encoder.ts b/packages/sol-compiler/src/utils/encoder.ts deleted file mode 100644 index 40b103fd55..0000000000 --- a/packages/sol-compiler/src/utils/encoder.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { AbiDefinition, AbiType, ConstructorAbi, ContractAbi, DataItem } from 'ethereum-types'; -import * as _ from 'lodash'; -import * as web3Abi from 'web3-eth-abi'; - -export const encoder = { - encodeConstructorArgsFromAbi(args: any[], abi: ContractAbi): string { - const constructorTypes: string[] = []; - _.each(abi, (element: AbiDefinition) => { - if (element.type === AbiType.Constructor) { - // tslint:disable-next-line:no-unnecessary-type-assertion - const constuctorAbi = element as ConstructorAbi; - _.each(constuctorAbi.inputs, (input: DataItem) => { - constructorTypes.push(input.type); - }); - } - }); - const encodedParameters = web3Abi.encodeParameters(constructorTypes, args); - return encodedParameters; - }, -}; diff --git a/packages/sol-compiler/src/utils/fs_wrapper.ts b/packages/sol-compiler/src/utils/fs_wrapper.ts deleted file mode 100644 index a52b509632..0000000000 --- a/packages/sol-compiler/src/utils/fs_wrapper.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { promisify } from '@0x/utils'; -import * as fs from 'fs'; -import * as mkdirp from 'mkdirp'; - -export const fsWrapper = { - readdirAsync: promisify(fs.readdir), - readFileAsync: promisify(fs.readFile), - writeFileAsync: promisify(fs.writeFile), - mkdirpAsync: promisify(mkdirp), - doesPathExistSync: fs.existsSync, - rmdirSync: fs.rmdirSync, - removeFileAsync: promisify(fs.unlink), - statAsync: promisify(fs.stat), - appendFileAsync: promisify(fs.appendFile), - accessAsync: promisify(fs.access), - doesFileExistAsync: async (filePath: string): Promise => { - try { - await fsWrapper.accessAsync( - filePath, - // node says we need to use bitwise, but tslint says no: - fs.constants.F_OK | fs.constants.R_OK, // tslint:disable-line:no-bitwise - ); - } catch (err) { - return false; - } - return true; - }, -}; diff --git a/packages/sol-compiler/src/utils/types.ts b/packages/sol-compiler/src/utils/types.ts deleted file mode 100644 index f756c51bb5..0000000000 --- a/packages/sol-compiler/src/utils/types.ts +++ /dev/null @@ -1,44 +0,0 @@ -export enum AbiType { - Function = 'function', - Constructor = 'constructor', - Event = 'event', - Fallback = 'fallback', -} - -export interface SolcErrors { - [key: string]: boolean; -} - -export interface ContractSourceData { - [contractName: string]: ContractSpecificSourceData; -} - -export interface BinaryPaths { - [key: string]: string; -} - -export interface ContractSpecificSourceData { - solcVersionRange: string; - sourceHash: Buffer; - sourceTreeHash: Buffer; -} - -export interface Token { - address?: string; - name: string; - symbol: string; - decimals: number; - ipfsHash: string; - swarmHash: string; -} - -export type DoneCallback = (err?: Error) => void; - -export class CompilationError extends Error { - public errorsCount: number; - public typeName = 'CompilationError'; - constructor(errorsCount: number) { - super('Compilation errors encountered'); - this.errorsCount = errorsCount; - } -} diff --git a/packages/sol-compiler/src/utils/utils.ts b/packages/sol-compiler/src/utils/utils.ts deleted file mode 100644 index 4f2de2caa3..0000000000 --- a/packages/sol-compiler/src/utils/utils.ts +++ /dev/null @@ -1,6 +0,0 @@ -export const utils = { - stringifyWithFormatting(obj: any): string { - const stringifiedObj = JSON.stringify(obj, null, '\t'); - return stringifiedObj; - }, -}; diff --git a/packages/sol-compiler/test/compiler_test.ts b/packages/sol-compiler/test/compiler_test.ts deleted file mode 100644 index f7086649c5..0000000000 --- a/packages/sol-compiler/test/compiler_test.ts +++ /dev/null @@ -1,165 +0,0 @@ -import { hexUtils } from '@0x/utils'; -import * as chai from 'chai'; -import { CompilerOptions, ContractArtifact } from 'ethereum-types'; -import 'mocha'; -import { join } from 'path'; - -import { Compiler } from '../src/compiler'; -import { fsWrapper } from '../src/utils/fs_wrapper'; - -import { exchange_binary } from './fixtures/exchange_bin'; -import { v6_contract_binary } from './fixtures/v6_contract_bin'; -import { v7_contract_binary } from './fixtures/v7_contract_bin'; -import { chaiSetup } from './util/chai_setup'; -import { constants } from './util/constants'; - -chaiSetup.configure(); -const expect = chai.expect; - -const METADATA_SIZE = 43; - -describe('#Compiler', function(): void { - this.timeout(constants.timeoutMs); // tslint:disable-line:no-invalid-this - const artifactsDir = `${__dirname}/fixtures/artifacts`; - const contractsDir = `${__dirname}/fixtures/contracts`; - const compilerOpts: CompilerOptions = { - artifactsDir, - contractsDir, - contracts: constants.contracts, - }; - it('should create a Compiler with empty opts', async () => { - const _compiler = new Compiler(); // tslint:disable-line no-unused-variable - }); - it('should create an Exchange artifact with the correct unlinked binary', async () => { - compilerOpts.contracts = ['Exchange']; - - const exchangeArtifactPath = `${artifactsDir}/Exchange.json`; - if (fsWrapper.doesPathExistSync(exchangeArtifactPath)) { - await fsWrapper.removeFileAsync(exchangeArtifactPath); - } - - await new Compiler(compilerOpts).compileAsync(); - - const opts = { - encoding: 'utf8', - }; - const exchangeArtifactString = await fsWrapper.readFileAsync(exchangeArtifactPath, opts); - const exchangeArtifact: ContractArtifact = JSON.parse(exchangeArtifactString); - const unlinkedBinaryWithoutMetadata = hexUtils.slice( - exchangeArtifact.compilerOutput.evm.bytecode.object, - 0, - -METADATA_SIZE, - ); - const exchangeBinaryWithoutMetadata = hexUtils.slice(exchange_binary, 0, -METADATA_SIZE); - expect(unlinkedBinaryWithoutMetadata).to.equal(exchangeBinaryWithoutMetadata); - }); - it("should throw when Whatever.sol doesn't contain a Whatever contract", async () => { - const contract = 'BadContractName'; - - const exchangeArtifactPath = `${artifactsDir}/${contract}.json`; - if (fsWrapper.doesPathExistSync(exchangeArtifactPath)) { - await fsWrapper.removeFileAsync(exchangeArtifactPath); - } - - compilerOpts.contracts = [contract]; - const compiler = new Compiler(compilerOpts); - - expect(compiler.compileAsync()).to.be.rejected(); - }); - describe('after a successful compilation', () => { - const contract = 'Exchange'; - let artifactPath: string; - let artifactCreatedAtMs: number; - beforeEach(async () => { - compilerOpts.contracts = [contract]; - - artifactPath = `${artifactsDir}/${contract}.json`; - if (fsWrapper.doesPathExistSync(artifactPath)) { - await fsWrapper.removeFileAsync(artifactPath); - } - - await new Compiler(compilerOpts).compileAsync(); - - artifactCreatedAtMs = (await fsWrapper.statAsync(artifactPath)).mtimeMs; - }); - it('recompilation should update artifact when source has changed', async () => { - // append some meaningless data to the contract, so that its hash - // will change, so that the compiler will decide to recompile it. - await fsWrapper.appendFileAsync(join(contractsDir, `${contract}.sol`), ' '); - - await new Compiler(compilerOpts).compileAsync(); - - const artifactModifiedAtMs = (await fsWrapper.statAsync(artifactPath)).mtimeMs; - - expect(artifactModifiedAtMs).to.be.greaterThan(artifactCreatedAtMs); - }); - it("recompilation should NOT update artifact when source hasn't changed", async () => { - await new Compiler(compilerOpts).compileAsync(); - - const artifactModifiedAtMs = (await fsWrapper.statAsync(artifactPath)).mtimeMs; - - expect(artifactModifiedAtMs).to.equal(artifactCreatedAtMs); - }); - }); - it('should only compile what was requested', async () => { - // remove all artifacts - for (const artifact of await fsWrapper.readdirAsync(artifactsDir)) { - await fsWrapper.removeFileAsync(join(artifactsDir, artifact)); - } - - // compile EmptyContract - compilerOpts.contracts = ['EmptyContract']; - await new Compiler(compilerOpts).compileAsync(); - - // make sure the artifacts dir only contains EmptyContract.json - for (const artifact of await fsWrapper.readdirAsync(artifactsDir)) { - expect(artifact).to.equal('EmptyContract.json'); - } - }); - it('should compile a V0.6 contract', async () => { - compilerOpts.contracts = ['V6Contract']; - - const artifactPath = `${artifactsDir}/V6Contract.json`; - if (fsWrapper.doesPathExistSync(artifactPath)) { - await fsWrapper.removeFileAsync(artifactPath); - } - - await new Compiler(compilerOpts).compileAsync(); - - const opts = { - encoding: 'utf8', - }; - const exchangeArtifactString = await fsWrapper.readFileAsync(artifactPath, opts); - const exchangeArtifact: ContractArtifact = JSON.parse(exchangeArtifactString); - const actualBinaryWithoutMetadata = hexUtils.slice( - exchangeArtifact.compilerOutput.evm.bytecode.object, - 0, - -METADATA_SIZE, - ); - const expectedBinaryWithoutMetadata = hexUtils.slice(v6_contract_binary, 0, -METADATA_SIZE); - expect(actualBinaryWithoutMetadata).to.eq(expectedBinaryWithoutMetadata); - }); - it('should compile a V0.7 contract', async () => { - compilerOpts.contracts = ['V7Contract']; - - const artifactPath = `${artifactsDir}/V7Contract.json`; - if (fsWrapper.doesPathExistSync(artifactPath)) { - await fsWrapper.removeFileAsync(artifactPath); - } - - await new Compiler(compilerOpts).compileAsync(); - - const opts = { - encoding: 'utf8', - }; - const exchangeArtifactString = await fsWrapper.readFileAsync(artifactPath, opts); - const exchangeArtifact: ContractArtifact = JSON.parse(exchangeArtifactString); - const actualBinaryWithoutMetadata = hexUtils.slice( - exchangeArtifact.compilerOutput.evm.bytecode.object, - 0, - -METADATA_SIZE, - ); - const expectedBinaryWithoutMetadata = hexUtils.slice(v7_contract_binary, 0, -METADATA_SIZE); - expect(actualBinaryWithoutMetadata).to.eq(expectedBinaryWithoutMetadata); - }); -}); diff --git a/packages/sol-compiler/test/compiler_utils_test.ts b/packages/sol-compiler/test/compiler_utils_test.ts deleted file mode 100644 index b8c18110c0..0000000000 --- a/packages/sol-compiler/test/compiler_utils_test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import * as chai from 'chai'; -import * as dirtyChai from 'dirty-chai'; -import * as _ from 'lodash'; -import 'mocha'; - -import { - createDirIfDoesNotExistAsync, - getNormalizedErrMsg, - parseDependencies, - parseSolidityVersionRange, -} from '../src/utils/compiler'; -import { fsWrapper } from '../src/utils/fs_wrapper'; - -chai.use(dirtyChai); -const expect = chai.expect; - -describe('Compiler utils', () => { - describe('#getNormalizedErrorMessage', () => { - it('normalizes the error message', () => { - const errMsg = 'base/Token.sol:6:46: Warning: Unused local variable'; - const normalizedErrMsg = getNormalizedErrMsg(errMsg); - expect(normalizedErrMsg).to.be.equal('Token.sol:6:46: Warning: Unused local variable'); - }); - }); - describe('#createDirIfDoesNotExistAsync', () => { - it('creates artifacts dir', async () => { - const artifactsDir = `${__dirname}/artifacts`; - expect(fsWrapper.doesPathExistSync(artifactsDir)).to.be.false(); - await createDirIfDoesNotExistAsync(artifactsDir); - expect(fsWrapper.doesPathExistSync(artifactsDir)).to.be.true(); - fsWrapper.rmdirSync(artifactsDir); - expect(fsWrapper.doesPathExistSync(artifactsDir)).to.be.false(); - }); - }); - describe('#parseSolidityVersionRange', () => { - it('correctly parses the version range', () => { - expect(parseSolidityVersionRange('pragma solidity ^0.0.1;')).to.be.equal('^0.0.1'); - expect(parseSolidityVersionRange('\npragma solidity 0.0.1;')).to.be.equal('0.0.1'); - expect(parseSolidityVersionRange('pragma solidity <=1.0.1;')).to.be.equal('<=1.0.1'); - expect(parseSolidityVersionRange('pragma solidity ~1.0.1;')).to.be.equal('~1.0.1'); - }); - // TODO: For now that doesn't work. This will work after we switch to a grammar-based parser - it.skip('correctly parses the version range with comments', () => { - expect(parseSolidityVersionRange('// pragma solidity ~1.0.1;\npragma solidity ~1.0.2;')).to.be.equal( - '~1.0.2', - ); - }); - }); - describe('#parseDependencies', () => { - it('correctly parses Exchange dependencies', async () => { - const path = `${__dirname}/fixtures/contracts/Exchange.sol`; - const source = await fsWrapper.readFileAsync(path, { - encoding: 'utf8', - }); - const dependencies = parseDependencies({ source, path, absolutePath: path }); - const expectedDependencies = [ - 'zeppelin-solidity/contracts/token/ERC20/ERC20.sol', - 'packages/sol-compiler/lib/test/fixtures/contracts/TokenTransferProxy.sol', - 'packages/sol-compiler/lib/test/fixtures/contracts/base/SafeMath.sol', - ]; - _.each(expectedDependencies, expectedDepdency => { - const foundDependency = _.find(dependencies, dependency => _.endsWith(dependency, expectedDepdency)); - expect(foundDependency, `${expectedDepdency} not found`).to.not.be.undefined(); - }); - }); - it('correctly parses TokenTransferProxy dependencies', async () => { - const path = `${__dirname}/fixtures/contracts/TokenTransferProxy.sol`; - const source = await fsWrapper.readFileAsync(path, { - encoding: 'utf8', - }); - expect(parseDependencies({ source, path, absolutePath: path })).to.be.deep.equal([ - 'zeppelin-solidity/contracts/ownership/Ownable.sol', - 'zeppelin-solidity/contracts/token/ERC20/ERC20.sol', - ]); - }); - // TODO: For now that doesn't work. This will work after we switch to a grammar-based parser - it.skip('correctly parses commented out dependencies', async () => { - const path = ''; - const source = `// import "./TokenTransferProxy.sol";`; - expect(parseDependencies({ path, source, absolutePath: path })).to.be.deep.equal([]); - }); - }); -}); diff --git a/packages/sol-compiler/test/fixtures/contracts/BadContractName.sol b/packages/sol-compiler/test/fixtures/contracts/BadContractName.sol deleted file mode 100644 index 3193cc0ebb..0000000000 --- a/packages/sol-compiler/test/fixtures/contracts/BadContractName.sol +++ /dev/null @@ -1,3 +0,0 @@ -pragma solidity ^0.4.14; - -contract ContractNameThatDoesntMatchFilename { } diff --git a/packages/sol-compiler/test/fixtures/contracts/EmptyContract.sol b/packages/sol-compiler/test/fixtures/contracts/EmptyContract.sol deleted file mode 100644 index 971ca7826c..0000000000 --- a/packages/sol-compiler/test/fixtures/contracts/EmptyContract.sol +++ /dev/null @@ -1,3 +0,0 @@ -pragma solidity ^0.4.14; - -contract EmptyContract { } diff --git a/packages/sol-compiler/test/fixtures/contracts/Exchange.sol b/packages/sol-compiler/test/fixtures/contracts/Exchange.sol deleted file mode 100644 index 67c6ad1d58..0000000000 --- a/packages/sol-compiler/test/fixtures/contracts/Exchange.sol +++ /dev/null @@ -1,603 +0,0 @@ -/* - - Copyright 2019 ZeroEx Intl. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -pragma solidity ^0.4.14; - -import {ERC20 as Token} from "zeppelin-solidity/contracts/token/ERC20/ERC20.sol"; - -import "./TokenTransferProxy.sol"; -import "./base/SafeMath.sol"; - -/// @title Exchange - Facilitates exchange of ERC20 tokens. -/// @author Amir Bandeali - , Will Warren - -contract Exchange is SafeMath { - - // Error Codes - enum Errors { - ORDER_EXPIRED, // Order has already expired - ORDER_FULLY_FILLED_OR_CANCELLED, // Order has already been fully filled or cancelled - ROUNDING_ERROR_TOO_LARGE, // Rounding error too large - INSUFFICIENT_BALANCE_OR_ALLOWANCE // Insufficient balance or allowance for token transfer - } - - string constant public VERSION = "1.0.0"; - uint16 constant public EXTERNAL_QUERY_GAS_LIMIT = 4999; // Changes to state require at least 5000 gas - - address public ZRX_TOKEN_CONTRACT; - address public TOKEN_TRANSFER_PROXY_CONTRACT; - - // Mappings of orderHash => amounts of takerTokenAmount filled or cancelled. - mapping (bytes32 => uint) public filled; - mapping (bytes32 => uint) public cancelled; - - event LogFill( - address indexed maker, - address taker, - address indexed feeRecipient, - address makerToken, - address takerToken, - uint filledMakerTokenAmount, - uint filledTakerTokenAmount, - uint paidMakerFee, - uint paidTakerFee, - bytes32 indexed tokens, // keccak256(makerToken, takerToken), allows subscribing to a token pair - bytes32 orderHash - ); - - event LogCancel( - address indexed maker, - address indexed feeRecipient, - address makerToken, - address takerToken, - uint cancelledMakerTokenAmount, - uint cancelledTakerTokenAmount, - bytes32 indexed tokens, - bytes32 orderHash - ); - - event LogError(uint8 indexed errorId, bytes32 indexed orderHash); - - struct Order { - address maker; - address taker; - address makerToken; - address takerToken; - address feeRecipient; - uint makerTokenAmount; - uint takerTokenAmount; - uint makerFee; - uint takerFee; - uint expirationTimestampInSec; - bytes32 orderHash; - } - - function Exchange(address _zrxToken, address _tokenTransferProxy) { - ZRX_TOKEN_CONTRACT = _zrxToken; - TOKEN_TRANSFER_PROXY_CONTRACT = _tokenTransferProxy; - } - - /* - * Core exchange functions - */ - - /// @dev Fills the input order. - /// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient. - /// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt. - /// @param fillTakerTokenAmount Desired amount of takerToken to fill. - /// @param shouldThrowOnInsufficientBalanceOrAllowance Test if transfer will fail before attempting. - /// @param v ECDSA signature parameter v. - /// @param r ECDSA signature parameters r. - /// @param s ECDSA signature parameters s. - /// @return Total amount of takerToken filled in trade. - function fillOrder( - address[5] orderAddresses, - uint[6] orderValues, - uint fillTakerTokenAmount, - bool shouldThrowOnInsufficientBalanceOrAllowance, - uint8 v, - bytes32 r, - bytes32 s) - public - returns (uint filledTakerTokenAmount) - { - Order memory order = Order({ - maker: orderAddresses[0], - taker: orderAddresses[1], - makerToken: orderAddresses[2], - takerToken: orderAddresses[3], - feeRecipient: orderAddresses[4], - makerTokenAmount: orderValues[0], - takerTokenAmount: orderValues[1], - makerFee: orderValues[2], - takerFee: orderValues[3], - expirationTimestampInSec: orderValues[4], - orderHash: getOrderHash(orderAddresses, orderValues) - }); - - require(order.taker == address(0) || order.taker == msg.sender); - require(order.makerTokenAmount > 0 && order.takerTokenAmount > 0 && fillTakerTokenAmount > 0); - require(isValidSignature( - order.maker, - order.orderHash, - v, - r, - s - )); - - if (block.timestamp >= order.expirationTimestampInSec) { - LogError(uint8(Errors.ORDER_EXPIRED), order.orderHash); - return 0; - } - - uint remainingTakerTokenAmount = safeSub(order.takerTokenAmount, getUnavailableTakerTokenAmount(order.orderHash)); - filledTakerTokenAmount = min256(fillTakerTokenAmount, remainingTakerTokenAmount); - if (filledTakerTokenAmount == 0) { - LogError(uint8(Errors.ORDER_FULLY_FILLED_OR_CANCELLED), order.orderHash); - return 0; - } - - if (isRoundingError(filledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount)) { - LogError(uint8(Errors.ROUNDING_ERROR_TOO_LARGE), order.orderHash); - return 0; - } - - if (!shouldThrowOnInsufficientBalanceOrAllowance && !isTransferable(order, filledTakerTokenAmount)) { - LogError(uint8(Errors.INSUFFICIENT_BALANCE_OR_ALLOWANCE), order.orderHash); - return 0; - } - - uint filledMakerTokenAmount = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount); - uint paidMakerFee; - uint paidTakerFee; - filled[order.orderHash] = safeAdd(filled[order.orderHash], filledTakerTokenAmount); - require(transferViaTokenTransferProxy( - order.makerToken, - order.maker, - msg.sender, - filledMakerTokenAmount - )); - require(transferViaTokenTransferProxy( - order.takerToken, - msg.sender, - order.maker, - filledTakerTokenAmount - )); - if (order.feeRecipient != address(0)) { - if (order.makerFee > 0) { - paidMakerFee = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.makerFee); - require(transferViaTokenTransferProxy( - ZRX_TOKEN_CONTRACT, - order.maker, - order.feeRecipient, - paidMakerFee - )); - } - if (order.takerFee > 0) { - paidTakerFee = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.takerFee); - require(transferViaTokenTransferProxy( - ZRX_TOKEN_CONTRACT, - msg.sender, - order.feeRecipient, - paidTakerFee - )); - } - } - - LogFill( - order.maker, - msg.sender, - order.feeRecipient, - order.makerToken, - order.takerToken, - filledMakerTokenAmount, - filledTakerTokenAmount, - paidMakerFee, - paidTakerFee, - keccak256(order.makerToken, order.takerToken), - order.orderHash - ); - return filledTakerTokenAmount; - } - - /// @dev Cancels the input order. - /// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient. - /// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt. - /// @param cancelTakerTokenAmount Desired amount of takerToken to cancel in order. - /// @return Amount of takerToken cancelled. - function cancelOrder( - address[5] orderAddresses, - uint[6] orderValues, - uint cancelTakerTokenAmount) - public - returns (uint) - { - Order memory order = Order({ - maker: orderAddresses[0], - taker: orderAddresses[1], - makerToken: orderAddresses[2], - takerToken: orderAddresses[3], - feeRecipient: orderAddresses[4], - makerTokenAmount: orderValues[0], - takerTokenAmount: orderValues[1], - makerFee: orderValues[2], - takerFee: orderValues[3], - expirationTimestampInSec: orderValues[4], - orderHash: getOrderHash(orderAddresses, orderValues) - }); - - require(order.maker == msg.sender); - require(order.makerTokenAmount > 0 && order.takerTokenAmount > 0 && cancelTakerTokenAmount > 0); - - if (block.timestamp >= order.expirationTimestampInSec) { - LogError(uint8(Errors.ORDER_EXPIRED), order.orderHash); - return 0; - } - - uint remainingTakerTokenAmount = safeSub(order.takerTokenAmount, getUnavailableTakerTokenAmount(order.orderHash)); - uint cancelledTakerTokenAmount = min256(cancelTakerTokenAmount, remainingTakerTokenAmount); - if (cancelledTakerTokenAmount == 0) { - LogError(uint8(Errors.ORDER_FULLY_FILLED_OR_CANCELLED), order.orderHash); - return 0; - } - - cancelled[order.orderHash] = safeAdd(cancelled[order.orderHash], cancelledTakerTokenAmount); - - LogCancel( - order.maker, - order.feeRecipient, - order.makerToken, - order.takerToken, - getPartialAmount(cancelledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount), - cancelledTakerTokenAmount, - keccak256(order.makerToken, order.takerToken), - order.orderHash - ); - return cancelledTakerTokenAmount; - } - - /* - * Wrapper functions - */ - - /// @dev Fills an order with specified parameters and ECDSA signature, throws if specified amount not filled entirely. - /// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient. - /// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt. - /// @param fillTakerTokenAmount Desired amount of takerToken to fill. - /// @param v ECDSA signature parameter v. - /// @param r ECDSA signature parameters r. - /// @param s ECDSA signature parameters s. - function fillOrKillOrder( - address[5] orderAddresses, - uint[6] orderValues, - uint fillTakerTokenAmount, - uint8 v, - bytes32 r, - bytes32 s) - public - { - require(fillOrder( - orderAddresses, - orderValues, - fillTakerTokenAmount, - false, - v, - r, - s - ) == fillTakerTokenAmount); - } - - /// @dev Synchronously executes multiple fill orders in a single transaction. - /// @param orderAddresses Array of address arrays containing individual order addresses. - /// @param orderValues Array of uint arrays containing individual order values. - /// @param fillTakerTokenAmounts Array of desired amounts of takerToken to fill in orders. - /// @param shouldThrowOnInsufficientBalanceOrAllowance Test if transfers will fail before attempting. - /// @param v Array ECDSA signature v parameters. - /// @param r Array of ECDSA signature r parameters. - /// @param s Array of ECDSA signature s parameters. - function batchFillOrders( - address[5][] orderAddresses, - uint[6][] orderValues, - uint[] fillTakerTokenAmounts, - bool shouldThrowOnInsufficientBalanceOrAllowance, - uint8[] v, - bytes32[] r, - bytes32[] s) - public - { - for (uint i = 0; i < orderAddresses.length; i++) { - fillOrder( - orderAddresses[i], - orderValues[i], - fillTakerTokenAmounts[i], - shouldThrowOnInsufficientBalanceOrAllowance, - v[i], - r[i], - s[i] - ); - } - } - - /// @dev Synchronously executes multiple fillOrKill orders in a single transaction. - /// @param orderAddresses Array of address arrays containing individual order addresses. - /// @param orderValues Array of uint arrays containing individual order values. - /// @param fillTakerTokenAmounts Array of desired amounts of takerToken to fill in orders. - /// @param v Array ECDSA signature v parameters. - /// @param r Array of ECDSA signature r parameters. - /// @param s Array of ECDSA signature s parameters. - function batchFillOrKillOrders( - address[5][] orderAddresses, - uint[6][] orderValues, - uint[] fillTakerTokenAmounts, - uint8[] v, - bytes32[] r, - bytes32[] s) - public - { - for (uint i = 0; i < orderAddresses.length; i++) { - fillOrKillOrder( - orderAddresses[i], - orderValues[i], - fillTakerTokenAmounts[i], - v[i], - r[i], - s[i] - ); - } - } - - /// @dev Synchronously executes multiple fill orders in a single transaction until total fillTakerTokenAmount filled. - /// @param orderAddresses Array of address arrays containing individual order addresses. - /// @param orderValues Array of uint arrays containing individual order values. - /// @param fillTakerTokenAmount Desired total amount of takerToken to fill in orders. - /// @param shouldThrowOnInsufficientBalanceOrAllowance Test if transfers will fail before attempting. - /// @param v Array ECDSA signature v parameters. - /// @param r Array of ECDSA signature r parameters. - /// @param s Array of ECDSA signature s parameters. - /// @return Total amount of fillTakerTokenAmount filled in orders. - function fillOrdersUpTo( - address[5][] orderAddresses, - uint[6][] orderValues, - uint fillTakerTokenAmount, - bool shouldThrowOnInsufficientBalanceOrAllowance, - uint8[] v, - bytes32[] r, - bytes32[] s) - public - returns (uint) - { - uint filledTakerTokenAmount = 0; - for (uint i = 0; i < orderAddresses.length; i++) { - require(orderAddresses[i][3] == orderAddresses[0][3]); // takerToken must be the same for each order - filledTakerTokenAmount = safeAdd(filledTakerTokenAmount, fillOrder( - orderAddresses[i], - orderValues[i], - safeSub(fillTakerTokenAmount, filledTakerTokenAmount), - shouldThrowOnInsufficientBalanceOrAllowance, - v[i], - r[i], - s[i] - )); - if (filledTakerTokenAmount == fillTakerTokenAmount) break; - } - return filledTakerTokenAmount; - } - - /// @dev Synchronously cancels multiple orders in a single transaction. - /// @param orderAddresses Array of address arrays containing individual order addresses. - /// @param orderValues Array of uint arrays containing individual order values. - /// @param cancelTakerTokenAmounts Array of desired amounts of takerToken to cancel in orders. - function batchCancelOrders( - address[5][] orderAddresses, - uint[6][] orderValues, - uint[] cancelTakerTokenAmounts) - public - { - for (uint i = 0; i < orderAddresses.length; i++) { - cancelOrder( - orderAddresses[i], - orderValues[i], - cancelTakerTokenAmounts[i] - ); - } - } - - /* - * Constant public functions - */ - - /// @dev Calculates Keccak-256 hash of order with specified parameters. - /// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient. - /// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt. - /// @return Keccak-256 hash of order. - function getOrderHash(address[5] orderAddresses, uint[6] orderValues) - public - constant - returns (bytes32) - { - return keccak256( - address(this), - orderAddresses[0], // maker - orderAddresses[1], // taker - orderAddresses[2], // makerToken - orderAddresses[3], // takerToken - orderAddresses[4], // feeRecipient - orderValues[0], // makerTokenAmount - orderValues[1], // takerTokenAmount - orderValues[2], // makerFee - orderValues[3], // takerFee - orderValues[4], // expirationTimestampInSec - orderValues[5] // salt - ); - } - - /// @dev Verifies that an order signature is valid. - /// @param signer address of signer. - /// @param hash Signed Keccak-256 hash. - /// @param v ECDSA signature parameter v. - /// @param r ECDSA signature parameters r. - /// @param s ECDSA signature parameters s. - /// @return Validity of order signature. - function isValidSignature( - address signer, - bytes32 hash, - uint8 v, - bytes32 r, - bytes32 s) - public - constant - returns (bool) - { - return signer == ecrecover( - keccak256("\x19Ethereum Signed Message:\n32", hash), - v, - r, - s - ); - } - - /// @dev Checks if rounding error > 0.1%. - /// @param numerator Numerator. - /// @param denominator Denominator. - /// @param target Value to multiply with numerator/denominator. - /// @return Rounding error is present. - function isRoundingError(uint numerator, uint denominator, uint target) - public - constant - returns (bool) - { - uint remainder = mulmod(target, numerator, denominator); - if (remainder == 0) return false; // No rounding error. - - uint errPercentageTimes1000000 = safeDiv( - safeMul(remainder, 1000000), - safeMul(numerator, target) - ); - return errPercentageTimes1000000 > 1000; - } - - /// @dev Calculates partial value given a numerator and denominator. - /// @param numerator Numerator. - /// @param denominator Denominator. - /// @param target Value to calculate partial of. - /// @return Partial value of target. - function getPartialAmount(uint numerator, uint denominator, uint target) - public - constant - returns (uint) - { - return safeDiv(safeMul(numerator, target), denominator); - } - - /// @dev Calculates the sum of values already filled and cancelled for a given order. - /// @param orderHash The Keccak-256 hash of the given order. - /// @return Sum of values already filled and cancelled. - function getUnavailableTakerTokenAmount(bytes32 orderHash) - public - constant - returns (uint) - { - return safeAdd(filled[orderHash], cancelled[orderHash]); - } - - - /* - * Internal functions - */ - - /// @dev Transfers a token using TokenTransferProxy transferFrom function. - /// @param token Address of token to transferFrom. - /// @param from Address transfering token. - /// @param to Address receiving token. - /// @param value Amount of token to transfer. - /// @return Success of token transfer. - function transferViaTokenTransferProxy( - address token, - address from, - address to, - uint value) - internal - returns (bool) - { - return TokenTransferProxy(TOKEN_TRANSFER_PROXY_CONTRACT).transferFrom(token, from, to, value); - } - - /// @dev Checks if any order transfers will fail. - /// @param order Order struct of params that will be checked. - /// @param fillTakerTokenAmount Desired amount of takerToken to fill. - /// @return Predicted result of transfers. - function isTransferable(Order order, uint fillTakerTokenAmount) - internal - constant // The called token contracts may attempt to change state, but will not be able to due to gas limits on getBalance and getAllowance. - returns (bool) - { - address taker = msg.sender; - uint fillMakerTokenAmount = getPartialAmount(fillTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount); - - if (order.feeRecipient != address(0)) { - bool isMakerTokenZRX = order.makerToken == ZRX_TOKEN_CONTRACT; - bool isTakerTokenZRX = order.takerToken == ZRX_TOKEN_CONTRACT; - uint paidMakerFee = getPartialAmount(fillTakerTokenAmount, order.takerTokenAmount, order.makerFee); - uint paidTakerFee = getPartialAmount(fillTakerTokenAmount, order.takerTokenAmount, order.takerFee); - uint requiredMakerZRX = isMakerTokenZRX ? safeAdd(fillMakerTokenAmount, paidMakerFee) : paidMakerFee; - uint requiredTakerZRX = isTakerTokenZRX ? safeAdd(fillTakerTokenAmount, paidTakerFee) : paidTakerFee; - - if ( getBalance(ZRX_TOKEN_CONTRACT, order.maker) < requiredMakerZRX - || getAllowance(ZRX_TOKEN_CONTRACT, order.maker) < requiredMakerZRX - || getBalance(ZRX_TOKEN_CONTRACT, taker) < requiredTakerZRX - || getAllowance(ZRX_TOKEN_CONTRACT, taker) < requiredTakerZRX - ) return false; - - if (!isMakerTokenZRX && ( getBalance(order.makerToken, order.maker) < fillMakerTokenAmount // Don't double check makerToken if ZRX - || getAllowance(order.makerToken, order.maker) < fillMakerTokenAmount) - ) return false; - if (!isTakerTokenZRX && ( getBalance(order.takerToken, taker) < fillTakerTokenAmount // Don't double check takerToken if ZRX - || getAllowance(order.takerToken, taker) < fillTakerTokenAmount) - ) return false; - } else if ( getBalance(order.makerToken, order.maker) < fillMakerTokenAmount - || getAllowance(order.makerToken, order.maker) < fillMakerTokenAmount - || getBalance(order.takerToken, taker) < fillTakerTokenAmount - || getAllowance(order.takerToken, taker) < fillTakerTokenAmount - ) return false; - - return true; - } - - /// @dev Get token balance of an address. - /// @param token Address of token. - /// @param owner Address of owner. - /// @return Token balance of owner. - function getBalance(address token, address owner) - internal - constant // The called token contract may attempt to change state, but will not be able to due to an added gas limit. - returns (uint) - { - return Token(token).balanceOf.gas(EXTERNAL_QUERY_GAS_LIMIT)(owner); // Limit gas to prevent reentrancy - } - - /// @dev Get allowance of token given to TokenTransferProxy by an address. - /// @param token Address of token. - /// @param owner Address of owner. - /// @return Allowance of token given to TokenTransferProxy by owner. - function getAllowance(address token, address owner) - internal - constant // The called token contract may attempt to change state, but will not be able to due to an added gas limit. - returns (uint) - { - return Token(token).allowance.gas(EXTERNAL_QUERY_GAS_LIMIT)(owner, TOKEN_TRANSFER_PROXY_CONTRACT); // Limit gas to prevent reentrancy - } -} diff --git a/packages/sol-compiler/test/fixtures/contracts/TokenTransferProxy.sol b/packages/sol-compiler/test/fixtures/contracts/TokenTransferProxy.sol deleted file mode 100644 index fc1cc029c2..0000000000 --- a/packages/sol-compiler/test/fixtures/contracts/TokenTransferProxy.sol +++ /dev/null @@ -1,115 +0,0 @@ -/* - - Copyright 2019 ZeroEx Intl. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -pragma solidity ^0.4.14; - -import { Ownable } from "zeppelin-solidity/contracts/ownership/Ownable.sol"; -import { ERC20 as Token } from "zeppelin-solidity/contracts/token/ERC20/ERC20.sol"; - -/// @title TokenTransferProxy - Transfers tokens on behalf of contracts that have been approved via decentralized governance. -/// @author Amir Bandeali - , Will Warren - -contract TokenTransferProxy is Ownable { - - /// @dev Only authorized addresses can invoke functions with this modifier. - modifier onlyAuthorized { - require(authorized[msg.sender]); - _; - } - - modifier targetAuthorized(address target) { - require(authorized[target]); - _; - } - - modifier targetNotAuthorized(address target) { - require(!authorized[target]); - _; - } - - mapping (address => bool) public authorized; - address[] public authorities; - - event LogAuthorizedAddressAdded(address indexed target, address indexed caller); - event LogAuthorizedAddressRemoved(address indexed target, address indexed caller); - - /* - * Public functions - */ - - /// @dev Authorizes an address. - /// @param target Address to authorize. - function addAuthorizedAddress(address target) - public - onlyOwner - targetNotAuthorized(target) - { - authorized[target] = true; - authorities.push(target); - LogAuthorizedAddressAdded(target, msg.sender); - } - - /// @dev Removes authorizion of an address. - /// @param target Address to remove authorization from. - function removeAuthorizedAddress(address target) - public - onlyOwner - targetAuthorized(target) - { - delete authorized[target]; - for (uint i = 0; i < authorities.length; i++) { - if (authorities[i] == target) { - authorities[i] = authorities[authorities.length - 1]; - authorities.length -= 1; - break; - } - } - LogAuthorizedAddressRemoved(target, msg.sender); - } - - /// @dev Calls into ERC20 Token contract, invoking transferFrom. - /// @param token Address of token to transfer. - /// @param from Address to transfer token from. - /// @param to Address to transfer token to. - /// @param value Amount of token to transfer. - /// @return Success of transfer. - function transferFrom( - address token, - address from, - address to, - uint value) - public - onlyAuthorized - returns (bool) - { - return Token(token).transferFrom(from, to, value); - } - - /* - * Public constant functions - */ - - /// @dev Gets all authorized addresses. - /// @return Array of authorized addresses. - function getAuthorizedAddresses() - public - constant - returns (address[]) - { - return authorities; - } -} diff --git a/packages/sol-compiler/test/fixtures/contracts/V6Contract.sol b/packages/sol-compiler/test/fixtures/contracts/V6Contract.sol deleted file mode 100644 index 6180d53a34..0000000000 --- a/packages/sol-compiler/test/fixtures/contracts/V6Contract.sol +++ /dev/null @@ -1,37 +0,0 @@ -/* - - Copyright 2020 ZeroEx Intl. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -pragma solidity 0.6.4; - - -contract V6Contract { - - uint256 private _privateNumber; - - constructor(uint256 privateNumber) public { - _privateNumber = privateNumber; - } - - fallback() external { - revert('nope'); - } - - receive() payable external { - // no-op - } -} diff --git a/packages/sol-compiler/test/fixtures/contracts/V7Contract.sol b/packages/sol-compiler/test/fixtures/contracts/V7Contract.sol deleted file mode 100644 index cb8561c3cf..0000000000 --- a/packages/sol-compiler/test/fixtures/contracts/V7Contract.sol +++ /dev/null @@ -1,37 +0,0 @@ -/* - - Copyright 2020 ZeroEx Intl. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -pragma solidity 0.7.0; - - -contract V7Contract { - - uint256 private _privateNumber; - - constructor(uint256 privateNumber) public { - _privateNumber = privateNumber; - } - - fallback() external { - revert('nope'); - } - - receive() payable external { - // no-op - } -} diff --git a/packages/sol-compiler/test/fixtures/contracts/base/SafeMath.sol b/packages/sol-compiler/test/fixtures/contracts/base/SafeMath.sol deleted file mode 100644 index 92ce11cded..0000000000 --- a/packages/sol-compiler/test/fixtures/contracts/base/SafeMath.sol +++ /dev/null @@ -1,41 +0,0 @@ -pragma solidity ^0.4.14; - -contract SafeMath { - function safeMul(uint a, uint b) internal constant returns (uint256) { - uint c = a * b; - assert(a == 0 || c / a == b); - return c; - } - - function safeDiv(uint a, uint b) internal constant returns (uint256) { - uint c = a / b; - return c; - } - - function safeSub(uint a, uint b) internal constant returns (uint256) { - assert(b <= a); - return a - b; - } - - function safeAdd(uint a, uint b) internal constant returns (uint256) { - uint c = a + b; - assert(c >= a); - return c; - } - - function max64(uint64 a, uint64 b) internal constant returns (uint64) { - return a >= b ? a : b; - } - - function min64(uint64 a, uint64 b) internal constant returns (uint64) { - return a < b ? a : b; - } - - function max256(uint256 a, uint256 b) internal constant returns (uint256) { - return a >= b ? a : b; - } - - function min256(uint256 a, uint256 b) internal constant returns (uint256) { - return a < b ? a : b; - } -} diff --git a/packages/sol-compiler/test/fixtures/contracts/base/Token.sol b/packages/sol-compiler/test/fixtures/contracts/base/Token.sol deleted file mode 100644 index 483010d7d1..0000000000 --- a/packages/sol-compiler/test/fixtures/contracts/base/Token.sol +++ /dev/null @@ -1,38 +0,0 @@ -pragma solidity ^0.4.14; - -contract Token { - - /// @return total amount of tokens - function totalSupply() constant returns (uint supply) {} - - /// @param _owner The address from which the balance will be retrieved - /// @return The balance - function balanceOf(address _owner) constant returns (uint balance) {} - - /// @notice send `_value` token to `_to` from `msg.sender` - /// @param _to The address of the recipient - /// @param _value The amount of token to be transferred - /// @return Whether the transfer was successful or not - function transfer(address _to, uint _value) returns (bool success) {} - - /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` - /// @param _from The address of the sender - /// @param _to The address of the recipient - /// @param _value The amount of token to be transferred - /// @return Whether the transfer was successful or not - function transferFrom(address _from, address _to, uint _value) returns (bool success) {} - - /// @notice `msg.sender` approves `_addr` to spend `_value` tokens - /// @param _spender The address of the account able to transfer the tokens - /// @param _value The amount of wei to be approved for transfer - /// @return Whether the approval was successful or not - function approve(address _spender, uint _value) returns (bool success) {} - - /// @param _owner The address of the account owning tokens - /// @param _spender The address of the account able to transfer the tokens - /// @return Amount of remaining tokens allowed to spent - function allowance(address _owner, address _spender) constant returns (uint remaining) {} - - event Transfer(address indexed _from, address indexed _to, uint _value); - event Approval(address indexed _owner, address indexed _spender, uint _value); -} diff --git a/packages/sol-compiler/test/fixtures/exchange_bin.ts b/packages/sol-compiler/test/fixtures/exchange_bin.ts deleted file mode 100644 index 9fbf9bf957..0000000000 --- a/packages/sol-compiler/test/fixtures/exchange_bin.ts +++ /dev/null @@ -1,4 +0,0 @@ -export const constructor_args = - '0x000000000000000000000000e41d2489571d322189246dafa5ebde1f4699f4980000000000000000000000008da0d80f5007ef1e431dd2127178d224e32c2ef4'; -export const exchange_binary = - '0x608060405234801561001057600080fd5b50604051604080612d998339810180604052810190808051906020019092919080519060200190929190505050816000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555080600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505050612cca806100cf6000396000f3006080604052600436106100fc576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806314df96ee14610101578063288cdc911461015a5780632ac126221461019f578063363349be146101e4578063394c21e7146103f85780633b30ba59146104975780634f150787146104ee578063741bcc931461071b5780637e9abb50146107cf5780638163681e1461081457806398024a8b146108a6578063add1cbc5146108fb578063b7b2c7d614610952578063baa0181d14610b8b578063bc61394a14610cef578063cfc4d0ec14610dc3578063f06bbf7514610e60578063ffa1ad7414610e93575b600080fd5b34801561010d57600080fd5b50610140600480360381019080803590602001909291908035906020019092919080359060200190929190505050610f23565b604051808215151515815260200191505060405180910390f35b34801561016657600080fd5b506101896004803603810190808035600019169060200190929190505050610f7b565b6040518082815260200191505060405180910390f35b3480156101ab57600080fd5b506101ce6004803603810190808035600019169060200190929190505050610f93565b6040518082815260200191505060405180910390f35b3480156101f057600080fd5b506103e260048036038101908080359060200190820180359060200190808060200260200160405190810160405280939291908181526020016000905b8282101561027257848483905060a00201600580602002604051908101604052809291908260056020028082843782019150505050508152602001906001019061022d565b5050505050919291929080359060200190820180359060200190808060200260200160405190810160405280939291908181526020016000905b828210156102f157848483905060c0020160068060200260405190810160405280929190826006602002808284378201915050505050815260200190600101906102ac565b5050505050919291929080359060200190929190803515159060200190929190803590602001908201803590602001908080602002602001604051908101604052809392919081815260200183836020028082843782019150505050505091929192908035906020019082018035906020019080806020026020016040519081016040528093929190818152602001838360200280828437820191505050505050919291929080359060200190820180359060200190808060200260200160405190810160405280939291908181526020018383602002808284378201915050505050509192919290505050610fab565b6040518082815260200191505060405180910390f35b34801561040457600080fd5b506104816004803603810190808060a001906005806020026040519081016040528092919082600560200280828437820191505050505091929192908060c0019060068060200260405190810160405280929190826006602002808284378201915050505050919291929080359060200190929190505050611110565b6040518082815260200191505060405180910390f35b3480156104a357600080fd5b506104ac6115f8565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b3480156104fa57600080fd5b5061071960048036038101908080359060200190820180359060200190808060200260200160405190810160405280939291908181526020016000905b8282101561057c57848483905060a002016005806020026040519081016040528092919082600560200280828437820191505050505081526020019060010190610537565b5050505050919291929080359060200190820180359060200190808060200260200160405190810160405280939291908181526020016000905b828210156105fb57848483905060c0020160068060200260405190810160405280929190826006602002808284378201915050505050815260200190600101906105b6565b505050505091929192908035906020019082018035906020019080806020026020016040519081016040528093929190818152602001838360200280828437820191505050505050919291929080359060200190820180359060200190808060200260200160405190810160405280939291908181526020018383602002808284378201915050505050509192919290803590602001908201803590602001908080602002602001604051908101604052809392919081815260200183836020028082843782019150505050505091929192908035906020019082018035906020019080806020026020016040519081016040528093929190818152602001838360200280828437820191505050505050919291929050505061161d565b005b34801561072757600080fd5b506107cd6004803603810190808060a001906005806020026040519081016040528092919082600560200280828437820191505050505091929192908060c0019060068060200260405190810160405280929190826006602002808284378201915050505050919291929080359060200190929190803560ff169060200190929190803560001916906020019092919080356000191690602001909291905050506116da565b005b3480156107db57600080fd5b506107fe60048036038101908080356000191690602001909291905050506116ff565b6040518082815260200191505060405180910390f35b34801561082057600080fd5b5061088c600480360381019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035600019169060200190929190803560ff16906020019092919080356000191690602001909291908035600019169060200190929190505050611748565b604051808215151515815260200191505060405180910390f35b3480156108b257600080fd5b506108e5600480360381019080803590602001909291908035906020019092919080359060200190929190505050611849565b6040518082815260200191505060405180910390f35b34801561090757600080fd5b50610910611867565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34801561095e57600080fd5b50610b8960048036038101908080359060200190820180359060200190808060200260200160405190810160405280939291908181526020016000905b828210156109e057848483905060a00201600580602002604051908101604052809291908260056020028082843782019150505050508152602001906001019061099b565b5050505050919291929080359060200190820180359060200190808060200260200160405190810160405280939291908181526020016000905b82821015610a5f57848483905060c002016006806020026040519081016040528092919082600660200280828437820191505050505081526020019060010190610a1a565b505050505091929192908035906020019082018035906020019080806020026020016040519081016040528093929190818152602001838360200280828437820191505050505050919291929080351515906020019092919080359060200190820180359060200190808060200260200160405190810160405280939291908181526020018383602002808284378201915050505050509192919290803590602001908201803590602001908080602002602001604051908101604052809392919081815260200183836020028082843782019150505050505091929192908035906020019082018035906020019080806020026020016040519081016040528093929190818152602001838360200280828437820191505050505050919291929050505061188d565b005b348015610b9757600080fd5b50610ced60048036038101908080359060200190820180359060200190808060200260200160405190810160405280939291908181526020016000905b82821015610c1957848483905060a002016005806020026040519081016040528092919082600560200280828437820191505050505081526020019060010190610bd4565b5050505050919291929080359060200190820180359060200190808060200260200160405190810160405280939291908181526020016000905b82821015610c9857848483905060c002016006806020026040519081016040528092919082600660200280828437820191505050505081526020019060010190610c53565b505050505091929192908035906020019082018035906020019080806020026020016040519081016040528093929190818152602001838360200280828437820191505050505050919291929050505061194d565b005b348015610cfb57600080fd5b50610dad6004803603810190808060a001906005806020026040519081016040528092919082600560200280828437820191505050505091929192908060c0019060068060200260405190810160405280929190826006602002808284378201915050505050919291929080359060200190929190803515159060200190929190803560ff169060200190929190803560001916906020019092919080356000191690602001909291905050506119c0565b6040518082815260200191505060405180910390f35b348015610dcf57600080fd5b50610e426004803603810190808060a001906005806020026040519081016040528092919082600560200280828437820191505050505091929192908060c00190600680602002604051908101604052809291908260066020028082843782019150505050509192919290505050612160565b60405180826000191660001916815260200191505060405180910390f35b348015610e6c57600080fd5b50610e7561240b565b604051808261ffff1661ffff16815260200191505060405180910390f35b348015610e9f57600080fd5b50610ea8612411565b6040518080602001828103825283818151815260200191508051906020019080838360005b83811015610ee8578082015181840152602081019050610ecd565b50505050905090810190601f168015610f155780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b600080600084801515610f3257fe5b86850991506000821415610f495760009250610f72565b610f68610f5983620f424061244a565b610f63888761244a565b61247d565b90506103e8811192505b50509392505050565b60026020528060005260406000206000915090505481565b60036020528060005260406000206000915090505481565b6000806000809150600090505b895181101561110057896000815181101515610fd057fe5b906020019060200201516003600581101515610fe857fe5b602002015173ffffffffffffffffffffffffffffffffffffffff168a8281518110151561101157fe5b90602001906020020151600360058110151561102957fe5b602002015173ffffffffffffffffffffffffffffffffffffffff1614151561105057600080fd5b6110e4826110df8c8481518110151561106557fe5b906020019060200201518c8581518110151561107d57fe5b906020019060200201516110918d88612498565b8c8c888151811015156110a057fe5b906020019060200201518c898151811015156110b857fe5b906020019060200201518c8a8151811015156110d057fe5b906020019060200201516119c0565b6124b1565b9150878214156110f357611100565b8080600101915050610fb8565b8192505050979650505050505050565b600061111a612bd2565b6000806101606040519081016040528088600060058110151561113957fe5b602002015173ffffffffffffffffffffffffffffffffffffffff16815260200188600160058110151561116857fe5b602002015173ffffffffffffffffffffffffffffffffffffffff16815260200188600260058110151561119757fe5b602002015173ffffffffffffffffffffffffffffffffffffffff1681526020018860036005811015156111c657fe5b602002015173ffffffffffffffffffffffffffffffffffffffff1681526020018860046005811015156111f557fe5b602002015173ffffffffffffffffffffffffffffffffffffffff16815260200187600060068110151561122457fe5b6020020151815260200187600160068110151561123d57fe5b6020020151815260200187600260068110151561125657fe5b6020020151815260200187600360068110151561126f57fe5b6020020151815260200187600460068110151561128857fe5b6020020151815260200161129c8989612160565b6000191681525092503373ffffffffffffffffffffffffffffffffffffffff16836000015173ffffffffffffffffffffffffffffffffffffffff161415156112e357600080fd5b60008360a001511180156112fb575060008360c00151115b80156113075750600085115b151561131257600080fd5b8261012001514210151561136f57826101400151600019166000600381111561133757fe5b60ff167f36d86c59e00bd73dc19ba3adfe068e4b64ac7e92be35546adeddf1b956a87e9060405160405180910390a3600093506115ee565b61138a8360c001516113858561014001516116ff565b612498565b915061139685836124cf565b905060008114156113f05782610140015160001916600160038111156113b857fe5b60ff167f36d86c59e00bd73dc19ba3adfe068e4b64ac7e92be35546adeddf1b956a87e9060405160405180910390a3600093506115ee565b61141a600360008561014001516000191660001916815260200190815260200160002054826124b1565b60036000856101400151600019166000191681526020019081526020016000208190555082604001518360600151604051808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166c010000000000000000000000000281526014018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166c0100000000000000000000000002815260140192505050604051809103902060001916836080015173ffffffffffffffffffffffffffffffffffffffff16846000015173ffffffffffffffffffffffffffffffffffffffff167f67d66f160bc93d925d05dae1794c90d2d6d6688b29b84ff069398a9b0458713186604001518760600151611552878a60c001518b60a00151611849565b878a6101400151604051808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200184815260200183815260200182600019166000191681526020019550505050505060405180910390a48093505b5050509392505050565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60008090505b86518110156116d1576116c4878281518110151561163d57fe5b90602001906020020151878381518110151561165557fe5b90602001906020020151878481518110151561166d57fe5b90602001906020020151878581518110151561168557fe5b90602001906020020151878681518110151561169d57fe5b9060200190602002015187878151811015156116b557fe5b906020019060200201516116da565b8080600101915050611623565b50505050505050565b836116eb87878760008888886119c0565b1415156116f757600080fd5b505050505050565b600061174160026000846000191660001916815260200190815260200160002054600360008560001916600019168152602001908152602001600020546124b1565b9050919050565b600060018560405180807f19457468657265756d205369676e6564204d6573736167653a0a333200000000815250601c0182600019166000191681526020019150506040518091039020858585604051600081526020016040526040518085600019166000191681526020018460ff1660ff1681526020018360001916600019168152602001826000191660001916815260200194505050505060206040516020810390808403906000865af1158015611806573d6000803e3d6000fd5b5050506020604051035173ffffffffffffffffffffffffffffffffffffffff168673ffffffffffffffffffffffffffffffffffffffff1614905095945050505050565b600061185e611858858461244a565b8461247d565b90509392505050565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60008090505b87518110156119435761193588828151811015156118ad57fe5b9060200190602002015188838151811015156118c557fe5b9060200190602002015188848151811015156118dd57fe5b906020019060200201518888868151811015156118f657fe5b90602001906020020151888781518110151561190e57fe5b90602001906020020151888881518110151561192657fe5b906020019060200201516119c0565b508080600101915050611893565b5050505050505050565b60008090505b83518110156119ba576119ac848281518110151561196d57fe5b90602001906020020151848381518110151561198557fe5b90602001906020020151848481518110151561199d57fe5b90602001906020020151611110565b508080600101915050611953565b50505050565b60006119ca612bd2565b600080600080610160604051908101604052808e60006005811015156119ec57fe5b602002015173ffffffffffffffffffffffffffffffffffffffff1681526020018e6001600581101515611a1b57fe5b602002015173ffffffffffffffffffffffffffffffffffffffff1681526020018e6002600581101515611a4a57fe5b602002015173ffffffffffffffffffffffffffffffffffffffff1681526020018e6003600581101515611a7957fe5b602002015173ffffffffffffffffffffffffffffffffffffffff1681526020018e6004600581101515611aa857fe5b602002015173ffffffffffffffffffffffffffffffffffffffff1681526020018d6000600681101515611ad757fe5b602002015181526020018d6001600681101515611af057fe5b602002015181526020018d6002600681101515611b0957fe5b602002015181526020018d6003600681101515611b2257fe5b602002015181526020018d6004600681101515611b3b57fe5b60200201518152602001611b4f8f8f612160565b600019168152509450600073ffffffffffffffffffffffffffffffffffffffff16856020015173ffffffffffffffffffffffffffffffffffffffff161480611bc657503373ffffffffffffffffffffffffffffffffffffffff16856020015173ffffffffffffffffffffffffffffffffffffffff16145b1515611bd157600080fd5b60008560a00151118015611be9575060008560c00151115b8015611bf5575060008b115b1515611c0057600080fd5b611c1685600001518661014001518b8b8b611748565b1515611c2157600080fd5b84610120015142101515611c7e578461014001516000191660006003811115611c4657fe5b60ff167f36d86c59e00bd73dc19ba3adfe068e4b64ac7e92be35546adeddf1b956a87e9060405160405180910390a360009550612150565b611c998560c00151611c948761014001516116ff565b612498565b9350611ca58b856124cf565b95506000861415611cff578461014001516000191660016003811115611cc757fe5b60ff167f36d86c59e00bd73dc19ba3adfe068e4b64ac7e92be35546adeddf1b956a87e9060405160405180910390a360009550612150565b611d12868660c001518760a00151610f23565b15611d66578461014001516000191660026003811115611d2e57fe5b60ff167f36d86c59e00bd73dc19ba3adfe068e4b64ac7e92be35546adeddf1b956a87e9060405160405180910390a360009550612150565b89158015611d7b5750611d7985876124e8565b155b15611dce5784610140015160001916600380811115611d9657fe5b60ff167f36d86c59e00bd73dc19ba3adfe068e4b64ac7e92be35546adeddf1b956a87e9060405160405180910390a360009550612150565b611de1868660c001518760a00151611849565b9250611e0d600260008761014001516000191660001916815260200190815260200160002054876124b1565b600260008761014001516000191660001916815260200190815260200160002081905550611e45856040015186600001513386612838565b1515611e5057600080fd5b611e64856060015133876000015189612838565b1515611e6f57600080fd5b600073ffffffffffffffffffffffffffffffffffffffff16856080015173ffffffffffffffffffffffffffffffffffffffff16141515611f6e5760008560e001511115611f0c57611ec9868660c001518760e00151611849565b9150611f006000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff168660000151876080015185612838565b1515611f0b57600080fd5b5b60008561010001511115611f6d57611f2e868660c00151876101000151611849565b9050611f616000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1633876080015184612838565b1515611f6c57600080fd5b5b5b84604001518560600151604051808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166c010000000000000000000000000281526014018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166c0100000000000000000000000002815260140192505050604051809103902060001916856080015173ffffffffffffffffffffffffffffffffffffffff16866000015173ffffffffffffffffffffffffffffffffffffffff167f0d0b9391970d9a25552f37d436d2aae2925e2bfe1b2a923754bada030c498cb33389604001518a60600151898d8a8a8f6101400151604051808973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200186815260200185815260200184815260200183815260200182600019166000191681526020019850505050505050505060405180910390a48595505b5050505050979650505050505050565b60003083600060058110151561217257fe5b602002015184600160058110151561218657fe5b602002015185600260058110151561219a57fe5b60200201518660036005811015156121ae57fe5b60200201518760046005811015156121c257fe5b60200201518760006006811015156121d657fe5b60200201518860016006811015156121ea57fe5b60200201518960026006811015156121fe57fe5b60200201518a600360068110151561221257fe5b60200201518b600460068110151561222657fe5b60200201518c600560068110151561223a57fe5b6020020151604051808d73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166c010000000000000000000000000281526014018c73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166c010000000000000000000000000281526014018b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166c010000000000000000000000000281526014018a73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166c010000000000000000000000000281526014018973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166c010000000000000000000000000281526014018873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166c010000000000000000000000000281526014018781526020018681526020018581526020018481526020018381526020018281526020019c505050505050505050505050506040518091039020905092915050565b61138781565b6040805190810160405280600581526020017f312e302e3000000000000000000000000000000000000000000000000000000081525081565b6000808284029050600084148061246b575082848281151561246857fe5b04145b151561247357fe5b8091505092915050565b600080828481151561248b57fe5b0490508091505092915050565b60008282111515156124a657fe5b818303905092915050565b60008082840190508381101515156124c557fe5b8091505092915050565b60008183106124de57816124e0565b825b905092915050565b600080600080600080600080600033975061250c8a8c60c001518d60a00151611849565b9650600073ffffffffffffffffffffffffffffffffffffffff168b6080015173ffffffffffffffffffffffffffffffffffffffff161415156127b9576000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168b6040015173ffffffffffffffffffffffffffffffffffffffff161495506000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168b6060015173ffffffffffffffffffffffffffffffffffffffff161494506126078a8c60c001518d60e00151611849565b935061261d8a8c60c001518d6101000151611849565b92508561262a5783612635565b61263487856124b1565b5b915084612642578261264d565b61264c8a846124b1565b5b90508161267f6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff168d600001516129ac565b10806126b85750816126b66000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff168d60000151612a94565b105b806126ec5750806126ea6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff168a6129ac565b105b8061272057508061271e6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff168a612a94565b105b1561272e576000985061282a565b8515801561276757508661274a8c604001518d600001516129ac565b10806127665750866127648c604001518d60000151612a94565b105b5b15612775576000985061282a565b841580156127a657508961278d8c606001518a6129ac565b10806127a55750896127a38c606001518a612a94565b105b5b156127b4576000985061282a565b612825565b866127cc8c604001518d600001516129ac565b10806127e85750866127e68c604001518d60000151612a94565b105b806127ff5750896127fd8c606001518a6129ac565b105b806128165750896128148c606001518a612a94565b105b15612824576000985061282a565b5b600198505b505050505050505092915050565b6000600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166315dacbea868686866040518563ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001828152602001945050505050602060405180830381600087803b15801561296757600080fd5b505af115801561297b573d6000803e3d6000fd5b505050506040513d602081101561299157600080fd5b81019080805190602001909291905050509050949350505050565b60008273ffffffffffffffffffffffffffffffffffffffff166370a0823161138761ffff16846040518363ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001915050602060405180830381600088803b158015612a5057600080fd5b5087f1158015612a64573d6000803e3d6000fd5b50505050506040513d6020811015612a7b57600080fd5b8101908080519060200190929190505050905092915050565b60008273ffffffffffffffffffffffffffffffffffffffff1663dd62ed3e61138761ffff1684600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff166040518463ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200192505050602060405180830381600088803b158015612b8e57600080fd5b5087f1158015612ba2573d6000803e3d6000fd5b50505050506040513d6020811015612bb957600080fd5b8101908080519060200190929190505050905092915050565b61016060405190810160405280600073ffffffffffffffffffffffffffffffffffffffff168152602001600073ffffffffffffffffffffffffffffffffffffffff168152602001600073ffffffffffffffffffffffffffffffffffffffff168152602001600073ffffffffffffffffffffffffffffffffffffffff168152602001600073ffffffffffffffffffffffffffffffffffffffff16815260200160008152602001600081526020016000815260200160008152602001600081526020016000801916815250905600a165627a7a72305820f91599ebd80f85632ef190bb5e1a738e7288d68a2cf9dcc6b579d76b892dcf6f0029'; diff --git a/packages/sol-compiler/test/fixtures/v6_contract_bin.ts b/packages/sol-compiler/test/fixtures/v6_contract_bin.ts deleted file mode 100644 index 04cfbcc143..0000000000 --- a/packages/sol-compiler/test/fixtures/v6_contract_bin.ts +++ /dev/null @@ -1,2 +0,0 @@ -export const v6_contract_binary = - '0x6080604052348015600f57600080fd5b5060405161011238038061011283398181016040526020811015603157600080fd5b8101908080519060200190929190505050806000819055505060ba806100586000396000f3fe608060405236600a57005b348015601557600080fd5b506040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260048152602001807f6e6f70650000000000000000000000000000000000000000000000000000000081525060200191505060405180910390fdfea26469706673582212208084a572151fb41e40aa4d1197e387cba7b4f0cbd982e34682974038667b564764736f6c63430006040033'; diff --git a/packages/sol-compiler/test/fixtures/v7_contract_bin.ts b/packages/sol-compiler/test/fixtures/v7_contract_bin.ts deleted file mode 100644 index abb3b6a407..0000000000 --- a/packages/sol-compiler/test/fixtures/v7_contract_bin.ts +++ /dev/null @@ -1,2 +0,0 @@ -export const v7_contract_binary = - '0x6080604052348015600f57600080fd5b5060405161011238038061011283398181016040526020811015603157600080fd5b8101908080519060200190929190505050806000819055505060ba806100586000396000f3fe608060405236600a57005b348015601557600080fd5b506040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260048152602001807f6e6f70650000000000000000000000000000000000000000000000000000000081525060200191505060405180910390fdfea2646970667358221220d498aaab2683da1af2092969c6d8a0c3d992a9a9a0a5d19b54b5e704ab8fd5e364736f6c63430007000033'; diff --git a/packages/sol-compiler/test/util/chai_setup.ts b/packages/sol-compiler/test/util/chai_setup.ts deleted file mode 100644 index 1a87330932..0000000000 --- a/packages/sol-compiler/test/util/chai_setup.ts +++ /dev/null @@ -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); - }, -}; diff --git a/packages/sol-compiler/test/util/constants.ts b/packages/sol-compiler/test/util/constants.ts deleted file mode 100644 index f408e99d43..0000000000 --- a/packages/sol-compiler/test/util/constants.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { BigNumber } from '@0x/utils'; - -export const constants = { - optimizerEnabled: false, - gasPrice: new BigNumber(20000000000), - timeoutMs: 30000, - zrxTokenAddress: '0xe41d2489571d322189246dafa5ebde1f4699f498', - tokenTransferProxyAddress: '0x8da0d80f5007ef1e431dd2127178d224e32c2ef4', - contracts: '*' as '*', -}; diff --git a/packages/sol-compiler/test/util/provider.ts b/packages/sol-compiler/test/util/provider.ts deleted file mode 100644 index ab706bf641..0000000000 --- a/packages/sol-compiler/test/util/provider.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { web3Factory } from '@0x/dev-utils'; -import Web3ProviderEngine = require('web3-provider-engine'); - -const providerConfigs = { shouldUseInProcessGanache: true }; -const provider: Web3ProviderEngine = web3Factory.getRpcProvider(providerConfigs); - -export { provider }; diff --git a/packages/sol-compiler/tsconfig.json b/packages/sol-compiler/tsconfig.json deleted file mode 100644 index c6ffbb99b9..0000000000 --- a/packages/sol-compiler/tsconfig.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "extends": "../../tsconfig", - "compilerOptions": { - "outDir": "lib", - "rootDir": ".", - "strictFunctionTypes": false - }, - "include": ["./src/**/*", "./test/**/*"] -} diff --git a/packages/sol-compiler/tslint.json b/packages/sol-compiler/tslint.json deleted file mode 100644 index dd9053357e..0000000000 --- a/packages/sol-compiler/tslint.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": ["@0x/tslint-config"] -} diff --git a/packages/sol-compiler/typedoc-tsconfig.json b/packages/sol-compiler/typedoc-tsconfig.json deleted file mode 100644 index 22897c1315..0000000000 --- a/packages/sol-compiler/typedoc-tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../typedoc-tsconfig", - "compilerOptions": { - "outDir": "lib", - "strictFunctionTypes": false - }, - "include": ["./src/**/*", "./test/**/*"] -} diff --git a/packages/sol-coverage/.npmignore b/packages/sol-coverage/.npmignore deleted file mode 100644 index ea588d4859..0000000000 --- a/packages/sol-coverage/.npmignore +++ /dev/null @@ -1,9 +0,0 @@ -# Blacklist all files -.* -* -# Whitelist lib -!lib/**/* -# Blacklist tests and publish scripts -/lib/test/* -/lib/monorepo_scripts/ -# Package specific ignore diff --git a/packages/sol-coverage/CHANGELOG.json b/packages/sol-coverage/CHANGELOG.json deleted file mode 100644 index 8af1365808..0000000000 --- a/packages/sol-coverage/CHANGELOG.json +++ /dev/null @@ -1,372 +0,0 @@ -[ - { - "timestamp": 1594788383, - "version": "4.0.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1592969527, - "version": "4.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1582623685, - "version": "4.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1581204851, - "version": "4.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1580988106, - "version": "4.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1580811564, - "version": "4.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1579682890, - "version": "4.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1578272714, - "version": "4.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1576540892, - "version": "4.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1575931811, - "version": "4.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "4.0.0", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1575296764 - }, - { - "version": "3.1.0-beta.4", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1575290197 - }, - { - "version": "3.1.0-beta.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1574238768 - }, - { - "version": "3.1.0-beta.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1574030254 - }, - { - "version": "3.1.0-beta.1", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1573159180 - }, - { - "version": "3.1.0-beta.0", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1570135330 - }, - { - "timestamp": 1568744790, - "version": "3.0.12", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1567521715, - "version": "3.0.11", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1566446343, - "version": "3.0.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1565296576, - "version": "3.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1564604963, - "version": "3.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563957393, - "version": "3.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563006338, - "version": "3.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1558712885, - "version": "3.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1557507213, - "version": "3.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1554997931 - }, - { - "timestamp": 1553183790, - "version": "3.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1553091633, - "version": "3.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.0.0", - "changes": [ - { - "note": "Change the interface to accept a configuration object instead of `isVerbose`", - "pr": 1656 - }, - { - "note": "Add `ignoreFilesGlobs` property on a config object", - "pr": 1656 - }, - { - "note": "Allow project specific coverage ignore paths by specifying `config.ignoreFilesGlobs`", - "pr": 1656 - } - ], - "timestamp": 1551479279 - }, - { - "timestamp": 1551299797, - "version": "2.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551220833, - "version": "2.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551130135, - "version": "2.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1549733923, - "version": "2.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1549547375 - }, - { - "timestamp": 1549452781, - "version": "2.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.0", - "changes": [ - { - "note": "Upgrade the bignumber.js to v8.0.2", - "pr": 1517 - } - ], - "timestamp": 1549373905 - }, - { - "timestamp": 1547747677, - "version": "1.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547561734, - "version": "1.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547225310, - "version": "1.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.0", - "changes": [ - { - "note": "Initial release as a separate package. For historical entries see @0x/sol-tracing-utils", - "pr": 1492 - } - ] - } -] diff --git a/packages/sol-coverage/CHANGELOG.md b/packages/sol-coverage/CHANGELOG.md deleted file mode 100644 index 1178888889..0000000000 --- a/packages/sol-coverage/CHANGELOG.md +++ /dev/null @@ -1,168 +0,0 @@ - - -CHANGELOG - -## v4.0.10 - _July 15, 2020_ - - * Dependencies updated - -## v4.0.9 - _June 24, 2020_ - - * Dependencies updated - -## v4.0.8 - _February 25, 2020_ - - * Dependencies updated - -## v4.0.7 - _February 8, 2020_ - - * Dependencies updated - -## v4.0.6 - _February 6, 2020_ - - * Dependencies updated - -## v4.0.5 - _February 4, 2020_ - - * Dependencies updated - -## v4.0.4 - _January 22, 2020_ - - * Dependencies updated - -## v4.0.3 - _January 6, 2020_ - - * Dependencies updated - -## v4.0.2 - _December 17, 2019_ - - * Dependencies updated - -## v4.0.1 - _December 9, 2019_ - - * Dependencies updated - -## v4.0.0 - _December 2, 2019_ - - * Dependencies updated - -## v3.1.0-beta.4 - _December 2, 2019_ - - * Dependencies updated - -## v3.1.0-beta.3 - _November 20, 2019_ - - * Dependencies updated - -## v3.1.0-beta.2 - _November 17, 2019_ - - * Dependencies updated - -## v3.1.0-beta.1 - _November 7, 2019_ - - * Dependencies updated - -## v3.1.0-beta.0 - _October 3, 2019_ - - * Dependencies updated - -## v3.0.12 - _September 17, 2019_ - - * Dependencies updated - -## v3.0.11 - _September 3, 2019_ - - * Dependencies updated - -## v3.0.10 - _August 22, 2019_ - - * Dependencies updated - -## v3.0.9 - _August 8, 2019_ - - * Dependencies updated - -## v3.0.8 - _July 31, 2019_ - - * Dependencies updated - -## v3.0.7 - _July 24, 2019_ - - * Dependencies updated - -## v3.0.6 - _July 13, 2019_ - - * Dependencies updated - -## v3.0.5 - _May 24, 2019_ - - * Dependencies updated - -## v3.0.4 - _May 10, 2019_ - - * Dependencies updated - -## v3.0.3 - _April 11, 2019_ - - * Dependencies updated - -## v3.0.2 - _March 21, 2019_ - - * Dependencies updated - -## v3.0.1 - _March 20, 2019_ - - * Dependencies updated - -## v3.0.0 - _March 1, 2019_ - - * Change the interface to accept a configuration object instead of `isVerbose` (#1656) - * Add `ignoreFilesGlobs` property on a config object (#1656) - * Allow project specific coverage ignore paths by specifying `config.ignoreFilesGlobs` (#1656) - -## v2.0.6 - _February 27, 2019_ - - * Dependencies updated - -## v2.0.5 - _February 26, 2019_ - - * Dependencies updated - -## v2.0.4 - _February 25, 2019_ - - * Dependencies updated - -## v2.0.3 - _February 9, 2019_ - - * Dependencies updated - -## v2.0.2 - _February 7, 2019_ - - * Dependencies updated - -## v2.0.1 - _February 6, 2019_ - - * Dependencies updated - -## v2.0.0 - _February 5, 2019_ - - * Upgrade the bignumber.js to v8.0.2 (#1517) - -## v1.0.3 - _January 17, 2019_ - - * Dependencies updated - -## v1.0.2 - _January 15, 2019_ - - * Dependencies updated - -## v1.0.1 - _January 11, 2019_ - - * Dependencies updated - -## v1.0.0 - _Invalid date_ - - * Initial release as a separate package. For historical entries see @0x/sol-tracing-utils (#1492) diff --git a/packages/sol-coverage/README.md b/packages/sol-coverage/README.md deleted file mode 100644 index 2c84e80745..0000000000 --- a/packages/sol-coverage/README.md +++ /dev/null @@ -1,75 +0,0 @@ -## @0x/sol-coverage - -A Solidity code coverage tool. - -### Read the [Documentation](https://0x.org/docs/tools/sol-coverage). - -## Installation - -```bash -yarn add @0x/sol-coverage -``` - -**Import** - -```javascript -import { CoverageSubprovider } from '@0x/sol-coverage'; -``` - -or - -```javascript -var CoverageSubprovider = require('@0x/sol-coverage').CoverageSubprovider; -``` - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install dependencies - -If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: - -```bash -yarn config set workspaces-experimental true -``` - -Then install dependencies - -```bash -yarn install -``` - -### Build - -To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory: - -```bash -PKG=@0x/sol-coverage yarn build -``` - -Or continuously rebuild on change: - -```bash -PKG=@0x/sol-coverage yarn watch -``` - -### Clean - -```bash -yarn clean -``` - -### Lint - -```bash -yarn lint -``` - -### Run Tests - -```bash -yarn test -``` diff --git a/packages/sol-coverage/docs/reference.mdx b/packages/sol-coverage/docs/reference.mdx deleted file mode 100644 index a1c4d94dbd..0000000000 --- a/packages/sol-coverage/docs/reference.mdx +++ /dev/null @@ -1,744 +0,0 @@ - - -# Class: AbstractArtifactAdapter - - -## Methods - -### `Abstract` collectContractsDataAsync - -▸ **collectContractsDataAsync**(): *`Promise`* - -*Defined in [sol-tracing-utils/src/artifact_adapters/abstract_artifact_adapter.ts:4](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-tracing-utils/src/artifact_adapters/abstract_artifact_adapter.ts#L4)* - -**Returns:** *`Promise`* - -
- -# Class: SolCompilerArtifactAdapter - - -## Constructors - - - -\+ **new SolCompilerArtifactAdapter**(`artifactsPath?`: undefined | string, `sourcesPath?`: undefined | string): *[SolCompilerArtifactAdapter](#class-solcompilerartifactadapter)* - -*Defined in [sol-tracing-utils/src/artifact_adapters/sol_compiler_artifact_adapter.ts:18](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-tracing-utils/src/artifact_adapters/sol_compiler_artifact_adapter.ts#L18)* - -Instantiates a SolCompilerArtifactAdapter - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`artifactsPath?` | undefined \| string | Path to your artifacts directory | -`sourcesPath?` | undefined \| string | Path to your contract sources directory | - -**Returns:** *[SolCompilerArtifactAdapter](#class-solcompilerartifactadapter)* - -## Methods - -### collectContractsDataAsync - -▸ **collectContractsDataAsync**(): *`Promise`* - -*Overrides [AbstractArtifactAdapter](_sol_tracing_utils_src_artifact_adapters_abstract_artifact_adapter_.abstractartifactadapter.md).[collectContractsDataAsync](#abstract-collectcontractsdataasync)* - -*Defined in [sol-tracing-utils/src/artifact_adapters/sol_compiler_artifact_adapter.ts:44](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-tracing-utils/src/artifact_adapters/sol_compiler_artifact_adapter.ts#L44)* - -**Returns:** *`Promise`* - -
- -# Class: TruffleArtifactAdapter - - -## Constructors - - - -\+ **new TruffleArtifactAdapter**(`projectRoot`: string, `solcVersion`: string): *[TruffleArtifactAdapter](#class-truffleartifactadapter)* - -*Defined in [sol-tracing-utils/src/artifact_adapters/truffle_artifact_adapter.ts:29](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-tracing-utils/src/artifact_adapters/truffle_artifact_adapter.ts#L29)* - -Instantiates a TruffleArtifactAdapter - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`projectRoot` | string | Path to the truffle project's root directory | -`solcVersion` | string | Solidity version with which to compile all the contracts | - -**Returns:** *[TruffleArtifactAdapter](#class-truffleartifactadapter)* - -## Methods - -### collectContractsDataAsync - -▸ **collectContractsDataAsync**(): *`Promise`* - -*Overrides [AbstractArtifactAdapter](_sol_tracing_utils_src_artifact_adapters_abstract_artifact_adapter_.abstractartifactadapter.md).[collectContractsDataAsync](#abstract-collectcontractsdataasync)* - -*Defined in [sol-tracing-utils/src/artifact_adapters/truffle_artifact_adapter.ts:40](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-tracing-utils/src/artifact_adapters/truffle_artifact_adapter.ts#L40)* - -**Returns:** *`Promise`* - -
- - - - - - - - - - - - - - - - - - - - -## Type aliases - -### Callback - -Ƭ **Callback**: *function* - -*Defined in [subproviders/src/types.ts:131](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L131)* - -#### Type declaration: - -▸ (): *void* - -___ - - - -### ErrorCallback - -Ƭ **ErrorCallback**: *function* - -*Defined in [subproviders/src/types.ts:130](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L130)* - -#### Type declaration: - -▸ (`err`: `Error` | null, `data?`: any): *void* - -**Parameters:** - -Name | Type | ------- | ------ | -`err` | `Error` \| null | -`data?` | any | - -___ - - - -### NextCallback - -Ƭ **NextCallback**: *function* - -*Defined in [subproviders/src/types.ts:133](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L133)* - -#### Type declaration: - -▸ (`callback?`: [OnNextCompleted](#onnextcompleted)): *void* - -**Parameters:** - -Name | Type | ------- | ------ | -`callback?` | [OnNextCompleted](#onnextcompleted) | - -___ - -### OnNextCompleted - -Ƭ **OnNextCompleted**: *function* - -*Defined in [subproviders/src/types.ts:132](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L132)* - -#### Type declaration: - -▸ (`err`: `Error` | null, `result`: any, `cb`: [Callback](#callback)): *void* - -**Parameters:** - -Name | Type | ------- | ------ | -`err` | `Error` \| null | -`result` | any | -`cb` | [Callback](#callback) | - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# Interface: JSONRPCRequestPayload - - -## Properties - -### id - -• **id**: *number* - -*Defined in [ethereum-types/src/index.ts:331](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L331)* - -___ - -### jsonrpc - -• **jsonrpc**: *string* - -*Defined in [ethereum-types/src/index.ts:332](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L332)* - -___ - -### method - -• **method**: *string* - -*Defined in [ethereum-types/src/index.ts:330](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L330)* - -___ - -### params - -• **params**: *any[]* - -*Defined in [ethereum-types/src/index.ts:329](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L329)* - -
- -# Interface: JSONRPCResponseError - - -## Properties - -### code - -• **code**: *number* - -*Defined in [ethereum-types/src/index.ts:337](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L337)* - -___ - -### message - -• **message**: *string* - -*Defined in [ethereum-types/src/index.ts:336](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L336)* - -
- -# Interface: JSONRPCResponsePayload - - -## Properties - -### `Optional` error - -• **error**? : *[JSONRPCResponseError](#class-jsonrpcresponseerror)* - -*Defined in [ethereum-types/src/index.ts:344](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L344)* - -___ - -### id - -• **id**: *number* - -*Defined in [ethereum-types/src/index.ts:342](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L342)* - -___ - -### jsonrpc - -• **jsonrpc**: *string* - -*Defined in [ethereum-types/src/index.ts:343](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L343)* - -___ - -### result - -• **result**: *any* - -*Defined in [ethereum-types/src/index.ts:341](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L341)* - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# Class: CoverageSubprovider - -This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface. -It's used to compute your code coverage while running solidity tests. - - -## Constructors - - - -\+ **new CoverageSubprovider**(`artifactAdapter`: `AbstractArtifactAdapter`, `defaultFromAddress`: string, `partialConfig`: [CoverageSubproviderPartialConfig](#coveragesubproviderpartialconfig)): *[CoverageSubprovider](#class-coveragesubprovider)* - -*Overrides void* - -*Defined in [sol-coverage/src/coverage_subprovider.ts:44](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-coverage/src/coverage_subprovider.ts#L44)* - -Instantiates a CoverageSubprovider instance - -**Parameters:** - -Name | Type | Default | Description | ------- | ------ | ------ | ------ | -`artifactAdapter` | `AbstractArtifactAdapter` | - | Adapter for used artifacts format (0x, truffle, giveth, etc.) | -`defaultFromAddress` | string | - | default from address to use when sending transactions | -`partialConfig` | [CoverageSubproviderPartialConfig](#coveragesubproviderpartialconfig) | {} | Partial configuration object | - -**Returns:** *[CoverageSubprovider](#class-coveragesubprovider)* - -## Methods - -### emitPayloadAsync - -▸ **emitPayloadAsync**(`payload`: `Partial`): *`Promise`* - - - -Defined in subproviders/lib/src/subproviders/subprovider.d.ts:25 - -Emits a JSON RPC payload that will then be handled by the ProviderEngine instance -this subprovider is a part of. The payload will cascade down the subprovider middleware -stack until finding the responsible entity for handling the request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `Partial` | JSON RPC payload | - -**Returns:** *`Promise`* - -JSON RPC response payload - -___ - -### handleRequest - -▸ **handleRequest**(`payload`: `JSONRPCRequestPayload`, `next`: [NextCallback](#nextcallback), `_end`: [ErrorCallback](#errorcallback)): *`Promise`* - - - -*Overrides void* - -Defined in sol-tracing-utils/lib/src/trace_collection_subprovider.d.ts:42 - -This method conforms to the web3-provider-engine interface. -It is called internally by the ProviderEngine when it is this subproviders -turn to handle a JSON RPC request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `JSONRPCRequestPayload` | JSON RPC payload | -`next` | [NextCallback](#nextcallback) | Callback to call if this subprovider decides not to handle the request | -`_end` | [ErrorCallback](#errorcallback) | Callback to call if subprovider handled the request and wants to pass back the request. | - -**Returns:** *`Promise`* - -___ - -### setEngine - -▸ **setEngine**(`engine`: `Web3ProviderEngine`): *void* - - - -*Overrides void* - -Defined in sol-tracing-utils/lib/src/trace_collection_subprovider.d.ts:49 - -Set's the subprovider's engine to the ProviderEngine it is added to. -This is only called within the ProviderEngine source code, do not call -directly. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`engine` | `Web3ProviderEngine` | The ProviderEngine this subprovider is added to | - -**Returns:** *void* - -___ - -### start - -▸ **start**(): *void* - - - -Defined in sol-tracing-utils/lib/src/trace_collection_subprovider.d.ts:29 - -Starts trace collection - -**Returns:** *void* - -___ - -### stop - -▸ **stop**(): *void* - - - -Defined in sol-tracing-utils/lib/src/trace_collection_subprovider.d.ts:33 - -Stops trace collection - -**Returns:** *void* - -___ - -### writeCoverageAsync - -▸ **writeCoverageAsync**(): *`Promise`* - -*Defined in [sol-coverage/src/coverage_subprovider.ts:78](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-coverage/src/coverage_subprovider.ts#L78)* - -Write the test coverage results to a file in Istanbul format. - -**Returns:** *`Promise`* - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# Interface: JSONRPCRequestPayloadWithMethod - - -## Properties - -### id - -• **id**: *number* - - - -Defined in ethereum-types/lib/index.d.ts:268 - -___ - -### jsonrpc - -• **jsonrpc**: *string* - - - -Defined in ethereum-types/lib/index.d.ts:269 - -___ - -### method - -• **method**: *string* - -*Overrides void* - -*Defined in [subproviders/src/types.ts:136](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L136)* - -___ - -### params - -• **params**: *any[]* - - - -Defined in ethereum-types/lib/index.d.ts:266 - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -## Type aliases - - - - - - - - - - - - -## Type aliases - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -## Type aliases - -### CoverageSubproviderPartialConfig - -Ƭ **CoverageSubproviderPartialConfig**: *`Partial`* - -*Defined in [sol-coverage/src/coverage_subprovider.ts:31](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-coverage/src/coverage_subprovider.ts#L31)* - -## Object literals - -### `Const` DEFAULT_COVERAGE_SUBPROVIDER_CONFIG - -#### ▪ **DEFAULT_COVERAGE_SUBPROVIDER_CONFIG**: *object* - -*Defined in [sol-coverage/src/coverage_subprovider.ts:33](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-coverage/src/coverage_subprovider.ts#L33)* - -#### ignoreFilesGlobs - -• **ignoreFilesGlobs**: *never[]* = [] - -*Defined in [sol-coverage/src/coverage_subprovider.ts:35](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-coverage/src/coverage_subprovider.ts#L35)* - -#### isVerbose - -• **isVerbose**: *boolean* = true - -*Defined in [sol-coverage/src/coverage_subprovider.ts:34](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-coverage/src/coverage_subprovider.ts#L34)* - -
- - - -
- - - -
- - - -
- diff --git a/packages/sol-coverage/package.json b/packages/sol-coverage/package.json deleted file mode 100644 index 53e3513af6..0000000000 --- a/packages/sol-coverage/package.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "name": "@0x/sol-coverage", - "version": "4.0.10", - "engines": { - "node": ">=6.12" - }, - "description": "Generate coverage reports for Solidity code", - "main": "lib/src/index.js", - "types": "lib/src/index.d.ts", - "scripts": { - "build": "tsc -b", - "build:ci": "yarn build", - "lint": "tslint --format stylish --project .", - "fix": "tslint --fix --format stylish --project .", - "clean": "shx rm -rf lib src/artifacts generated_docs", - "diff_docs": "git diff --exit-code ./docs", - "s3:sync_md_docs": "aws s3 sync ./docs s3://docs-markdown/${npm_package_name}/v${npm_package_version} --profile 0xproject --region us-east-1 --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers", - "docs:md": "ts-doc-gen --sourceDir='$PROJECT_FILES' --output=$MD_FILE_DIR --fileExtension=mdx --tsconfig=./typedoc-tsconfig.json", - "docs:json": "typedoc --excludePrivate --excludeExternals --excludeProtected --ignoreCompilerErrors --target ES5 --tsconfig typedoc-tsconfig.json --json $JSON_FILE_PATH $PROJECT_FILES" - }, - "config": { - "postpublish": { - "assets": [] - } - }, - "repository": { - "type": "git", - "url": "https://github.com/0xProject/0x-monorepo.git" - }, - "license": "Apache-2.0", - "bugs": { - "url": "https://github.com/0xProject/0x-monorepo/issues" - }, - "homepage": "https://github.com/0xProject/0x-monorepo/packages/sol-coverage/README.md", - "dependencies": { - "@0x/sol-tracing-utils": "^7.1.0", - "@0x/subproviders": "^6.1.1", - "@0x/typescript-typings": "^5.1.1", - "@types/minimatch": "^3.0.3", - "ethereum-types": "^3.2.0", - "lodash": "^4.17.11", - "minimatch": "^3.0.4", - "web3-provider-engine": "14.0.6" - }, - "devDependencies": { - "@0x/ts-doc-gen": "^0.0.22", - "@0x/tslint-config": "^4.1.0", - "@types/node": "12.12.54", - "@types/web3-provider-engine": "^14.0.0", - "npm-run-all": "^4.1.2", - "nyc": "^11.0.1", - "shx": "^0.2.2", - "sinon": "^4.0.0", - "tslint": "5.11.0", - "typedoc": "^0.15.0", - "typescript": "3.0.1" - }, - "publishConfig": { - "access": "public" - }, - "gitHead": "4f91bfd907996b2f4dd383778b50c479c2602b56" -} diff --git a/packages/sol-coverage/src/coverage_subprovider.ts b/packages/sol-coverage/src/coverage_subprovider.ts deleted file mode 100644 index fe7780f32e..0000000000 --- a/packages/sol-coverage/src/coverage_subprovider.ts +++ /dev/null @@ -1,188 +0,0 @@ -import { - AbstractArtifactAdapter, - BranchCoverage, - collectCoverageEntries, - ContractData, - Coverage, - FunctionCoverage, - FunctionDescription, - SourceRange, - StatementCoverage, - StatementDescription, - Subtrace, - SubTraceInfo, - TraceCollector, - TraceInfoSubprovider, - utils, -} from '@0x/sol-tracing-utils'; -import * as _ from 'lodash'; -import * as minimatch from 'minimatch'; - -/** - * This type defines the schema of the config object that could be passed to CoverageSubprovider - * isVerbose: If true - will log any unknown transactions. Defaults to true. - * ignoreFilesGlobs: The list of globs matching the file names of the files we want to ignore coverage for. Defaults to []. - */ -export interface CoverageSubproviderConfig { - isVerbose: boolean; - ignoreFilesGlobs: string[]; -} - -export type CoverageSubproviderPartialConfig = Partial; - -export const DEFAULT_COVERAGE_SUBPROVIDER_CONFIG = { - isVerbose: true, - ignoreFilesGlobs: [], -}; - -/** - * This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface. - * It's used to compute your code coverage while running solidity tests. - */ -export class CoverageSubprovider extends TraceInfoSubprovider { - private readonly _coverageCollector: TraceCollector; - private readonly _coverageSubproviderCnfig: CoverageSubproviderConfig; - /** - * Instantiates a CoverageSubprovider instance - * @param artifactAdapter Adapter for used artifacts format (0x, truffle, giveth, etc.) - * @param defaultFromAddress default from address to use when sending transactions - * @param partialConfig Partial configuration object - */ - constructor( - artifactAdapter: AbstractArtifactAdapter, - defaultFromAddress: string, - partialConfig: CoverageSubproviderPartialConfig = {}, - ) { - const traceCollectionSubproviderConfig = { - shouldCollectTransactionTraces: true, - shouldCollectGasEstimateTraces: true, - shouldCollectCallTraces: true, - }; - super(defaultFromAddress, traceCollectionSubproviderConfig); - this._coverageSubproviderCnfig = { - ...DEFAULT_COVERAGE_SUBPROVIDER_CONFIG, - ...partialConfig, - }; - this._coverageCollector = new TraceCollector( - artifactAdapter, - this._coverageSubproviderCnfig.isVerbose, - this._coverageHandler.bind(this), - ); - } - protected async _handleSubTraceInfoAsync(subTraceInfo: SubTraceInfo): Promise { - await this._coverageCollector.computeSingleTraceCoverageAsync(subTraceInfo); - } - /** - * Write the test coverage results to a file in Istanbul format. - */ - public async writeCoverageAsync(): Promise { - await this._coverageCollector.writeOutputAsync(); - } - private _isFileIgnored(absoluteFileName: string): boolean { - for (const ignoreFilesGlob of this._coverageSubproviderCnfig.ignoreFilesGlobs) { - if (minimatch(absoluteFileName, ignoreFilesGlob)) { - return true; - } - } - return false; - } - /** - * Computes partial coverage for a single file & subtrace. - * @param contractData Contract metadata (source, srcMap, bytecode) - * @param subtrace A subset of a transcation/call trace that was executed within that contract - * @param pcToSourceRange A mapping from program counters to source ranges - * @param fileIndex Index of a file to compute coverage for - * @return Partial istanbul coverage for that file & subtrace - */ - private _coverageHandler( - contractData: ContractData, - subtrace: Subtrace, - pcToSourceRange: { [programCounter: number]: SourceRange }, - fileIndex: number, - ): Coverage { - const absoluteFileName = contractData.sources[fileIndex]; - if (this._isFileIgnored(absoluteFileName)) { - return {}; - } - const coverageEntriesDescription = collectCoverageEntries(contractData.sourceCodes[fileIndex], IGNORE_REGEXP); - - // if the source wasn't provided for the fileIndex, we can't cover the file - if (coverageEntriesDescription === undefined) { - return {}; - } - - let sourceRanges = _.map(subtrace, structLog => pcToSourceRange[structLog.pc]); - sourceRanges = _.compact(sourceRanges); // Some PC's don't map to a source range and we just ignore them. - // By default lodash does a shallow object comparison. We JSON.stringify them and compare as strings. - sourceRanges = _.uniqBy(sourceRanges, s => JSON.stringify(s)); // We don't care if one PC was covered multiple times within a single transaction - sourceRanges = _.filter(sourceRanges, sourceRange => sourceRange.fileName === absoluteFileName); - const branchCoverage: BranchCoverage = {}; - const branchIds = _.keys(coverageEntriesDescription.branchMap); - for (const branchId of branchIds) { - const branchDescription = coverageEntriesDescription.branchMap[branchId]; - const branchIndexToIsBranchCovered = _.map(branchDescription.locations, location => { - const isBranchCovered = _.some(sourceRanges, range => utils.isRangeInside(range.location, location)); - const timesBranchCovered = Number(isBranchCovered); - return timesBranchCovered; - }); - branchCoverage[branchId] = branchIndexToIsBranchCovered; - } - const statementCoverage: StatementCoverage = {}; - const statementIds = _.keys(coverageEntriesDescription.statementMap); - for (const statementId of statementIds) { - const statementDescription = coverageEntriesDescription.statementMap[statementId]; - const isStatementCovered = _.some(sourceRanges, range => - utils.isRangeInside(range.location, statementDescription), - ); - const timesStatementCovered = Number(isStatementCovered); - statementCoverage[statementId] = timesStatementCovered; - } - const functionCoverage: FunctionCoverage = {}; - const functionIds = _.keys(coverageEntriesDescription.fnMap); - for (const fnId of functionIds) { - const functionDescription = coverageEntriesDescription.fnMap[fnId]; - const isFunctionCovered = _.some(sourceRanges, range => - utils.isRangeInside(range.location, functionDescription.loc), - ); - const timesFunctionCovered = Number(isFunctionCovered); - functionCoverage[fnId] = timesFunctionCovered; - } - // HACK: Solidity doesn't emit any opcodes that map back to modifiers with no args, that's why we map back to the - // function range and check if there is any covered statement within that range. - for (const modifierStatementId of coverageEntriesDescription.modifiersStatementIds) { - if (statementCoverage[modifierStatementId]) { - // Already detected as covered - continue; - } - const modifierDescription = coverageEntriesDescription.statementMap[modifierStatementId]; - const enclosingFunction = _.find(coverageEntriesDescription.fnMap, functionDescription => - utils.isRangeInside(modifierDescription, functionDescription.loc), - ) as FunctionDescription; - const isModifierCovered = _.some( - coverageEntriesDescription.statementMap, - (statementDescription: StatementDescription, statementId: number) => { - const isInsideTheModifierEnclosingFunction = utils.isRangeInside( - statementDescription, - enclosingFunction.loc, - ); - const isCovered = statementCoverage[statementId]; - return isInsideTheModifierEnclosingFunction && isCovered; - }, - ); - const timesModifierCovered = Number(isModifierCovered); - statementCoverage[modifierStatementId] = timesModifierCovered; - } - const partialCoverage = { - [absoluteFileName]: { - ...coverageEntriesDescription, - path: absoluteFileName, - f: functionCoverage, - s: statementCoverage, - b: branchCoverage, - }, - }; - return partialCoverage; - } -} - -const IGNORE_REGEXP = /\/\*\s*solcov\s+ignore\s+next\s*\*\/\s*/gm; diff --git a/packages/sol-coverage/src/globals.d.ts b/packages/sol-coverage/src/globals.d.ts deleted file mode 100644 index e799b35298..0000000000 --- a/packages/sol-coverage/src/globals.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// tslint:disable:completed-docs -declare module '*.json' { - const json: any; - /* tslint:disable */ - export default json; - /* tslint:enable */ -} diff --git a/packages/sol-coverage/src/index.ts b/packages/sol-coverage/src/index.ts deleted file mode 100644 index 9852345247..0000000000 --- a/packages/sol-coverage/src/index.ts +++ /dev/null @@ -1,26 +0,0 @@ -export { - CoverageSubprovider, - CoverageSubproviderConfig, - DEFAULT_COVERAGE_SUBPROVIDER_CONFIG, - CoverageSubproviderPartialConfig, -} from './coverage_subprovider'; -export { - SolCompilerArtifactAdapter, - TruffleArtifactAdapter, - AbstractArtifactAdapter, - ContractData, - SourceCodes, - Sources, -} from '@0x/sol-tracing-utils'; - -export { JSONRPCRequestPayload, JSONRPCResponsePayload, JSONRPCResponseError } from 'ethereum-types'; - -export { - JSONRPCRequestPayloadWithMethod, - NextCallback, - ErrorCallback, - OnNextCompleted, - Callback, -} from '@0x/subproviders'; - -export import Web3ProviderEngine = require('web3-provider-engine'); diff --git a/packages/sol-coverage/tsconfig.json b/packages/sol-coverage/tsconfig.json deleted file mode 100644 index 233008d61c..0000000000 --- a/packages/sol-coverage/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../tsconfig", - "compilerOptions": { - "outDir": "lib", - "rootDir": "." - }, - "include": ["./src/**/*"] -} diff --git a/packages/sol-coverage/tslint.json b/packages/sol-coverage/tslint.json deleted file mode 100644 index dd9053357e..0000000000 --- a/packages/sol-coverage/tslint.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": ["@0x/tslint-config"] -} diff --git a/packages/sol-coverage/typedoc-tsconfig.json b/packages/sol-coverage/typedoc-tsconfig.json deleted file mode 100644 index c9b0af1ae6..0000000000 --- a/packages/sol-coverage/typedoc-tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "../../typedoc-tsconfig", - "compilerOptions": { - "outDir": "lib" - }, - "include": ["./src/**/*", "./test/**/*"] -} diff --git a/packages/sol-doc/.npmignore b/packages/sol-doc/.npmignore deleted file mode 100644 index 1db0c99870..0000000000 --- a/packages/sol-doc/.npmignore +++ /dev/null @@ -1,12 +0,0 @@ -# Blacklist all files -.* -* -# Whitelist lib -!lib/**/* -# Blacklist tests and publish scripts -/lib/test/* -/lib/monorepo_scripts/ -# Package specific ignore -/docs -# Whitelist bin -!bin/**/* diff --git a/packages/sol-doc/CHANGELOG.json b/packages/sol-doc/CHANGELOG.json deleted file mode 100644 index 232ed7a6ab..0000000000 --- a/packages/sol-doc/CHANGELOG.json +++ /dev/null @@ -1,473 +0,0 @@ -[ - { - "timestamp": 1594788383, - "version": "3.1.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1592969527, - "version": "3.1.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.1.6", - "changes": [ - { - "note": "Include `bin` files" - } - ], - "timestamp": 1582677073 - }, - { - "timestamp": 1582623685, - "version": "3.1.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1581204851, - "version": "3.1.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1580988106, - "version": "3.1.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1580811564, - "version": "3.1.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1579682890, - "version": "3.1.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.1.0", - "changes": [ - { - "note": "Rewrite the whole thing to use custom AST walker.", - "pr": 2391 - } - ], - "timestamp": 1578272714 - }, - { - "timestamp": 1576540892, - "version": "3.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1575931811, - "version": "3.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.0.0", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1575296764 - }, - { - "version": "2.1.0-beta.4", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1575290197 - }, - { - "version": "2.1.0-beta.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1574238768 - }, - { - "version": "2.1.0-beta.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1574030254 - }, - { - "version": "2.1.0-beta.1", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1573159180 - }, - { - "version": "2.1.0-beta.0", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1570135330 - }, - { - "timestamp": 1568744790, - "version": "2.0.19", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1567521715, - "version": "2.0.18", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1566446343, - "version": "2.0.17", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1565296576, - "version": "2.0.16", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1564604963, - "version": "2.0.15", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563957393, - "version": "2.0.14", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.13", - "changes": [ - { - "note": "Confirm devdoc components exist before using them", - "pr": 1878 - } - ], - "timestamp": 1563006338 - }, - { - "timestamp": 1558712885, - "version": "2.0.12", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1557507213, - "version": "2.0.11", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.10", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1554997931 - }, - { - "timestamp": 1553183790, - "version": "2.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1553091633, - "version": "2.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551479279, - "version": "2.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551299797, - "version": "2.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551220833, - "version": "2.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551130135, - "version": "2.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1549733923, - "version": "2.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1549547375 - }, - { - "timestamp": 1549452781, - "version": "2.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.0", - "changes": [ - { - "note": "Upgrade the bignumber.js to v8.0.2", - "pr": 1517 - } - ], - "timestamp": 1549373905 - }, - { - "timestamp": 1547561734, - "version": "1.0.14", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547225310, - "version": "1.0.13", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547040760, - "version": "1.0.12", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.11", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544739608 - }, - { - "version": "1.0.10", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544570656 - }, - { - "timestamp": 1543401373, - "version": "1.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542821676, - "version": "1.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542208198, - "version": "1.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542134075, - "version": "1.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542028948, - "version": "1.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1541740904 - }, - { - "timestamp": 1539871071, - "version": "1.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1538693146 - }, - { - "timestamp": 1538157789, - "version": "1.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.0", - "changes": [ - { - "note": "Utility to generate documentation for Solidity smart contracts, outputting a format compliant with @0xproject/types.DocAgnosticFormat", - "pr": 1004 - } - ] - } -] diff --git a/packages/sol-doc/CHANGELOG.md b/packages/sol-doc/CHANGELOG.md deleted file mode 100644 index 9b2b699fc9..0000000000 --- a/packages/sol-doc/CHANGELOG.md +++ /dev/null @@ -1,214 +0,0 @@ - - -CHANGELOG - -## v3.1.8 - _July 15, 2020_ - - * Dependencies updated - -## v3.1.7 - _June 24, 2020_ - - * Dependencies updated - -## v3.1.6 - _February 26, 2020_ - - * Include `bin` files - -## v3.1.5 - _February 25, 2020_ - - * Dependencies updated - -## v3.1.4 - _February 8, 2020_ - - * Dependencies updated - -## v3.1.3 - _February 6, 2020_ - - * Dependencies updated - -## v3.1.2 - _February 4, 2020_ - - * Dependencies updated - -## v3.1.1 - _January 22, 2020_ - - * Dependencies updated - -## v3.1.0 - _January 6, 2020_ - - * Rewrite the whole thing to use custom AST walker. (#2391) - -## v3.0.2 - _December 17, 2019_ - - * Dependencies updated - -## v3.0.1 - _December 9, 2019_ - - * Dependencies updated - -## v3.0.0 - _December 2, 2019_ - - * Dependencies updated - -## v2.1.0-beta.4 - _December 2, 2019_ - - * Dependencies updated - -## v2.1.0-beta.3 - _November 20, 2019_ - - * Dependencies updated - -## v2.1.0-beta.2 - _November 17, 2019_ - - * Dependencies updated - -## v2.1.0-beta.1 - _November 7, 2019_ - - * Dependencies updated - -## v2.1.0-beta.0 - _October 3, 2019_ - - * Dependencies updated - -## v2.0.19 - _September 17, 2019_ - - * Dependencies updated - -## v2.0.18 - _September 3, 2019_ - - * Dependencies updated - -## v2.0.17 - _August 22, 2019_ - - * Dependencies updated - -## v2.0.16 - _August 8, 2019_ - - * Dependencies updated - -## v2.0.15 - _July 31, 2019_ - - * Dependencies updated - -## v2.0.14 - _July 24, 2019_ - - * Dependencies updated - -## v2.0.13 - _July 13, 2019_ - - * Confirm devdoc components exist before using them (#1878) - -## v2.0.12 - _May 24, 2019_ - - * Dependencies updated - -## v2.0.11 - _May 10, 2019_ - - * Dependencies updated - -## v2.0.10 - _April 11, 2019_ - - * Dependencies updated - -## v2.0.9 - _March 21, 2019_ - - * Dependencies updated - -## v2.0.8 - _March 20, 2019_ - - * Dependencies updated - -## v2.0.7 - _March 1, 2019_ - - * Dependencies updated - -## v2.0.6 - _February 27, 2019_ - - * Dependencies updated - -## v2.0.5 - _February 26, 2019_ - - * Dependencies updated - -## v2.0.4 - _February 25, 2019_ - - * Dependencies updated - -## v2.0.3 - _February 9, 2019_ - - * Dependencies updated - -## v2.0.2 - _February 7, 2019_ - - * Dependencies updated - -## v2.0.1 - _February 6, 2019_ - - * Dependencies updated - -## v2.0.0 - _February 5, 2019_ - - * Upgrade the bignumber.js to v8.0.2 (#1517) - -## v1.0.14 - _January 15, 2019_ - - * Dependencies updated - -## v1.0.13 - _January 11, 2019_ - - * Dependencies updated - -## v1.0.12 - _January 9, 2019_ - - * Dependencies updated - -## v1.0.11 - _December 13, 2018_ - - * Dependencies updated - -## v1.0.10 - _December 11, 2018_ - - * Dependencies updated - -## v1.0.9 - _November 28, 2018_ - - * Dependencies updated - -## v1.0.8 - _November 21, 2018_ - - * Dependencies updated - -## v1.0.7 - _November 14, 2018_ - - * Dependencies updated - -## v1.0.6 - _November 13, 2018_ - - * Dependencies updated - -## v1.0.5 - _November 12, 2018_ - - * Dependencies updated - -## v1.0.4 - _November 9, 2018_ - - * Dependencies updated - -## v1.0.3 - _October 18, 2018_ - - * Dependencies updated - -## v1.0.2 - _October 4, 2018_ - - * Dependencies updated - -## v1.0.1 - _September 28, 2018_ - - * Dependencies updated - -## v1.0.0 - _Invalid date_ - - * Utility to generate documentation for Solidity smart contracts, outputting a format compliant with @0xproject/types.DocAgnosticFormat (#1004) diff --git a/packages/sol-doc/bin/sol-doc.js b/packages/sol-doc/bin/sol-doc.js deleted file mode 100755 index 35c9ae735a..0000000000 --- a/packages/sol-doc/bin/sol-doc.js +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/env node -require('../lib/src/cli.js'); diff --git a/packages/sol-doc/coverage/.gitkeep b/packages/sol-doc/coverage/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/sol-doc/package.json b/packages/sol-doc/package.json deleted file mode 100644 index 9d1aac3ed4..0000000000 --- a/packages/sol-doc/package.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "name": "@0x/sol-doc", - "version": "3.1.8", - "description": "Solidity documentation generator", - "main": "lib/src/index.js", - "types": "lib/src/index.d.js", - "scripts": { - "start": "node ./lib/src/cli.js", - "build": "tsc", - "build:ci": "yarn build", - "test": "mocha --require source-map-support/register --require make-promises-safe lib/test/**/*_test.js --timeout 6000 --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", - "lint": "tslint --format stylish --project .", - "fix": "tslint --fix --format stylish --project .", - "clean": "shx rm -rf lib docs/*", - "generate-protocol-docs": "COMMIT=`git rev-parse --short HEAD`; mkdir -p ${npm_package_config_outputDir}; yarn start `echo ${npm_package_config_sources} | sed -r 's/(\\S+?)\\b/--source \\1/g'` --root ../../ --root ../../node_modules/@0x/contracts-=contracts/ `echo ${npm_package_config_contracts} | sed -r 's/(\\w+?)\\b/--contract \\1/g'` --md ${npm_package_config_outputDir}/reference.mdx --md-url-prefix \"${npm_package_config_repoBlobRoot}/${COMMIT}\"", - "s3:sync_md_docs": "aws s3 sync ${npm_package_config_outputDir} s3://docs-markdown/${npm_package_config_s3DocsPath} --profile 0xproject --region us-east-1 --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers" - }, - "config": { - "outputDir": "./docs", - "repoBlobRoot": "https://github.com/0xProject/0x-monorepo/blob", - "sources": "../../contracts/exchange/contracts/src/Exchange.sol ../../contracts/exchange-forwarder/contracts/src/Forwarder.sol ../../contracts/staking/contracts/src/Staking.sol ../../contracts/coordinator/contracts/src/Coordinator.sol", - "contracts": "Exchange Forwarder Staking Coordinator", - "s3DocsPath": "@0x/contracts-docs/v3.0.0" - }, - "bin": { - "sol-doc": "bin/sol-doc.js" - }, - "repository": "https://github.com/0xProject/0x-monorepo.git", - "author": "F. Eugene Aumson", - "license": "Apache-2.0", - "dependencies": { - "@0x/sol-compiler": "^4.1.1", - "@0x/types": "^3.2.0", - "@0x/utils": "^5.5.1", - "ethereum-types": "^3.2.0", - "ethereumjs-util": "^5.1.1", - "glob": "^7.1.2", - "yargs": "^10.0.3" - }, - "devDependencies": { - "@0x/dev-utils": "^3.3.0", - "@0x/tslint-config": "^4.1.0", - "@types/mocha": "^5.2.7", - "chai": "^4.0.1", - "chai-as-promised": "^7.1.0", - "chai-bignumber": "^3.0.0", - "dirty-chai": "^2.0.1", - "lodash": "^4.17.11", - "make-promises-safe": "^1.1.0", - "mocha": "^6.2.0", - "shx": "^0.2.2", - "source-map-support": "^0.5.0", - "tslint": "5.11.0" - }, - "publishConfig": { - "access": "public" - }, - "gitHead": "4f91bfd907996b2f4dd383778b50c479c2602b56" -} diff --git a/packages/sol-doc/src/cli.ts b/packages/sol-doc/src/cli.ts deleted file mode 100644 index 0f68a3d8a7..0000000000 --- a/packages/sol-doc/src/cli.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { logUtils } from '@0x/utils'; -import * as fs from 'fs'; -import * as glob from 'glob'; -import 'source-map-support/register'; -import { promisify } from 'util'; -import * as yargs from 'yargs'; - -import { extractDocsAsync } from './extract_docs'; -import { generateMarkdownFromDocs } from './gen_md'; -import { transformDocs } from './transform_docs'; - -const JSON_TAB_WIDTH = 2; - -(async () => { - const argv = yargs - .option('source', { - type: 'string', - array: true, - description: 'glob paths of source files to compile', - demandOption: true, - }) - .option('contract', { - type: 'string', - array: true, - description: 'generate docs for only a contract', - }) - .option('complete', { - type: 'boolean', - description: 'generate docs for all contracts and private methods', - }) - .option('noFlatten', { - type: 'boolean', - description: 'do not merge inherited contracts', - }) - .option('json', { - type: 'string', - description: 'file to save JSON to', - }) - .option('root', { - type: 'string', - array: true, - description: 'rewrite paths as relative to these directory', - }) - .option('md', { - type: 'string', - description: 'file to save markdown to', - }) - .option('mdUrlPrefix', { - type: 'string', - description: 'prefix for markdown links', - }) - .help().argv; - const sources = await getContractsAsync(argv.source); - if (!sources.length) { - throw new Error('no sources found'); - } - const docs = transformDocs(await extractDocsAsync(sources, argv.root), { - onlyExposed: !argv.complete, - flatten: !argv.noFlatten, - contracts: argv.contract, - }); - if (argv.json) { - await writeTextFileAsync(argv.json, JSON.stringify(docs, null, JSON_TAB_WIDTH)); - } - if (argv.md) { - await writeTextFileAsync(argv.md, generateMarkdownFromDocs(docs, { urlPrefix: argv.mdUrlPrefix })); - } -})().catch(err => { - logUtils.warn(err); - process.exit(1); -}); - -async function getContractsAsync(contractsGlobs: string[]): Promise { - let sources: string[] = []; - for (const g of contractsGlobs) { - sources = [...sources, ...(await promisify(glob)(g))]; - } - return sources; -} - -async function writeTextFileAsync(file: string, content: string): Promise { - return promisify(fs.writeFile)(file, content, { encoding: 'utf-8' }); -} diff --git a/packages/sol-doc/src/extract_docs.ts b/packages/sol-doc/src/extract_docs.ts deleted file mode 100644 index 3b9b71ea26..0000000000 --- a/packages/sol-doc/src/extract_docs.ts +++ /dev/null @@ -1,638 +0,0 @@ -import { Compiler } from '@0x/sol-compiler'; -import * as fs from 'fs'; -import * as path from 'path'; -import { promisify } from 'util'; - -import { - ArrayTypeNameNode, - AstNode, - ContractKind, - EnumValueNode, - FunctionKind, - isArrayTypeNameNode, - isContractDefinitionNode, - isEnumDefinitionNode, - isEventDefinitionNode, - isFunctionDefinitionNode, - isMappingTypeNameNode, - isSourceUnitNode, - isStructDefinitionNode, - isUserDefinedTypeNameNode, - isVariableDeclarationNode, - MappingTypeNameNode, - ParameterListNode, - SourceUnitNode, - splitAstNodeSrc, - StateMutability, - StorageLocation, - TypeNameNode, - VariableDeclarationNode, - Visibility, -} from './sol_ast'; - -export { ContractKind, FunctionKind, StateMutability, StorageLocation, Visibility } from './sol_ast'; - -export interface DocumentedItem { - doc: string; - line: number; - file: string; -} - -export interface EnumValueDocs extends DocumentedItem { - value: number; -} - -export interface ParamDocs extends DocumentedItem { - type: string; - indexed: boolean; - storageLocation: StorageLocation; - order: number; -} - -export interface ParamDocsMap { - [name: string]: ParamDocs; -} - -export interface EnumValueDocsMap { - [name: string]: EnumValueDocs; -} - -export interface MethodDocs extends DocumentedItem { - name: string; - contract: string; - stateMutability: string; - visibility: Visibility; - isAccessor: boolean; - kind: FunctionKind; - parameters: ParamDocsMap; - returns: ParamDocsMap; -} - -export interface EnumDocs extends DocumentedItem { - contract: string; - values: EnumValueDocsMap; -} - -export interface StructDocs extends DocumentedItem { - contract: string; - fields: ParamDocsMap; -} - -export interface EventDocs extends DocumentedItem { - contract: string; - name: string; - parameters: ParamDocsMap; -} - -export interface ContractDocs extends DocumentedItem { - kind: ContractKind; - inherits: string[]; - methods: MethodDocs[]; - events: EventDocs[]; - enums: { - [typeName: string]: EnumDocs; - }; - structs: { - [typeName: string]: StructDocs; - }; -} - -export interface SolidityDocs { - contracts: { - [typeName: string]: ContractDocs; - }; -} - -interface SolcOutput { - sources: { [file: string]: { id: number; ast: SourceUnitNode } }; - contracts: { - [file: string]: { - [contract: string]: { - metadata: string; - }; - }; - }; -} - -interface ContractMetadata { - sources: { [file: string]: { content: string } }; - settings: { remappings: string[] }; -} - -interface SourceData { - path: string; - content: string; -} - -interface Natspec { - comment: string; - dev: string; - params: { [name: string]: string }; - returns: { [name: string]: string }; -} - -/** - * Extract documentation, as JSON, from contract files. - */ -export async function extractDocsAsync(contractPaths: string[], roots: string[] = []): Promise { - const outputs = await compileAsync(contractPaths); - const sourceContents = (await Promise.all(outputs.map(getSourceContentsFromCompilerOutputAsync))).map(sources => - rewriteSourcePaths(sources, roots), - ); - const docs = createEmptyDocs(); - outputs.forEach((output, outputIdx) => { - for (const file of Object.keys(output.contracts)) { - const fileDocs = extractDocsFromFile( - output.sources[file].ast, - sourceContents[outputIdx][output.sources[file].id], - ); - mergeDocs(docs, fileDocs); - } - }); - return docs; -} - -async function compileAsync(files: string[]): Promise { - const compiler = new Compiler({ - contracts: files, - compilerSettings: { - outputSelection: { - '*': { - '*': ['metadata'], - '': ['ast'], - }, - }, - }, - }); - return (compiler.getCompilerOutputsAsync() as any) as Promise; -} - -async function getSourceContentsFromCompilerOutputAsync(output: SolcOutput): Promise { - const sources: SourceData[] = []; - for (const [importFile, fileOutput] of Object.entries(output.contracts)) { - if (importFile in sources) { - continue; - } - for (const contractOutput of Object.values(fileOutput)) { - const metadata = JSON.parse(contractOutput.metadata || '{}') as ContractMetadata; - let filePath = importFile; - if (!path.isAbsolute(filePath)) { - const { remappings } = metadata.settings; - let longestPrefix = ''; - let longestPrefixReplacement = ''; - for (const remapping of remappings) { - const [from, to] = remapping.substr(1).split('='); - if (longestPrefix.length < from.length) { - if (filePath.startsWith(from)) { - longestPrefix = from; - longestPrefixReplacement = to; - } - } - } - filePath = filePath.slice(longestPrefix.length); - filePath = path.join(longestPrefixReplacement, filePath); - } - const content = await promisify(fs.readFile)(filePath, { encoding: 'utf-8' }); - sources[output.sources[importFile].id] = { - path: path.relative('.', filePath), - content, - }; - } - } - return sources; -} - -function rewriteSourcePaths(sources: SourceData[], roots: string[]): SourceData[] { - const _roots = roots.map(root => root.split('=')); - return sources.map(s => { - let longestPrefix = ''; - let longestPrefixReplacement = ''; - for (const [from, to] of _roots) { - if (from.length > longestPrefix.length) { - if (s.path.startsWith(from)) { - longestPrefix = from; - longestPrefixReplacement = to || ''; - } - } - } - return { - ...s, - path: `${longestPrefixReplacement}${s.path.substr(longestPrefix.length)}`, - }; - }); -} - -function mergeDocs(dst: SolidityDocs, ...srcs: SolidityDocs[]): SolidityDocs { - if (srcs.length === 0) { - return dst; - } - for (const src of srcs) { - dst.contracts = { - ...dst.contracts, - ...src.contracts, - }; - } - return dst; -} - -function createEmptyDocs(): SolidityDocs { - return { contracts: {} }; -} - -function extractDocsFromFile(ast: SourceUnitNode, source: SourceData): SolidityDocs { - const HIDDEN_VISIBILITIES = [Visibility.Private, Visibility.Internal]; - const docs = createEmptyDocs(); - const visit = (node: AstNode, currentContractName?: string) => { - const { offset } = splitAstNodeSrc(node.src); - if (isSourceUnitNode(node)) { - for (const child of node.nodes) { - visit(child); - } - } else if (isContractDefinitionNode(node)) { - const natspec = getNatspecBefore(source.content, offset); - docs.contracts[node.name] = { - file: source.path, - line: getAstNodeLineNumber(node, source.content), - doc: natspec.dev || natspec.comment, - kind: node.contractKind, - inherits: node.baseContracts.map(c => normalizeType(c.baseName.typeDescriptions.typeString)), - methods: [], - events: [], - enums: {}, - structs: {}, - }; - for (const child of node.nodes) { - visit(child, node.name); - } - } else if (!currentContractName) { - return; - } else if (isVariableDeclarationNode(node)) { - if (HIDDEN_VISIBILITIES.includes(node.visibility)) { - return; - } - if (!node.stateVariable) { - return; - } - const natspec = getNatspecBefore(source.content, offset); - docs.contracts[currentContractName].methods.push({ - file: source.path, - line: getAstNodeLineNumber(node, source.content), - doc: getDocStringAround(source.content, offset), - name: node.name, - contract: currentContractName, - kind: FunctionKind.Function, - visibility: Visibility.External, - parameters: extractAcessorParameterDocs(node.typeName, natspec, source), - returns: extractAccesorReturnDocs(node.typeName, natspec, source), - stateMutability: StateMutability.View, - isAccessor: true, - }); - } else if (isFunctionDefinitionNode(node)) { - const natspec = getNatspecBefore(source.content, offset); - docs.contracts[currentContractName].methods.push({ - file: source.path, - line: getAstNodeLineNumber(node, source.content), - doc: natspec.dev || natspec.comment || getCommentsBefore(source.content, offset), - name: node.name, - contract: currentContractName, - kind: node.kind, - visibility: node.visibility, - parameters: extractFunctionParameterDocs(node.parameters, natspec, source), - returns: extractFunctionReturnDocs(node.returnParameters, natspec, source), - stateMutability: node.stateMutability, - isAccessor: false, - }); - } else if (isStructDefinitionNode(node)) { - const natspec = getNatspecBefore(source.content, offset); - docs.contracts[currentContractName].structs[node.canonicalName] = { - contract: currentContractName, - file: source.path, - line: getAstNodeLineNumber(node, source.content), - doc: natspec.dev || natspec.comment || getCommentsBefore(source.content, offset), - fields: extractStructFieldDocs(node.members, natspec, source), - }; - } else if (isEnumDefinitionNode(node)) { - const natspec = getNatspecBefore(source.content, offset); - docs.contracts[currentContractName].enums[node.canonicalName] = { - contract: currentContractName, - file: source.path, - line: getAstNodeLineNumber(node, source.content), - doc: natspec.dev || natspec.comment || getCommentsBefore(source.content, offset), - values: extractEnumValueDocs(node.members, natspec, source), - }; - } else if (isEventDefinitionNode(node)) { - const natspec = getNatspecBefore(source.content, offset); - docs.contracts[currentContractName].events.push({ - contract: currentContractName, - file: source.path, - line: getAstNodeLineNumber(node, source.content), - doc: natspec.dev || natspec.comment || getCommentsBefore(source.content, offset), - name: node.name, - parameters: extractFunctionParameterDocs(node.parameters, natspec, source), - }); - } - }; - visit(ast); - return docs; -} - -function extractAcessorParameterDocs(typeNameNode: TypeNameNode, natspec: Natspec, source: SourceData): ParamDocsMap { - const params: ParamDocsMap = {}; - const lineNumber = getAstNodeLineNumber(typeNameNode, source.content); - if (isMappingTypeNameNode(typeNameNode)) { - // Handle mappings. - let node = typeNameNode; - let order = 0; - do { - const paramName = `${Object.keys(params).length}`; - params[paramName] = { - file: source.path, - line: lineNumber, - doc: natspec.params[paramName] || '', - type: normalizeType(node.keyType.typeDescriptions.typeString), - indexed: false, - storageLocation: StorageLocation.Default, - order: order++, - }; - node = node.valueType as MappingTypeNameNode; - } while (isMappingTypeNameNode(node)); - } else if (isArrayTypeNameNode(typeNameNode)) { - // Handle arrays. - let node = typeNameNode; - let order = 0; - do { - const paramName = `${Object.keys(params).length}`; - params[paramName] = { - file: source.path, - line: lineNumber, - doc: natspec.params[paramName] || '', - type: 'uint256', - indexed: false, - storageLocation: StorageLocation.Default, - order: order++, - }; - node = node.baseType as ArrayTypeNameNode; - } while (isArrayTypeNameNode(node)); - } - return params; -} - -function extractAccesorReturnDocs(typeNameNode: TypeNameNode, natspec: Natspec, source: SourceData): ParamDocsMap { - let type = typeNameNode.typeDescriptions.typeString; - let storageLocation = StorageLocation.Default; - if (isMappingTypeNameNode(typeNameNode)) { - // Handle mappings. - let node = typeNameNode; - while (isMappingTypeNameNode(node.valueType)) { - node = node.valueType; - } - type = node.valueType.typeDescriptions.typeString; - storageLocation = type.startsWith('struct') ? StorageLocation.Memory : StorageLocation.Default; - } else if (isArrayTypeNameNode(typeNameNode)) { - // Handle arrays. - type = typeNameNode.baseType.typeDescriptions.typeString; - storageLocation = type.startsWith('struct') ? StorageLocation.Memory : StorageLocation.Default; - } else if (isUserDefinedTypeNameNode(typeNameNode)) { - storageLocation = typeNameNode.typeDescriptions.typeString.startsWith('struct') - ? StorageLocation.Memory - : StorageLocation.Default; - } - return { - '0': { - storageLocation, - type: normalizeType(type), - file: source.path, - line: getAstNodeLineNumber(typeNameNode, source.content), - doc: natspec.returns['0'] || '', - indexed: false, - order: 0, - }, - }; -} - -function extractFunctionParameterDocs( - paramListNodes: ParameterListNode, - natspec: Natspec, - source: SourceData, -): ParamDocsMap { - const params: ParamDocsMap = {}; - for (const param of paramListNodes.parameters) { - params[param.name] = { - file: source.path, - line: getAstNodeLineNumber(param, source.content), - doc: natspec.params[param.name] || '', - type: normalizeType(param.typeName.typeDescriptions.typeString), - indexed: param.indexed, - storageLocation: param.storageLocation, - order: 0, - }; - } - return params; -} - -function extractFunctionReturnDocs( - paramListNodes: ParameterListNode, - natspec: Natspec, - source: SourceData, -): ParamDocsMap { - const returns: ParamDocsMap = {}; - let order = 0; - for (const [idx, param] of Object.entries(paramListNodes.parameters)) { - returns[param.name || idx] = { - file: source.path, - line: getAstNodeLineNumber(param, source.content), - doc: natspec.returns[param.name || idx] || '', - type: normalizeType(param.typeName.typeDescriptions.typeString), - indexed: false, - storageLocation: param.storageLocation, - order: order++, - }; - } - return returns; -} - -function extractStructFieldDocs( - fieldNodes: VariableDeclarationNode[], - natspec: Natspec, - source: SourceData, -): ParamDocsMap { - const fields: ParamDocsMap = {}; - let order = 0; - for (const field of fieldNodes) { - const { offset } = splitAstNodeSrc(field.src); - fields[field.name] = { - file: source.path, - line: getAstNodeLineNumber(field, source.content), - doc: natspec.params[field.name] || getDocStringAround(source.content, offset), - type: normalizeType(field.typeName.typeDescriptions.typeString), - indexed: false, - storageLocation: field.storageLocation, - order: order++, - }; - } - return fields; -} - -function extractEnumValueDocs(valuesNodes: EnumValueNode[], natspec: Natspec, source: SourceData): EnumValueDocsMap { - const values: EnumValueDocsMap = {}; - for (const value of valuesNodes) { - const { offset } = splitAstNodeSrc(value.src); - values[value.name] = { - file: source.path, - line: getAstNodeLineNumber(value, source.content), - doc: natspec.params[value.name] || getDocStringAround(source.content, offset), - value: Object.keys(values).length, - }; - } - return values; -} - -function offsetToLineIndex(code: string, offset: number): number { - let currentOffset = 0; - let lineIdx = 0; - while (currentOffset <= offset) { - const lineEnd = code.indexOf('\n', currentOffset); - if (lineEnd === -1) { - return lineIdx; - } - currentOffset = lineEnd + 1; - ++lineIdx; - } - return lineIdx - 1; -} - -function offsetToLine(code: string, offset: number): string { - let lineEnd = code.substr(offset).search(/\r?\n/); - lineEnd = lineEnd === -1 ? code.length - offset : lineEnd; - let lineStart = code.lastIndexOf('\n', offset); - lineStart = lineStart === -1 ? 0 : lineStart; - return code.substr(lineStart, offset - lineStart + lineEnd).trim(); -} - -function getPrevLine(code: string, offset: number): [string | undefined, number] { - const lineStart = code.lastIndexOf('\n', offset); - if (lineStart <= 0) { - return [undefined, 0]; - } - const prevLineStart = code.lastIndexOf('\n', lineStart - 1); - if (prevLineStart === -1) { - return [code.substr(0, lineStart).trim(), 0]; - } - return [code.substring(prevLineStart + 1, lineStart).trim(), prevLineStart + 1]; -} - -function getAstNodeLineNumber(node: AstNode, code: string): number { - return offsetToLineIndex(code, splitAstNodeSrc(node.src).offset) + 1; -} - -function getNatspecBefore(code: string, offset: number): Natspec { - const natspec = { comment: '', dev: '', params: {}, returns: {} }; - // Walk backwards through the lines until there is no longer a natspec - // comment. - let currentDirectivePayloads = []; - let currentLine: string | undefined; - let currentOffset = offset; - while (true) { - [currentLine, currentOffset] = getPrevLine(code, currentOffset); - if (currentLine === undefined) { - break; - } - const m = /^\/\/\/\s*(?:@(\w+\b)\s*)?(.*?)$/.exec(currentLine); - if (!m) { - break; - } - const directive = m[1]; - let directiveParam: string | undefined; - let rest = m[2] || ''; - // Parse directives that take a parameter. - if (directive === 'param' || directive === 'return') { - const m2 = /^(\w+\b)(.*)$/.exec(rest); - if (m2) { - directiveParam = m2[1]; - rest = m2[2] || ''; - } - } - currentDirectivePayloads.push(rest); - if (directive !== undefined) { - const fullPayload = currentDirectivePayloads - .reverse() - .map(s => s.trim()) - .join(' '); - switch (directive) { - case 'dev': - natspec.dev = fullPayload; - break; - case 'param': - if (directiveParam) { - natspec.params = { - ...natspec.params, - [directiveParam]: fullPayload, - }; - } - break; - case 'return': - if (directiveParam) { - natspec.returns = { - ...natspec.returns, - [directiveParam]: fullPayload, - }; - } - break; - default: - break; - } - currentDirectivePayloads = []; - } - } - if (currentDirectivePayloads.length > 0) { - natspec.comment = currentDirectivePayloads - .reverse() - .map(s => s.trim()) - .join(' '); - } - return natspec; -} - -function getTrailingCommentAt(code: string, offset: number): string { - const m = /\/\/\s*(.+)\s*$/.exec(offsetToLine(code, offset)); - return m ? m[1] : ''; -} - -function getCommentsBefore(code: string, offset: number): string { - let currentOffset = offset; - const comments = []; - do { - let prevLine; - [prevLine, currentOffset] = getPrevLine(code, currentOffset); - if (prevLine === undefined) { - break; - } - const m = /^\s*\/\/\s*(.+)\s*$/.exec(prevLine); - if (m && !m[1].startsWith('solhint')) { - comments.push(m[1].trim()); - } else { - break; - } - } while (currentOffset > 0); - return comments.reverse().join(' '); -} - -function getDocStringBefore(code: string, offset: number): string { - const natspec = getNatspecBefore(code, offset); - return natspec.dev || natspec.comment || getCommentsBefore(code, offset); -} - -function getDocStringAround(code: string, offset: number): string { - const natspec = getNatspecBefore(code, offset); - return natspec.dev || natspec.comment || getDocStringBefore(code, offset) || getTrailingCommentAt(code, offset); -} - -function normalizeType(type: string): string { - const m = /^(?:\w+ )?(.*)$/.exec(type); - if (!m) { - return type; - } - return m[1]; -} - -// tslint:disable-next-line: max-file-line-count diff --git a/packages/sol-doc/src/gen_md.ts b/packages/sol-doc/src/gen_md.ts deleted file mode 100644 index e11f199247..0000000000 --- a/packages/sol-doc/src/gen_md.ts +++ /dev/null @@ -1,232 +0,0 @@ -import { DocumentedItem, EventDocs, MethodDocs, SolidityDocs } from './extract_docs'; - -export interface MarkdownOpts { - urlPrefix: string; -} - -/** - * Convert JSON docs to markdown. - */ -export function generateMarkdownFromDocs(docs: SolidityDocs, opts: Partial = {}): string { - const lines: string[] = []; - const sortedContracts = Object.keys(docs.contracts).sort(); - for (const contractName of sortedContracts) { - lines.push(...generateContractsContent(contractName, docs, opts)); - } - return lines.join('\n'); -} - -function generateContractsContent(name: string, docs: SolidityDocs, opts: Partial): string[] { - const contract = docs.contracts[name]; - const enums = []; - const sortedEnums = Object.entries(contract.enums).sort(([a], [b]) => a.localeCompare(b)); - for (const [enumName, enumDocs] of sortedEnums) { - enums.push([ - `### ${toCode(enumName)}`, - enumDocs.doc, - '', - toSourceAttributionLink(enumDocs, opts), - '', - `***Members***`, - ...createTableContent( - ['Name', 'Value', 'Description'], - Object.entries(enumDocs.values).map(([n, d]) => [ - toSourceLink(toCode(n), d, opts), - toCode(d.value), - d.doc, - ]), - ), - ]); - } - const structSections = []; - const sortedStructs = Object.entries(contract.structs).sort(([a], [b]) => a.localeCompare(b)); - for (const [structName, structDocs] of sortedStructs) { - structSections.push([ - `### ${toCode(structName)}`, - structDocs.doc, - '', - toSourceAttributionLink(structDocs, opts), - '', - `***Fields***`, - ...createTableContent( - ['Name', 'Type', 'Description'], - Object.entries(structDocs.fields).map(([n, d]) => [ - toSourceLink(toCode(n), d, opts), - toCode(d.type), - d.doc, - ]), - ), - ]); - } - const eventSections = []; - const sortedEvents = contract.events.sort((a, b) => a.name.localeCompare(b.name)); - for (const event of sortedEvents) { - eventSections.push([ - `### ${toCode(event.name)}`, - event.doc, - '', - `• ${toCode(getEventSignature(event))}`, - '', - toSourceAttributionLink(event, opts), - '', - `***Parameters***`, - ...createTableContent( - ['Name', 'Type', 'Indexed', 'Description'], - Object.entries(event.parameters).map(([n, d]) => [ - toSourceLink(toCode(n), d, opts), - toCode(d.type), - toCode(d.indexed), - d.doc, - ]), - ), - ]); - } - const methodSections = []; - const sortedMethods = contract.methods.sort((a, b) => a.name.localeCompare(b.name)); - for (const method of sortedMethods) { - const annotation = method.isAccessor ? ' *(generated)*' : method.kind === 'fallback' ? ' *(fallback)*' : ''; - methodSections.push([ - `### ${toCode(getNormalizedMethodName(method))}`, - method.doc, - '', - `• ${toCode(getMethodSignature(method))}${annotation}`, - '', - toSourceAttributionLink(method, opts), - '', - ...(Object.keys(method.parameters).length !== 0 - ? [ - `***Parameters***`, - ...createTableContent( - ['Name', 'Type', 'Description'], - Object.entries(method.parameters).map(([n, d]) => [ - toSourceLink(toCode(n), d, opts), - toCode(d.type), - d.doc, - ]), - ), - ] - : []), - ...(Object.keys(method.returns).length !== 0 - ? [ - `***Returns***`, - ...createTableContent( - ['Name', 'Type', 'Description'], - Object.entries(method.returns).map(([n, d]) => [ - toSourceLink(toCode(n), d, opts), - toCode(d.type), - d.doc, - ]), - ), - ] - : []), - ]); - } - return [ - `# ${contract.kind} ${toCode(name)}`, - contract.doc, - '', - toSourceAttributionLink(contract, opts), - '', - ...(enums.length > 0 ? ['## Enums', ...joinSections(enums)] : []), - ...(structSections.length > 0 ? ['## Structs', ...joinSections(structSections)] : []), - ...(eventSections.length > 0 ? ['## Events', ...joinSections(eventSections)] : []), - ...(methodSections.length > 0 ? ['## Methods', ...joinSections(methodSections)] : []), - ]; -} - -interface Stringable { - toString(): string; -} - -function joinSections(sections: string[][]): string[] { - if (sections.length === 0) { - return []; - } - const joined: string[] = []; - for (const s of sections) { - joined.push(...s, '---'); - } - return joined.slice(0, joined.length - 1); -} - -function toCode(v: Stringable | boolean): string { - if (typeof v === 'boolean') { - return `\`${v ? true : false}\``; - } - return `\`${v}\``; -} - -function toSourceLink(text: string, doc: DocumentedItem, opts: Partial): string { - return `[${text}](${toSourceURL(doc.file, doc.line, opts.urlPrefix)})`; -} - -function toSourceAttributionLink(doc: DocumentedItem, opts: Partial): string { - return `  *Defined in ${toSourceLink(`${doc.file}:${doc.line}`, doc, opts)}*`; -} - -function toSourceURL(file: string, line: number, prefix?: string): string { - if (file.startsWith('/')) { - return `${file}#L${line}`; - } - const _prefix = !prefix || prefix.endsWith('/') ? prefix || '' : `${prefix}/`; - return `${_prefix}${file}#L${line}`; -} - -function getMethodSignature(method: MethodDocs): string { - const args = Object.entries(method.parameters).map(([_name, param]) => { - return /^\d+$/.test(_name) ? param.type : `${param.type} ${_name}`; - }); - const returns = Object.entries(method.returns).map(([_name, param]) => { - return /^\d+$/.test(_name) ? param.type : `${param.type} ${_name}`; - }); - const _returns = returns.length !== 0 ? `: (${returns.join(', ')})` : ''; - const mutabilityPrefix = ['view', 'pure'].includes(method.stateMutability) - ? 'constant ' - : method.stateMutability === 'payable' - ? 'payable ' - : ''; - return `${mutabilityPrefix}function ${getNormalizedMethodName(method)}(${args.join(', ')})${_returns}`; -} - -function getNormalizedMethodName(method: MethodDocs): string { - let name = method.name; - if (method.kind === 'constructor') { - name = 'constructor'; - } else if (method.kind === 'fallback') { - name = ''; - } - return name; -} - -function getEventSignature(event: EventDocs): string { - const args = Object.entries(event.parameters).map(([name, param]) => { - return /^\d+$/.test(name) ? param.type : `${param.type} ${name}`; - }); - return `event ${event.name}(${args.join(', ')})`; -} - -function createTableContent(headers: string[], rows: Stringable[][]): string[] { - const [_headers, _rows] = filterTableEmptyColumns(headers, rows); - const lines = [ - _headers.join(' | '), - _headers.map(h => h.replace(/./g, '-')).join(' | '), - ..._rows.map(r => r.join(' | ')), - ].map(line => `| ${line} |`); - return ['', ...lines, '']; -} - -function filterTableEmptyColumns(headers: string[], rows: Stringable[][]): [string[], Stringable[][]] { - const emptyColumnIndicesByRow = rows.map(r => r.map((c, i) => i).filter(i => r[i] === '')); - const emptyColumnIndices = emptyColumnIndicesByRow.reduce((acc, row) => { - for (const i of row) { - if (!acc.includes(i)) { - acc.push(i); - } - } - return acc; - }, []); - return [ - headers.filter((v, i) => !emptyColumnIndices.includes(i)), - rows.filter((v, i) => !emptyColumnIndices.includes(i)), - ]; -} diff --git a/packages/sol-doc/src/index.ts b/packages/sol-doc/src/index.ts deleted file mode 100644 index 21628c28b2..0000000000 --- a/packages/sol-doc/src/index.ts +++ /dev/null @@ -1,20 +0,0 @@ -export { - ContractDocs, - ContractKind, - EnumValueDocs, - EnumValueDocsMap, - EventDocs, - extractDocsAsync, - FunctionKind, - MethodDocs, - ParamDocs, - ParamDocsMap, - SolidityDocs, - StorageLocation, - StructDocs, - Visibility, -} from './extract_docs'; - -export { transformDocs, TransformOpts } from './transform_docs'; - -export { generateMarkdownFromDocs, MarkdownOpts } from './gen_md'; diff --git a/packages/sol-doc/src/sol_ast.ts b/packages/sol-doc/src/sol_ast.ts deleted file mode 100644 index e76872aa2c..0000000000 --- a/packages/sol-doc/src/sol_ast.ts +++ /dev/null @@ -1,231 +0,0 @@ -export enum AstNodeType { - SourceUnit = 'SourceUnit', - ContractDefinition = 'ContractDefinition', - FunctionDefinition = 'FunctionDefinition', - ParameterList = 'ParameterList', - VariableDeclaration = 'VariableDeclaration', - UserDefinedTypeName = 'UserDefinedTypeName', - ElementaryTypeName = 'ElementaryTypeName', - ArrayTypeName = 'ArrayTypeName', - Mapping = 'Mapping', - StructDefinition = 'StructDefinition', - EnumDefinition = 'EnumDefinition', - EnumValue = 'EnumValue', - InheritanceSpecifier = 'InheritanceSpecifier', - EventDefinition = 'EventDefinition', -} - -export enum Visibility { - Internal = 'internal', - External = 'external', - Public = 'public', - Private = 'private', -} - -export enum StateMutability { - Nonpayable = 'nonpayable', - Payable = 'payable', - View = 'view', - Pure = 'pure', -} - -export enum FunctionKind { - Constructor = 'constructor', - Function = 'function', - Fallback = 'fallback', -} - -export enum ContractKind { - Contract = 'contract', - Interface = 'interface', - Library = 'library', -} - -export enum StorageLocation { - Default = 'default', - Storage = 'storage', - Memory = 'memory', - CallData = 'calldata', -} - -export interface AstNode { - id: number; - nodeType: AstNodeType; - src: string; -} - -export interface SourceUnitNode extends AstNode { - path: string; - nodes: AstNode[]; - exportedSymbols: { - [symbol: string]: number[]; - }; -} - -export interface ContractDefinitionNode extends AstNode { - name: string; - contractKind: ContractKind; - fullyImplemented: boolean; - linearizedBaseContracts: number[]; - contractDependencies: number[]; - baseContracts: InheritanceSpecifierNode[]; - nodes: AstNode[]; -} - -export interface InheritanceSpecifierNode extends AstNode { - baseName: UserDefinedTypeNameNode; -} - -export interface FunctionDefinitionNode extends AstNode { - name: string; - implemented: boolean; - scope: number; - kind: FunctionKind; - parameters: ParameterListNode; - returnParameters: ParameterListNode; - visibility: Visibility; - stateMutability: StateMutability; -} - -export interface ParameterListNode extends AstNode { - parameters: VariableDeclarationNode[]; -} - -export interface VariableDeclarationNode extends AstNode { - name: string; - value: AstNode | null; - constant: boolean; - scope: number; - visibility: Visibility; - stateVariable: boolean; - storageLocation: StorageLocation; - indexed: boolean; - typeName: TypeNameNode; -} - -export interface TypeNameNode extends AstNode { - name: string; - typeDescriptions: { - typeIdentifier: string; - typeString: string; - }; -} - -export interface UserDefinedTypeNameNode extends TypeNameNode { - referencedDeclaration: number; -} - -export interface MappingTypeNameNode extends TypeNameNode { - keyType: ElementaryTypeNameNode; - valueType: TypeNameNode; -} - -export interface ElementaryTypeNameNode extends TypeNameNode {} - -export interface ArrayTypeNameNode extends TypeNameNode { - length: number | null; - baseType: TypeNameNode; -} - -export interface StructDefinitionNode extends AstNode { - scope: number; - name: string; - canonicalName: string; - members: VariableDeclarationNode[]; -} - -export interface EnumDefinitionNode extends AstNode { - name: string; - canonicalName: string; - members: EnumValueNode[]; -} - -export interface EnumValueNode extends AstNode { - name: string; -} - -export interface EventDefinitionNode extends AstNode { - name: string; - parameters: ParameterListNode; -} - -/** - * Check if a node is a SourceUnit node. - */ -export function isSourceUnitNode(node: AstNode): node is SourceUnitNode { - return node.nodeType === AstNodeType.SourceUnit; -} - -/** - * Check if a node is a ContractDefinition ode. - */ -export function isContractDefinitionNode(node: AstNode): node is ContractDefinitionNode { - return node.nodeType === AstNodeType.ContractDefinition; -} - -/** - * Check if a node is a VariableDeclaration ode. - */ -export function isVariableDeclarationNode(node: AstNode): node is VariableDeclarationNode { - return node.nodeType === AstNodeType.VariableDeclaration; -} - -/** - * Check if a node is a FunctionDefinition node. - */ -export function isFunctionDefinitionNode(node: AstNode): node is FunctionDefinitionNode { - return node.nodeType === AstNodeType.FunctionDefinition; -} - -/** - * Check if a node is a StructDefinition ode. - */ -export function isStructDefinitionNode(node: AstNode): node is StructDefinitionNode { - return node.nodeType === AstNodeType.StructDefinition; -} - -/** - * Check if a node is a EnumDefinition ode. - */ -export function isEnumDefinitionNode(node: AstNode): node is EnumDefinitionNode { - return node.nodeType === AstNodeType.EnumDefinition; -} - -/** - * Check if a node is a Mapping node. - */ -export function isMappingTypeNameNode(node: AstNode): node is MappingTypeNameNode { - return node.nodeType === AstNodeType.Mapping; -} - -/** - * Check if a node is a ArrayTypeName node. - */ -export function isArrayTypeNameNode(node: AstNode): node is ArrayTypeNameNode { - return node.nodeType === AstNodeType.ArrayTypeName; -} - -/** - * Check if a node is a UserDefinedTypeName node. - */ -export function isUserDefinedTypeNameNode(node: AstNode): node is UserDefinedTypeNameNode { - return node.nodeType === AstNodeType.UserDefinedTypeName; -} - -/** - * Check if a node is a EventDefinition node. - */ -export function isEventDefinitionNode(node: AstNode): node is EventDefinitionNode { - return node.nodeType === AstNodeType.EventDefinition; -} - -/** - * Split an AST source mapping string into its parts. - */ -export function splitAstNodeSrc(src: string): { offset: number; length: number; sourceId: number } { - // tslint:disable-next-line: custom-no-magic-numbers - const [offset, length, sourceId] = src.split(':').map(s => parseInt(s, 10)); - return { offset, length, sourceId }; -} - -// tslint:disable-next-line: max-file-line-count diff --git a/packages/sol-doc/src/transform_docs.ts b/packages/sol-doc/src/transform_docs.ts deleted file mode 100644 index dd7e942ae8..0000000000 --- a/packages/sol-doc/src/transform_docs.ts +++ /dev/null @@ -1,235 +0,0 @@ -import { ContractDocs, EventDocs, MethodDocs, ParamDocsMap, SolidityDocs, Visibility } from './extract_docs'; - -export interface TransformOpts { - onlyExposed: boolean; - flatten: boolean; - contracts: string[]; -} - -interface TypesUsage { - [type: string]: { - methods: MethodDocs[]; - events: EventDocs[]; - structs: string[]; - }; -} - -/** - * Apply some nice transformations to extracted JSON docs, such as flattening - * inherited contracts and filtering out unexposed or unused types. - */ -export function transformDocs(docs: SolidityDocs, opts: Partial = {}): SolidityDocs { - const _opts = { - onlyExposed: false, - flatten: false, - contracts: undefined, - ...opts, - }; - const _docs = { - ...docs, - contracts: { ...docs.contracts }, - }; - if (_opts.flatten) { - for (const [contractName] of Object.entries(docs.contracts)) { - _docs.contracts[contractName] = flattenContract(contractName, docs); - } - } - return filterTypes(_docs, _opts.contracts || Object.keys(docs.contracts), _opts.onlyExposed); -} - -function flattenContract(contractName: string, docs: SolidityDocs, seen: string[] = []): ContractDocs { - seen.push(contractName); - const contract = docs.contracts[contractName]; - const bases = []; - for (const ancestor of contract.inherits) { - if (!seen.includes(ancestor)) { - bases.push(flattenContract(ancestor, docs, seen)); - } - } - return mergeContracts([...bases, contract]); -} - -function mergeContracts(contracts: ContractDocs[]): ContractDocs { - return { - ...contracts[contracts.length - 1], - methods: mergeMethods(concat(...contracts.map(c => c.methods))), - events: mergeEvents(concat(...contracts.map(c => c.events))), - }; -} - -function concat(...arrs: T[][]): T[] { - return arrs.reduce((prev: T[], curr: T[]) => { - prev.push(...curr); - return prev; - }, []); -} - -function mergeMethods(methods: MethodDocs[]): MethodDocs[] { - const ids: string[] = []; - const merged: MethodDocs[] = []; - for (const method of methods) { - if (method.visibility === Visibility.Private) { - continue; - } - const id = getMethodId(method.name, method.parameters); - if (method.kind === 'constructor') { - const constructorIndex = merged.findIndex(m => m.kind === 'constructor'); - if (constructorIndex !== -1) { - merged[constructorIndex] = method; - ids[constructorIndex] = id; - continue; - } - } - const existingIdx = ids.indexOf(id); - if (existingIdx !== -1) { - merged[existingIdx] = method; - ids[existingIdx] = id; - } else { - merged.push(method); - ids.push(id); - } - } - return merged; -} - -function mergeEvents(events: EventDocs[]): EventDocs[] { - const ids: string[] = []; - const merged: EventDocs[] = []; - for (const event of events) { - const selector = getMethodId(event.name, event.parameters); - const existingIdx = ids.indexOf(selector); - if (existingIdx !== -1) { - merged[existingIdx] = event; - ids[existingIdx] = selector; - } else { - merged.push(event); - ids.push(selector); - } - } - return merged; -} - -function getMethodId(name: string, params: ParamDocsMap): string { - const paramsTypes = Object.values(params).map(p => p.type); - return `${name}(${paramsTypes.join(',')})`; -} - -function filterTypes(docs: SolidityDocs, contracts: string[], onlyExposed: boolean = false): SolidityDocs { - const inheritedContracts = getAllInheritedContracts(contracts, docs); - const contractsWithInheritance = [...inheritedContracts, ...contracts]; - const filteredDocs: SolidityDocs = { - ...docs, - contracts: {}, - }; - const usages = getTypeUsage(docs); - for (const [contractName, contract] of Object.entries(docs.contracts)) { - if (inheritedContracts.includes(contractName) && !contracts.includes(contractName)) { - continue; - } - const filteredContract: ContractDocs = { - ...contract, - methods: contract.methods.filter(m => !onlyExposed || isMethodVisible(m)), - structs: {}, - enums: {}, - }; - for (const [typeName, doc] of Object.entries(contract.structs)) { - if (isTypeUsedByContracts(typeName, usages, contractsWithInheritance, onlyExposed)) { - filteredContract.structs[typeName] = doc; - } - } - for (const [typeName, doc] of Object.entries(contract.enums)) { - if (isTypeUsedByContracts(typeName, usages, contractsWithInheritance, onlyExposed)) { - filteredContract.enums[typeName] = doc; - } - } - if ( - contracts.includes(contractName) || - Object.keys(filteredContract.structs).length !== 0 || - Object.keys(filteredContract.enums).length !== 0 - ) { - filteredDocs.contracts[contractName] = filteredContract; - } - } - return filteredDocs; -} - -function getAllInheritedContracts(contracts: string[], docs: SolidityDocs): string[] { - const result: string[] = []; - for (const contract of contracts) { - for (const inherited of docs.contracts[contract].inherits) { - if (result.includes(inherited)) { - continue; - } - result.push(inherited, ...getAllInheritedContracts([inherited], docs)); - } - } - return result; -} - -function getTypeUsage(docs: SolidityDocs): TypesUsage { - const types: TypesUsage = {}; - const addTypeUser = (type: string, user: { method?: MethodDocs; event?: EventDocs; struct?: string }) => { - if (types[type] === undefined) { - types[type] = { methods: [], events: [], structs: [] }; - } - if (user.method !== undefined) { - types[type].methods.push(user.method); - } - if (user.event !== undefined) { - types[type].events.push(user.event); - } - if (user.struct !== undefined) { - types[type].structs.push(user.struct); - } - }; - for (const contract of Object.values(docs.contracts)) { - for (const [typeName, doc] of Object.entries(contract.structs)) { - for (const field of Object.values(doc.fields)) { - addTypeUser(field.type, { struct: typeName }); - } - } - for (const doc of contract.events) { - for (const param of Object.values(doc.parameters)) { - addTypeUser(param.type, { event: doc }); - } - } - for (const doc of contract.methods) { - for (const param of Object.values(doc.parameters)) { - addTypeUser(param.type, { method: doc }); - } - for (const param of Object.values(doc.returns)) { - addTypeUser(param.type, { method: doc }); - } - } - } - return types; -} - -function isTypeUsedByContracts( - type: string, - usages: TypesUsage, - contracts: string[], - onlyExposed: boolean = false, -): boolean { - const usage = usages[type]; - if (usage === undefined) { - return false; - } - for (const struct of usage.structs) { - if (isTypeUsedByContracts(struct, usages, contracts, onlyExposed)) { - return true; - } - } - if (usage.events.some(e => contracts.includes(e.contract))) { - return true; - } - if (usage.methods.filter(m => !onlyExposed || isMethodVisible(m)).some(m => contracts.includes(m.contract))) { - return true; - } - return false; -} - -function isMethodVisible(method: MethodDocs): boolean { - const VISIBLES = [Visibility.External, Visibility.Public]; - return VISIBLES.includes(method.visibility); -} diff --git a/packages/sol-doc/test/extract_docs_test.ts b/packages/sol-doc/test/extract_docs_test.ts deleted file mode 100644 index 66d520aa68..0000000000 --- a/packages/sol-doc/test/extract_docs_test.ts +++ /dev/null @@ -1,514 +0,0 @@ -import { chaiSetup } from '@0x/dev-utils'; -import { expect } from 'chai'; -import * as _ from 'lodash'; -import * as path from 'path'; - -import { extractDocsAsync, MethodDocs, SolidityDocs, StorageLocation, Visibility } from '../src/extract_docs'; - -chaiSetup.configure(); - -// tslint:disable: custom-no-magic-numbers -describe('extractDocsAsync()', () => { - const INTERFACE_CONTRACT = 'InterfaceContract'; - const TEST_CONTRACT = 'TestContract'; - const BASE_CONTRACT = 'BaseContract'; - const LIBRARY_CONTRACT = 'LibraryContract'; - const INPUT_CONTRACTS = [TEST_CONTRACT, BASE_CONTRACT, LIBRARY_CONTRACT, INTERFACE_CONTRACT]; - const INPUT_FILE_PATHS = INPUT_CONTRACTS.map(f => path.resolve(__dirname, '../../test/inputs', `${f}.sol`)); - - let docs: SolidityDocs; - - function createDocString(itemName: string): string { - return `Documentation for \`${itemName}\`.`; - } - - before(async () => { - docs = await extractDocsAsync(_.shuffle(INPUT_FILE_PATHS)); - }); - - describe('contracts', () => { - it('extracts all contracts with docs', async () => { - const contractLines: { [name: string]: number } = { - [TEST_CONTRACT]: 10, - [BASE_CONTRACT]: 9, - [INTERFACE_CONTRACT]: 4, - [LIBRARY_CONTRACT]: 5, - }; - const NO_DOCS = [INTERFACE_CONTRACT]; - for (const contract of INPUT_CONTRACTS) { - const cd = docs.contracts[contract]; - expect(cd).to.exist(''); - if (NO_DOCS.includes(contract)) { - expect(cd.doc).to.eq(''); - } else { - expect(cd.doc).to.eq(createDocString(contract)); - } - expect(cd.line, `${contract}.line`).to.eq(contractLines[contract]); - } - }); - - it('extracts contract inheritance', async () => { - const contractInherits: { [name: string]: string[] } = { - [TEST_CONTRACT]: [BASE_CONTRACT, INTERFACE_CONTRACT], - [BASE_CONTRACT]: [], - [INTERFACE_CONTRACT]: [], - [LIBRARY_CONTRACT]: [], - }; - for (const contract of INPUT_CONTRACTS) { - const cd = docs.contracts[contract]; - expect(cd.inherits).to.deep.eq(contractInherits[contract]); - } - }); - }); - - describe('methods', () => { - interface ExpectedMethodProps { - noDoc?: boolean; - line: number; - visibility: Visibility; - params?: { - [name: string]: { - noDoc?: boolean; - line: number; - type: string; - storage?: StorageLocation; - }; - }; - returns?: { - [name: string]: { - noDoc?: boolean; - line: number; - type: string; - storage?: StorageLocation; - }; - }; - } - - function assertMethodDocs(fullMethodName: string, props: ExpectedMethodProps): void { - const [contractName, methodName] = fullMethodName.split('.'); - const m = docs.contracts[contractName].methods.find(_m => _m.name === methodName) as MethodDocs; - { - const doc = props.noDoc ? '' : createDocString(methodName); - expect(m).to.exist(''); - expect(m.visibility).to.eq(props.visibility); - expect(m.contract).to.eq(contractName); - expect(m.doc).to.eq(doc); - } - const params = props.params || {}; - expect(Object.keys(m.parameters), 'number of parameters').to.be.length(Object.keys(params).length); - for (const [paramName, paramDoc] of Object.entries(params)) { - const actualParam = m.parameters[paramName]; - const doc = paramDoc.noDoc ? '' : createDocString(paramName); - const storage = paramDoc.storage === undefined ? StorageLocation.Default : paramDoc.storage; - expect(actualParam).to.exist(''); - expect(actualParam.doc).to.eq(doc); - expect(actualParam.line).to.eq(paramDoc.line); - expect(actualParam.storageLocation).to.eq(storage); - expect(actualParam.type).to.eq(paramDoc.type); - } - const returns = props.returns || {}; - expect(Object.keys(m.returns), 'number of returns').to.be.length(Object.keys(returns).length); - for (const [returnName, returnDoc] of Object.entries(returns)) { - const actualReturn = m.returns[returnName]; - const doc = returnDoc.noDoc ? '' : createDocString(returnName); - const storage = returnDoc.storage === undefined ? StorageLocation.Default : returnDoc.storage; - expect(actualReturn).to.exist(''); - expect(actualReturn.doc).to.eq(doc); - expect(actualReturn.line).to.eq(returnDoc.line); - expect(actualReturn.storageLocation).to.eq(storage); - expect(actualReturn.type).to.eq(returnDoc.type); - } - } - - describe('`TestContract`', () => { - it('`testContractMethod1`', () => { - assertMethodDocs('TestContract.testContractMethod1', { - line: 15, - visibility: Visibility.Public, - }); - }); - - it('`testContractMethod2`', () => { - assertMethodDocs('TestContract.testContractMethod2', { - line: 15, - visibility: Visibility.Internal, - params: { - p1: { - line: 24, - type: 'address', - }, - p2: { - line: 25, - type: 'uint256', - }, - p3: { - line: 26, - type: 'LibraryContract.LibraryContractEnum', - }, - }, - returns: { - r1: { - line: 29, - type: 'int32', - }, - }, - }); - }); - - it('`testContractMethod3`', () => { - assertMethodDocs('TestContract.testContractMethod3', { - line: 37, - visibility: Visibility.External, - params: { - p1: { - line: 37, - type: 'InterfaceContract.InterfaceStruct', - storage: StorageLocation.CallData, - }, - }, - returns: { - r1: { - line: 39, - type: 'bytes32[][]', - storage: StorageLocation.Memory, - }, - }, - }); - }); - - it('`testContractMethod4`', () => { - assertMethodDocs('TestContract.testContractMethod4', { - line: 45, - visibility: Visibility.Private, - params: { - p1: { - line: 46, - type: 'LibraryContract.LibraryStruct[]', - noDoc: true, - storage: StorageLocation.Storage, - }, - p2: { - line: 47, - type: 'InterfaceContract.InterfaceStruct[]', - noDoc: true, - storage: StorageLocation.Memory, - }, - p3: { - line: 48, - type: 'bytes[]', - noDoc: true, - storage: StorageLocation.Memory, - }, - }, - returns: { - r1: { - line: 51, - type: 'bytes', - noDoc: true, - storage: StorageLocation.Memory, - }, - r2: { - line: 51, - type: 'bytes', - noDoc: true, - storage: StorageLocation.Memory, - }, - }, - }); - }); - }); - - describe('`BaseContract`', () => { - it('`baseContractMethod1`', () => { - assertMethodDocs('BaseContract.baseContractMethod1', { - line: 36, - visibility: Visibility.Internal, - params: { - p1: { - line: 39, - type: 'bytes', - storage: StorageLocation.Memory, - }, - p2: { - line: 39, - type: 'bytes32', - }, - }, - returns: { - '0': { - line: 41, - type: 'InterfaceContract.InterfaceStruct', - storage: StorageLocation.Memory, - }, - }, - }); - }); - - it('`baseContractField1`', () => { - assertMethodDocs('BaseContract.baseContractField1', { - line: 26, - visibility: Visibility.External, - params: { - '0': { - line: 26, - type: 'bytes32', - }, - '1': { - line: 26, - type: 'address', - }, - }, - returns: { - '0': { - line: 26, - type: 'InterfaceContract.InterfaceStruct', - storage: StorageLocation.Memory, - }, - }, - }); - }); - - it('`baseContractField2`', () => { - assertMethodDocs('BaseContract.baseContractField2', { - line: 30, - visibility: Visibility.External, - params: { - '0': { - line: 30, - type: 'uint256', - }, - }, - returns: { - '0': { - noDoc: true, - line: 30, - type: 'bytes32', - }, - }, - }); - }); - - it('`baseContractField3`', () => { - // This field is private so no method should exist for it. - expect(docs.contracts.TestContract.events.find(e => e.name === 'baseContractField3')).to.eq(undefined); - }); - }); - }); - - describe('events', () => { - interface ExpectedEventProps { - noDoc?: boolean; - line: number; - params?: { - [name: string]: { - noDoc?: boolean; - line: number; - type: string; - indexed?: boolean; - }; - }; - } - - function assertEventDocs(fullEventName: string, props: ExpectedEventProps): void { - const [contractName, eventName] = fullEventName.split('.'); - const e = docs.contracts[contractName].events.find(_e => _e.name === eventName) as MethodDocs; - { - const doc = props.noDoc ? '' : createDocString(eventName); - expect(e).to.exist(''); - expect(e.contract).to.eq(contractName); - expect(e.doc).to.eq(doc); - } - const params = props.params || {}; - expect(Object.keys(e.parameters), 'number of parameters').to.be.length(Object.keys(params).length); - for (const [paramName, paramDoc] of Object.entries(params)) { - const actualParam = e.parameters[paramName]; - const doc = paramDoc.noDoc ? '' : createDocString(paramName); - const isIndexed = paramDoc.indexed === undefined ? false : paramDoc.indexed; - expect(actualParam).to.exist(''); - expect(actualParam.doc).to.eq(doc); - expect(actualParam.line).to.eq(paramDoc.line); - expect(actualParam.indexed).to.eq(isIndexed); - expect(actualParam.type).to.eq(paramDoc.type); - } - } - - describe('`BaseContract`', () => { - it('`BaseContractEvent1`', () => { - assertEventDocs('BaseContract.BaseContractEvent1', { - line: 14, - params: { - p1: { - line: 14, - type: 'address', - indexed: true, - }, - p2: { - line: 14, - type: 'InterfaceContract.InterfaceStruct', - }, - }, - }); - }); - - it('`BaseContractEvent2`', () => { - assertEventDocs('BaseContract.BaseContractEvent2', { - line: 16, - params: { - p1: { - line: 17, - type: 'uint256', - noDoc: true, - }, - p2: { - line: 18, - type: 'uint256', - indexed: true, - noDoc: true, - }, - }, - }); - }); - }); - }); - - describe('enums', () => { - interface ExpectedEnumProps { - noDoc?: boolean; - line: number; - values?: { - [name: string]: { - noDoc?: boolean; - line: number; - value: number; - }; - }; - } - - function assertEnumDocs(fullEnumName: string, props: ExpectedEnumProps): void { - const [contractName, enumName] = fullEnumName.split('.'); - const e = docs.contracts[contractName].enums[`${contractName}.${enumName}`]; - { - const doc = props.noDoc ? '' : createDocString(enumName); - expect(e).to.exist(''); - expect(e.contract).to.eq(contractName); - expect(e.doc).to.eq(doc); - } - const values = props.values || {}; - expect(Object.keys(e.values), 'number of values').to.be.length(Object.keys(values).length); - for (const [valueName, valueDoc] of Object.entries(values)) { - const actualValue = e.values[valueName]; - const doc = valueDoc.noDoc ? '' : createDocString(valueName); - expect(actualValue).to.exist(''); - expect(actualValue.doc).to.eq(doc); - expect(actualValue.line).to.eq(valueDoc.line); - expect(actualValue.value).to.eq(valueDoc.value); - } - } - - describe('`LibraryContract`', () => { - it('`LibraryContractEnum`', () => { - assertEnumDocs('LibraryContract.LibraryContractEnum', { - line: 9, - values: { - EnumMember1: { - line: 10, - value: 0, - }, - EnumMember2: { - line: 11, - value: 1, - }, - EnumMember3: { - line: 13, - value: 2, - }, - EnumMember4: { - noDoc: true, - line: 14, - value: 3, - }, - }, - }); - }); - }); - }); - - describe('structs', () => { - interface ExpectedStructProps { - noDoc?: boolean; - line: number; - fields?: { - [name: string]: { - noDoc?: boolean; - line: number; - type: string; - order: number; - }; - }; - } - - function assertStructDocs(fullStructName: string, props: ExpectedStructProps): void { - const [contractName, structName] = fullStructName.split('.'); - const s = docs.contracts[contractName].structs[`${contractName}.${structName}`]; - { - const doc = props.noDoc ? '' : createDocString(structName); - expect(s).to.exist(''); - expect(s.contract).to.eq(contractName); - expect(s.doc).to.eq(doc); - } - const fields = props.fields || {}; - expect(Object.keys(s.fields), 'number of fields').to.be.length(Object.keys(fields).length); - for (const [fieldName, fieldDoc] of Object.entries(fields)) { - const actualField = s.fields[fieldName]; - const doc = fieldDoc.noDoc ? '' : createDocString(fieldName); - expect(actualField).to.exist(''); - expect(actualField.doc).to.eq(doc); - expect(actualField.line).to.eq(fieldDoc.line); - expect(actualField.type).to.eq(fieldDoc.type); - expect(actualField.storageLocation).to.eq(StorageLocation.Default); - expect(actualField.indexed).to.eq(false); - } - } - - describe('`LibraryContract`', () => { - it('`LibraryStruct`', () => { - assertStructDocs('LibraryContract.LibraryStruct', { - line: 19, - fields: { - structField: { - line: 20, - type: 'mapping(bytes32 => address)', - order: 0, - }, - }, - }); - }); - }); - - describe('`InterfaceContract`', () => { - it('`InterfaceStruct`', () => { - assertStructDocs('InterfaceContract.InterfaceStruct', { - line: 9, - fields: { - structField1: { - line: 9, - type: 'address', - order: 0, - }, - structField2: { - line: 10, - type: 'uint256', - order: 1, - }, - structField3: { - line: 12, - type: 'bytes32', - order: 2, - }, - }, - }); - }); - }); - }); -}); -// tslint:disable: max-file-line-count diff --git a/packages/sol-doc/test/gen_md_test.ts b/packages/sol-doc/test/gen_md_test.ts deleted file mode 100644 index cbee7c88c0..0000000000 --- a/packages/sol-doc/test/gen_md_test.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { chaiSetup } from '@0x/dev-utils'; -import { expect } from 'chai'; -import * as _ from 'lodash'; - -import { FunctionKind, SolidityDocs } from '../src/extract_docs'; -import { generateMarkdownFromDocs } from '../src/gen_md'; - -import { randomContract, randomWord } from './utils/random_docs'; - -chaiSetup.configure(); - -// tslint:disable: custom-no-magic-numbers -describe('generateMarkdownFromDocs()', () => { - const URL_PREFIX = randomWord(); - const DOCS: SolidityDocs = { - contracts: { - ..._.mapValues( - _.groupBy( - _.times(_.random(2, 8), () => - ((name: string) => ({ name, ...randomContract(name) }))(`${randomWord()}Contract`), - ), - 'name', - ), - g => g[0], - ), - }, - }; - - let md: string; - let mdLines: string[]; - - function getMarkdownHeaders(level: number): string[] { - const lines = mdLines.filter(line => new RegExp(`^\\s*#{${level}}[^#]`).test(line)); - // tslint:disable-next-line: no-non-null-assertion - return lines.map(line => /^\s*#+\s*(.+?)\s*$/.exec(line)![1]); - } - - function getMarkdownLinks(): string[] { - const links: string[] = []; - for (const line of mdLines) { - const re = /\[[^\]]+\]\(([^)]+)\)/g; - let m: string[] | undefined | null; - do { - m = re.exec(line); - if (m) { - links.push(m[1]); - } - } while (m); - } - return links; - } - - before(() => { - md = generateMarkdownFromDocs(DOCS, { urlPrefix: URL_PREFIX }); - mdLines = md.split('\n'); - }); - - it('generates entries for all contracts', () => { - const headers = getMarkdownHeaders(1); - for (const [contractName, contract] of Object.entries(DOCS.contracts)) { - expect(headers).to.include(`${contract.kind} \`${contractName}\``); - } - }); - - it('generates entries for all enums', () => { - const headers = getMarkdownHeaders(3); - for (const contract of Object.values(DOCS.contracts)) { - for (const enumName of Object.keys(contract.enums)) { - expect(headers).to.include(`\`${enumName}\``); - } - } - }); - - it('generates entries for all structs', () => { - const headers = getMarkdownHeaders(3); - for (const contract of Object.values(DOCS.contracts)) { - for (const structName of Object.keys(contract.structs)) { - expect(headers).to.include(`\`${structName}\``); - } - } - }); - - it('generates entries for all events', () => { - const headers = getMarkdownHeaders(3); - for (const contract of Object.values(DOCS.contracts)) { - for (const event of contract.events) { - expect(headers).to.include(`\`${event.name}\``); - } - } - }); - - it('generates entries for all methods', () => { - const headers = getMarkdownHeaders(3); - for (const contract of Object.values(DOCS.contracts)) { - for (const method of contract.methods) { - if (method.kind === FunctionKind.Fallback) { - expect(headers).to.include(`\`\``); - } else if (method.kind === FunctionKind.Constructor) { - expect(headers).to.include(`\`constructor\``); - } else { - expect(headers).to.include(`\`${method.name}\``); - } - } - } - }); - - it('prefixes all URLs with the prefix', () => { - const urls = getMarkdownLinks(); - for (const url of urls) { - expect(url.startsWith(URL_PREFIX)).to.be.true(); - } - }); -}); -// tslint:disable: max-file-line-count diff --git a/packages/sol-doc/test/inputs/BaseContract.sol b/packages/sol-doc/test/inputs/BaseContract.sol deleted file mode 100644 index eba64abb7b..0000000000 --- a/packages/sol-doc/test/inputs/BaseContract.sol +++ /dev/null @@ -1,43 +0,0 @@ -pragma solidity ^0.5; -pragma experimental ABIEncoderV2; - -import "./InterfaceContract.sol"; -import "./LibraryContract.sol"; - - -/// @dev Documentation for `BaseContract`. -contract BaseContract { - - /// @dev Documentation for `BaseContractEvent1`. - /// @param p1 Documentation for `p1`. - /// @param p2 Documentation for `p2`. - event BaseContractEvent1(address indexed p1, InterfaceContract.InterfaceStruct p2); - // Documentation for `BaseContractEvent2`. - event BaseContractEvent2( - uint256 p1, - uint256 indexed p2 - ); - - - /// @dev Documentation for `baseContractField1`. - /// @param 1 Documentation for `1`. - /// @param 0 Documentation for `0`. - /// @return 0 Documentation for `0`. - mapping (bytes32 => mapping(address => InterfaceContract.InterfaceStruct)) public baseContractField1; - - /// @dev Documentation for `baseContractField2`. - /// @param 0 Documentation for `0`. - bytes32[] public baseContractField2; - - /// @dev Documentation for `_baseContractField3`. - uint256 private _baseContractField3; - - /// @dev Documentation for `baseContractMethod1`. - /// @param p1 Documentation for `p1`. - /// @param p2 Documentation for `p2`. - /// @return 0 Documentation for `0`. - function baseContractMethod1(bytes memory p1, bytes32 p2) - internal - returns (InterfaceContract.InterfaceStruct memory) - {} -} diff --git a/packages/sol-doc/test/inputs/InterfaceContract.sol b/packages/sol-doc/test/inputs/InterfaceContract.sol deleted file mode 100644 index bdc87b38fa..0000000000 --- a/packages/sol-doc/test/inputs/InterfaceContract.sol +++ /dev/null @@ -1,14 +0,0 @@ -pragma solidity ^0.5; - - -contract InterfaceContract { - - /// @dev Documentation for `InterfaceStruct`. - /// @param structField2 Documentation for `structField2`. - struct InterfaceStruct { - address structField1; // Documentation for `structField1`. - uint256 structField2; // Stuff to ignore. - // Documentation for `structField3`. - bytes32 structField3; - } -} diff --git a/packages/sol-doc/test/inputs/LibraryContract.sol b/packages/sol-doc/test/inputs/LibraryContract.sol deleted file mode 100644 index 08e5b2547b..0000000000 --- a/packages/sol-doc/test/inputs/LibraryContract.sol +++ /dev/null @@ -1,22 +0,0 @@ -pragma solidity ^0.5; - - -/// @dev Documentation for `LibraryContract`. -contract LibraryContract { - - /// @dev Documentation for `LibraryContractEnum`. - /// @param EnumMember1 Documentation for `EnumMember1`. - enum LibraryContractEnum { - EnumMember1, - EnumMember2, // Documentation for `EnumMember2`. - // Documentation for `EnumMember3`. - EnumMember3, - EnumMember4 - } - - /// @dev Documentation for `LibraryStruct`. - /// @param structField Documentation for `structField`. - struct LibraryStruct { - mapping (bytes32 => address) structField; - } -} diff --git a/packages/sol-doc/test/inputs/TestContract.sol b/packages/sol-doc/test/inputs/TestContract.sol deleted file mode 100644 index a992682ad5..0000000000 --- a/packages/sol-doc/test/inputs/TestContract.sol +++ /dev/null @@ -1,55 +0,0 @@ -pragma solidity ^0.5; -pragma experimental ABIEncoderV2; - -import "./InterfaceContract.sol"; -import "./LibraryContract.sol"; -import "./BaseContract.sol"; - - -/// @dev Documentation for `TestContract`. -contract TestContract is - BaseContract, - InterfaceContract -{ - /// @dev Documentation for `testContractMethod1`. - function testContractMethod1() public {} - - // Stuff to ignore. - /// @dev Documentation for `testContractMethod2`. - /// @param p2 Documentation for `p2`. - /// @param p1 Documentation for `p1`. - /// @param p3 Documentation for `p3`. - /// @return r1 Documentation for `r1`. - function testContractMethod2( - address p1, - uint256 p2, - LibraryContract.LibraryContractEnum p3 - ) - internal - returns (int32 r1) - { - return r1; - } - - /// @dev Documentation for `testContractMethod3`. - /// @param p1 Documentation for `p1`. - /// @return r1 Documentation for `r1`. - function testContractMethod3(InterfaceContract.InterfaceStruct calldata p1) - external - returns (bytes32[][] memory r1) - { - return r1; - } - - // Documentation for `testContractMethod4`. - function testContractMethod4( - LibraryContract.LibraryStruct[] storage p1, - InterfaceContract.InterfaceStruct[] memory p2, - bytes[] memory p3 - ) - private - returns (bytes memory r1, bytes memory r2) - { - return (r1, r2); - } -} diff --git a/packages/sol-doc/test/transform_docs_test.ts b/packages/sol-doc/test/transform_docs_test.ts deleted file mode 100644 index 7b20932c13..0000000000 --- a/packages/sol-doc/test/transform_docs_test.ts +++ /dev/null @@ -1,225 +0,0 @@ -import { chaiSetup } from '@0x/dev-utils'; -import { expect } from 'chai'; -import * as _ from 'lodash'; - -import { ContractKind, EventDocs, FunctionKind, MethodDocs, SolidityDocs, Visibility } from '../src/extract_docs'; -import { transformDocs } from '../src/transform_docs'; - -import { - randomContract, - randomEnum, - randomEvent, - randomMethod, - randomParameter, - randomStruct, - randomWord, -} from './utils/random_docs'; - -chaiSetup.configure(); - -// tslint:disable: custom-no-magic-numbers -describe('transformDocs()', () => { - const INTERFACE_CONTRACT = 'InterfaceContract'; - const TEST_CONTRACT = 'TestContract'; - const BASE_CONTRACT = 'BaseContract'; - const OTHER_CONTRACT = 'OtherContract'; - const LIBRARY_CONTRACT = 'LibraryContract'; - const LIBRARY_EVENT = 'LibraryContract.LibraryEvent'; - const INTERFACE_EVENT = 'InterfaceContract.InterfaceEvent'; - const BASE_CONTRACT_EVENT = 'BaseContract.BaseContractEvent'; - const LIBRARY_ENUM = 'LibraryContract.LibraryEnum'; - const INTERFACE_ENUM = 'InterfaceContract.InterfaceEnum'; - const BASE_CONTRACT_ENUM = 'BaseContract.BaseContractEnum'; - const LIBRARY_STRUCT = 'LibraryContract.LibraryStruct'; - const INTERFACE_STRUCT = 'InterfaceContract.InterfaceStruct'; - const BASE_CONTRACT_STRUCT = 'BaseContract.BaseContractStruct'; - const OTHER_CONTRACT_STRUCT = 'OtherContract.OtherContractStruct'; - const INPUT_DOCS: SolidityDocs = { - contracts: { - [LIBRARY_CONTRACT]: _.merge(randomContract(LIBRARY_CONTRACT, { kind: ContractKind.Library }), { - events: { - [LIBRARY_EVENT]: randomEvent({ contract: LIBRARY_CONTRACT }), - }, - structs: { - [LIBRARY_STRUCT]: randomStruct({ contract: LIBRARY_CONTRACT }), - }, - enums: { - [LIBRARY_ENUM]: randomEnum({ contract: LIBRARY_CONTRACT }), - }, - }), - [INTERFACE_CONTRACT]: _.merge(randomContract(INTERFACE_CONTRACT, { kind: ContractKind.Interface }), { - events: { - [INTERFACE_EVENT]: randomEvent({ contract: INTERFACE_CONTRACT }), - }, - structs: { - [INTERFACE_STRUCT]: randomStruct({ contract: INTERFACE_CONTRACT }), - }, - enums: { - [INTERFACE_ENUM]: randomEnum({ contract: INTERFACE_CONTRACT }), - }, - }), - [BASE_CONTRACT]: _.merge(randomContract(BASE_CONTRACT, { kind: ContractKind.Contract }), { - events: { - [BASE_CONTRACT_EVENT]: randomEvent({ contract: BASE_CONTRACT }), - }, - structs: { - [BASE_CONTRACT_STRUCT]: randomStruct({ contract: BASE_CONTRACT }), - }, - enums: { - [BASE_CONTRACT_ENUM]: randomEnum({ contract: BASE_CONTRACT }), - }, - }), - [TEST_CONTRACT]: _.merge( - randomContract(TEST_CONTRACT, { kind: ContractKind.Contract, inherits: [BASE_CONTRACT] }), - { - methods: [ - randomMethod({ - contract: TEST_CONTRACT, - visibility: Visibility.External, - parameters: { - [randomWord()]: randomParameter(0, { type: INTERFACE_ENUM }), - }, - }), - randomMethod({ - contract: TEST_CONTRACT, - visibility: Visibility.Private, - parameters: { - [randomWord()]: randomParameter(0, { type: LIBRARY_STRUCT }), - }, - }), - ], - }, - ), - [OTHER_CONTRACT]: _.merge(randomContract(OTHER_CONTRACT, { kind: ContractKind.Contract }), { - structs: { - [OTHER_CONTRACT_STRUCT]: randomStruct({ - contract: OTHER_CONTRACT, - fields: { - [randomWord()]: randomParameter(0, { type: LIBRARY_ENUM }), - }, - }), - }, - methods: [ - randomMethod({ - contract: OTHER_CONTRACT, - visibility: Visibility.Public, - returns: { - [randomWord()]: randomParameter(0, { type: OTHER_CONTRACT_STRUCT }), - }, - }), - randomMethod({ - contract: OTHER_CONTRACT, - visibility: Visibility.Internal, - returns: { - [randomWord()]: randomParameter(0, { type: INTERFACE_STRUCT }), - }, - }), - ], - events: [ - randomEvent({ - contract: OTHER_CONTRACT, - parameters: { - [randomWord()]: randomParameter(0, { type: LIBRARY_STRUCT }), - }, - }), - ], - }), - }, - }; - - function getMethodId(method: MethodDocs): string { - if (method.kind === FunctionKind.Constructor) { - return 'constructor'; - } - return getEventId(method); - } - - function getEventId(method: EventDocs | MethodDocs): string { - const paramsTypes = Object.values(method.parameters).map(p => p.type); - return `${method.name}(${paramsTypes.join(',')})`; - } - - function getAllTypes(docs: SolidityDocs): string[] { - const allTypes: string[] = []; - for (const contract of Object.values(docs.contracts)) { - for (const structName of Object.keys(contract.structs)) { - allTypes.push(structName); - } - for (const enumName of Object.keys(contract.enums)) { - allTypes.push(enumName); - } - } - return allTypes; - } - - it('returns all contracts with no target contracts', () => { - const docs = transformDocs(INPUT_DOCS); - expect(Object.keys(docs.contracts)).to.deep.eq([ - LIBRARY_CONTRACT, - INTERFACE_CONTRACT, - BASE_CONTRACT, - TEST_CONTRACT, - OTHER_CONTRACT, - ]); - }); - - it('returns requested AND related contracts', () => { - const contracts = [TEST_CONTRACT, OTHER_CONTRACT]; - const docs = transformDocs(INPUT_DOCS, { contracts }); - expect(Object.keys(docs.contracts)).to.deep.eq([LIBRARY_CONTRACT, INTERFACE_CONTRACT, ...contracts]); - }); - - it('returns exposed and unexposed items by default', () => { - const contracts = [TEST_CONTRACT]; - const docs = transformDocs(INPUT_DOCS, { contracts }); - expect(Object.keys(docs.contracts)).to.deep.eq([LIBRARY_CONTRACT, INTERFACE_CONTRACT, ...contracts]); - const allTypes = getAllTypes(docs); - // Check for an exposed type. - expect(allTypes).to.include(INTERFACE_ENUM); - // Check for an unexposed type. - expect(allTypes).to.include(LIBRARY_STRUCT); - }); - - it('can hide unexposed items', () => { - const contracts = [OTHER_CONTRACT]; - const docs = transformDocs(INPUT_DOCS, { contracts, onlyExposed: true }); - expect(Object.keys(docs.contracts)).to.deep.eq([LIBRARY_CONTRACT, ...contracts]); - const allTypes = getAllTypes(docs); - // Check for an exposed type. - expect(allTypes).to.include(LIBRARY_ENUM); - // Check for an unexposed type. - expect(allTypes).to.not.include(INTERFACE_STRUCT); - }); - - describe('flattening', () => { - it('merges inherited methods', () => { - const docs = transformDocs(INPUT_DOCS, { contracts: [TEST_CONTRACT], flatten: true }); - const allMethods = _.uniqBy( - _.flatten( - [BASE_CONTRACT, TEST_CONTRACT].map(c => - INPUT_DOCS.contracts[c].methods.filter(m => m.visibility !== Visibility.Private), - ), - ), - m => getMethodId(m), - ); - const outputMethods = docs.contracts[TEST_CONTRACT].methods; - expect(outputMethods).to.length(allMethods.length); - for (const method of outputMethods) { - expect(allMethods.map(m => getMethodId(m))).to.include(getMethodId(method)); - } - }); - - it('merges inherited events', () => { - const docs = transformDocs(INPUT_DOCS, { contracts: [TEST_CONTRACT], flatten: true }); - const allEvents = _.uniqBy( - _.flatten([BASE_CONTRACT, TEST_CONTRACT].map(c => INPUT_DOCS.contracts[c].events)), - e => getEventId(e), - ); - const outputEvents = docs.contracts[TEST_CONTRACT].events; - expect(outputEvents).to.length(allEvents.length); - for (const event of outputEvents) { - expect(allEvents.map(m => getEventId(m))).to.include(getEventId(event)); - } - }); - }); -}); diff --git a/packages/sol-doc/test/utils/random_docs.ts b/packages/sol-doc/test/utils/random_docs.ts deleted file mode 100644 index 0d5f01d826..0000000000 --- a/packages/sol-doc/test/utils/random_docs.ts +++ /dev/null @@ -1,175 +0,0 @@ -import * as _ from 'lodash'; - -import { - ContractDocs, - ContractKind, - DocumentedItem, - EnumDocs, - EnumValueDocs, - EventDocs, - FunctionKind, - MethodDocs, - ParamDocs, - ParamDocsMap, - StateMutability, - StorageLocation, - StructDocs, - Visibility, -} from '../../src/extract_docs'; - -// tslint:disable: custom-no-magic-numbers completed-docs -const LETTERS = _.times(26, n => String.fromCharCode('a'.charCodeAt(0) + n)); - -export function randomWord(maxLength: number = 13): string { - return _.sampleSize(LETTERS, _.random(1, maxLength)).join(''); -} - -export function randomSentence(): string { - const numWords = _.random(3, 64); - return _.capitalize( - _.times(numWords, () => randomWord()) - .join(' ') - .concat('.'), - ); -} - -export function randomDocs(): DocumentedItem { - return { - doc: randomSentence(), - line: _.random(1, 65536), - file: _.capitalize(randomWord()).concat('.sol'), - }; -} - -export function randomBoolean(): boolean { - return _.random(0, 1) === 1; -} - -export function randomType(): string { - return _.sampleSize(['uint256', 'bytes32', 'bool', 'uint32', 'int256', 'int64', 'uint8'], 1)[0]; -} - -export function randomStorageLocation(): StorageLocation { - return _.sampleSize([StorageLocation.Default, StorageLocation.Memory, StorageLocation.Storage])[0]; -} - -export function randomContractKind(): ContractKind { - return _.sampleSize([ContractKind.Contract, ContractKind.Interface, ContractKind.Library])[0]; -} - -export function randomMutability(): StateMutability { - return _.sampleSize([ - StateMutability.Nonpayable, - StateMutability.Payable, - StateMutability.Pure, - StateMutability.View, - ])[0]; -} - -export function randomVisibility(): Visibility { - return _.sampleSize([Visibility.External, Visibility.Internal, Visibility.Public, Visibility.Private])[0]; -} - -export function randomFunctionKind(): FunctionKind { - return _.sampleSize([FunctionKind.Constructor, FunctionKind.Fallback, FunctionKind.Function])[0]; -} - -export function randomParameters(): ParamDocsMap { - const numParams = _.random(0, 7); - return _.zipObject(_.times(numParams, () => randomWord()), _.times(numParams, idx => randomParameter(idx))); -} - -export function randomParameter(order: number, fields?: Partial): ParamDocs { - return { - ...randomDocs(), - type: randomType(), - indexed: randomBoolean(), - storageLocation: randomStorageLocation(), - order, - ...fields, - }; -} - -export function randomEvent(fields?: Partial): EventDocs { - return { - ...randomDocs(), - contract: `${randomWord()}Contract`, - name: `${randomWord()}Event`, - parameters: randomParameters(), - ...fields, - }; -} - -export function randomMethod(fields?: Partial): MethodDocs { - return { - ...randomDocs(), - contract: `${randomWord()}Contract`, - name: `${randomWord()}Method`, - kind: randomFunctionKind(), - isAccessor: randomBoolean(), - stateMutability: randomMutability(), - visibility: randomVisibility(), - returns: randomParameters(), - parameters: randomParameters(), - ...fields, - }; -} - -export function randomStruct(fields?: Partial): StructDocs { - return { - ...randomDocs(), - contract: `${randomWord()}Contract`, - fields: randomParameters(), - ...fields, - }; -} - -export function randomEnum(fields?: Partial): EnumDocs { - return { - ...randomDocs(), - contract: `${randomWord()}Contract`, - values: _.mapValues( - _.groupBy( - _.times(_.random(1, 8), i => ({ - ...randomDocs(), - value: i, - name: randomWord(), - })), - 'name', - ), - v => (_.omit(v[0], 'name') as any) as EnumValueDocs, - ), - ...fields, - }; -} - -export function randomContract(contractName: string, fields?: Partial): ContractDocs { - return { - ...randomDocs(), - kind: randomContractKind(), - inherits: [], - events: _.times(_.random(1, 4), () => randomEvent({ contract: contractName })), - methods: _.times(_.random(1, 4), () => randomMethod({ contract: contractName })), - structs: _.mapValues( - _.groupBy( - _.times(_.random(1, 4), () => ({ - ...randomStruct({ contract: contractName }), - name: `${randomWord()}Struct`, - })), - 'name', - ), - v => (_.omit(v[0], 'name') as any) as StructDocs, - ), - enums: _.mapValues( - _.groupBy( - _.times(_.random(1, 4), () => ({ - ...randomEnum({ contract: contractName }), - name: `${randomWord()}Enum`, - })), - 'name', - ), - v => (_.omit(v[0], 'name') as any) as EnumDocs, - ), - ...fields, - }; -} diff --git a/packages/sol-doc/tsconfig.json b/packages/sol-doc/tsconfig.json deleted file mode 100644 index 2ee711adcc..0000000000 --- a/packages/sol-doc/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../tsconfig", - "compilerOptions": { - "outDir": "lib", - "rootDir": "." - }, - "include": ["./src/**/*", "./test/**/*"] -} diff --git a/packages/sol-doc/tslint.json b/packages/sol-doc/tslint.json deleted file mode 100644 index dd9053357e..0000000000 --- a/packages/sol-doc/tslint.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": ["@0x/tslint-config"] -} diff --git a/packages/sol-profiler/.npmignore b/packages/sol-profiler/.npmignore deleted file mode 100644 index ea588d4859..0000000000 --- a/packages/sol-profiler/.npmignore +++ /dev/null @@ -1,9 +0,0 @@ -# Blacklist all files -.* -* -# Whitelist lib -!lib/**/* -# Blacklist tests and publish scripts -/lib/test/* -/lib/monorepo_scripts/ -# Package specific ignore diff --git a/packages/sol-profiler/CHANGELOG.json b/packages/sol-profiler/CHANGELOG.json deleted file mode 100644 index 6cb70a82c2..0000000000 --- a/packages/sol-profiler/CHANGELOG.json +++ /dev/null @@ -1,388 +0,0 @@ -[ - { - "version": "4.1.0", - "changes": [ - { - "note": "Make sol-profiler (mostly) work again", - "pr": 2607 - } - ], - "timestamp": 1594788383 - }, - { - "timestamp": 1592969527, - "version": "4.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1582623685, - "version": "4.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1581204851, - "version": "4.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1580988106, - "version": "4.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1580811564, - "version": "4.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1579682890, - "version": "4.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1578272714, - "version": "4.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1576540892, - "version": "4.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1575931811, - "version": "4.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "4.0.0", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1575296764 - }, - { - "version": "3.2.0-beta.4", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1575290197 - }, - { - "version": "3.2.0-beta.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1574238768 - }, - { - "version": "3.2.0-beta.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1574030254 - }, - { - "version": "3.2.0-beta.1", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1573159180 - }, - { - "version": "3.2.0-beta.0", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1570135330 - }, - { - "timestamp": 1568744790, - "version": "3.1.14", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1567521715, - "version": "3.1.13", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1566446343, - "version": "3.1.12", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1565296576, - "version": "3.1.11", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1564604963, - "version": "3.1.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563957393, - "version": "3.1.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563006338, - "version": "3.1.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1558712885, - "version": "3.1.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1557507213, - "version": "3.1.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.1.5", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1554997931 - }, - { - "timestamp": 1553183790, - "version": "3.1.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1553091633, - "version": "3.1.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.1.2", - "changes": [ - { - "note": "Bug fixes related to stack parameters parsing", - "pr": 1663 - } - ], - "timestamp": 1551479279 - }, - { - "timestamp": 1551299797, - "version": "3.1.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.1.0", - "changes": [ - { - "note": "Add support for Ganache", - "pr": 1647 - } - ], - "timestamp": 1551220833 - }, - { - "version": "3.0.0", - "changes": [ - { - "note": "Big @0x/sol-profiler overhaul. It now has a bunch of new features", - "pr": 1638 - }, - { - "note": "Added a CLI interface for reporting non line-based profiling info", - "pr": 1638 - }, - { - "note": "Add memory consumption analysis", - "pr": 1638 - }, - { - "note": "Add calldata analysis", - "pr": 1638 - } - ], - "timestamp": 1551130135 - }, - { - "timestamp": 1549733923, - "version": "2.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1549547375 - }, - { - "timestamp": 1549452781, - "version": "2.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.1", - "changes": [ - { - "note": "Fix a bug when some parts of the profiling report were missing because of the coverage ignore lines", - "pr": 1535 - } - ], - "timestamp": 1549373905 - }, - { - "version": "2.0.0", - "changes": [ - { - "note": "Upgrade the bignumber.js to v8.0.2", - "pr": 1517 - } - ] - }, - { - "timestamp": 1547747677, - "version": "1.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547561734, - "version": "1.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547225310, - "version": "1.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.0", - "changes": [ - { - "note": "Initial release as a separate package. For historical entries see @0x/sol-tracing-utils", - "pr": 1492 - } - ] - } -] diff --git a/packages/sol-profiler/CHANGELOG.md b/packages/sol-profiler/CHANGELOG.md deleted file mode 100644 index 6f510d9f2b..0000000000 --- a/packages/sol-profiler/CHANGELOG.md +++ /dev/null @@ -1,173 +0,0 @@ - - -CHANGELOG - -## v4.1.0 - _July 15, 2020_ - - * Make sol-profiler (mostly) work again (#2607) - -## v4.0.9 - _June 24, 2020_ - - * Dependencies updated - -## v4.0.8 - _February 25, 2020_ - - * Dependencies updated - -## v4.0.7 - _February 8, 2020_ - - * Dependencies updated - -## v4.0.6 - _February 6, 2020_ - - * Dependencies updated - -## v4.0.5 - _February 4, 2020_ - - * Dependencies updated - -## v4.0.4 - _January 22, 2020_ - - * Dependencies updated - -## v4.0.3 - _January 6, 2020_ - - * Dependencies updated - -## v4.0.2 - _December 17, 2019_ - - * Dependencies updated - -## v4.0.1 - _December 9, 2019_ - - * Dependencies updated - -## v4.0.0 - _December 2, 2019_ - - * Dependencies updated - -## v3.2.0-beta.4 - _December 2, 2019_ - - * Dependencies updated - -## v3.2.0-beta.3 - _November 20, 2019_ - - * Dependencies updated - -## v3.2.0-beta.2 - _November 17, 2019_ - - * Dependencies updated - -## v3.2.0-beta.1 - _November 7, 2019_ - - * Dependencies updated - -## v3.2.0-beta.0 - _October 3, 2019_ - - * Dependencies updated - -## v3.1.14 - _September 17, 2019_ - - * Dependencies updated - -## v3.1.13 - _September 3, 2019_ - - * Dependencies updated - -## v3.1.12 - _August 22, 2019_ - - * Dependencies updated - -## v3.1.11 - _August 8, 2019_ - - * Dependencies updated - -## v3.1.10 - _July 31, 2019_ - - * Dependencies updated - -## v3.1.9 - _July 24, 2019_ - - * Dependencies updated - -## v3.1.8 - _July 13, 2019_ - - * Dependencies updated - -## v3.1.7 - _May 24, 2019_ - - * Dependencies updated - -## v3.1.6 - _May 10, 2019_ - - * Dependencies updated - -## v3.1.5 - _April 11, 2019_ - - * Dependencies updated - -## v3.1.4 - _March 21, 2019_ - - * Dependencies updated - -## v3.1.3 - _March 20, 2019_ - - * Dependencies updated - -## v3.1.2 - _March 1, 2019_ - - * Bug fixes related to stack parameters parsing (#1663) - -## v3.1.1 - _February 27, 2019_ - - * Dependencies updated - -## v3.1.0 - _February 26, 2019_ - - * Add support for Ganache (#1647) - -## v3.0.0 - _February 25, 2019_ - - * Big @0x/sol-profiler overhaul. It now has a bunch of new features (#1638) - * Added a CLI interface for reporting non line-based profiling info (#1638) - * Add memory consumption analysis (#1638) - * Add calldata analysis (#1638) - -## v2.0.4 - _February 9, 2019_ - - * Dependencies updated - -## v2.0.3 - _February 7, 2019_ - - * Dependencies updated - -## v2.0.2 - _February 6, 2019_ - - * Dependencies updated - -## v2.0.1 - _February 5, 2019_ - - * Fix a bug when some parts of the profiling report were missing because of the coverage ignore lines (#1535) - -## v2.0.0 - _Invalid date_ - - * Upgrade the bignumber.js to v8.0.2 (#1517) - -## v1.0.3 - _January 17, 2019_ - - * Dependencies updated - -## v1.0.2 - _January 15, 2019_ - - * Dependencies updated - -## v1.0.1 - _January 11, 2019_ - - * Dependencies updated - -## v1.0.0 - _Invalid date_ - - * Initial release as a separate package. For historical entries see @0x/sol-tracing-utils (#1492) diff --git a/packages/sol-profiler/README.md b/packages/sol-profiler/README.md deleted file mode 100644 index c15ed3ad47..0000000000 --- a/packages/sol-profiler/README.md +++ /dev/null @@ -1,75 +0,0 @@ -## @0x/sol-profiler - -Solidity line-by-line gas profiler. - -### Read the [Documentation](https://0x.org/docs/tools/sol-profiler). - -## Installation - -```bash -yarn add @0x/sol-profiler -``` - -**Import** - -```javascript -import { ProfilerSubprovider } from '@0x/sol-profiler'; -``` - -or - -```javascript -var ProfilerSubprovider = require('@0x/sol-profiler').ProfilerSubprovider; -``` - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install dependencies - -If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: - -```bash -yarn config set workspaces-experimental true -``` - -Then install dependencies - -```bash -yarn install -``` - -### Build - -To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory: - -```bash -PKG=@0x/sol-profiler yarn build -``` - -Or continuously rebuild on change: - -```bash -PKG=@0x/sol-profiler yarn watch -``` - -### Clean - -```bash -yarn clean -``` - -### Lint - -```bash -yarn lint -``` - -### Run Tests - -```bash -yarn test -``` diff --git a/packages/sol-profiler/docs/reference.mdx b/packages/sol-profiler/docs/reference.mdx deleted file mode 100644 index 5b60272a3b..0000000000 --- a/packages/sol-profiler/docs/reference.mdx +++ /dev/null @@ -1,738 +0,0 @@ - - -# Class: AbstractArtifactAdapter - - -## Methods - -### `Abstract` collectContractsDataAsync - -▸ **collectContractsDataAsync**(): *`Promise`* - -*Defined in [sol-tracing-utils/src/artifact_adapters/abstract_artifact_adapter.ts:4](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-tracing-utils/src/artifact_adapters/abstract_artifact_adapter.ts#L4)* - -**Returns:** *`Promise`* - -
- -# Class: SolCompilerArtifactAdapter - - -## Constructors - - - -\+ **new SolCompilerArtifactAdapter**(`artifactsPath?`: undefined | string, `sourcesPath?`: undefined | string): *[SolCompilerArtifactAdapter](#class-solcompilerartifactadapter)* - -*Defined in [sol-tracing-utils/src/artifact_adapters/sol_compiler_artifact_adapter.ts:18](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-tracing-utils/src/artifact_adapters/sol_compiler_artifact_adapter.ts#L18)* - -Instantiates a SolCompilerArtifactAdapter - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`artifactsPath?` | undefined \| string | Path to your artifacts directory | -`sourcesPath?` | undefined \| string | Path to your contract sources directory | - -**Returns:** *[SolCompilerArtifactAdapter](#class-solcompilerartifactadapter)* - -## Methods - -### collectContractsDataAsync - -▸ **collectContractsDataAsync**(): *`Promise`* - -*Overrides [AbstractArtifactAdapter](_sol_tracing_utils_src_artifact_adapters_abstract_artifact_adapter_.abstractartifactadapter.md).[collectContractsDataAsync](#abstract-collectcontractsdataasync)* - -*Defined in [sol-tracing-utils/src/artifact_adapters/sol_compiler_artifact_adapter.ts:44](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-tracing-utils/src/artifact_adapters/sol_compiler_artifact_adapter.ts#L44)* - -**Returns:** *`Promise`* - -
- -# Class: TruffleArtifactAdapter - - -## Constructors - - - -\+ **new TruffleArtifactAdapter**(`projectRoot`: string, `solcVersion`: string): *[TruffleArtifactAdapter](#class-truffleartifactadapter)* - -*Defined in [sol-tracing-utils/src/artifact_adapters/truffle_artifact_adapter.ts:29](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-tracing-utils/src/artifact_adapters/truffle_artifact_adapter.ts#L29)* - -Instantiates a TruffleArtifactAdapter - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`projectRoot` | string | Path to the truffle project's root directory | -`solcVersion` | string | Solidity version with which to compile all the contracts | - -**Returns:** *[TruffleArtifactAdapter](#class-truffleartifactadapter)* - -## Methods - -### collectContractsDataAsync - -▸ **collectContractsDataAsync**(): *`Promise`* - -*Overrides [AbstractArtifactAdapter](_sol_tracing_utils_src_artifact_adapters_abstract_artifact_adapter_.abstractartifactadapter.md).[collectContractsDataAsync](#abstract-collectcontractsdataasync)* - -*Defined in [sol-tracing-utils/src/artifact_adapters/truffle_artifact_adapter.ts:40](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-tracing-utils/src/artifact_adapters/truffle_artifact_adapter.ts#L40)* - -**Returns:** *`Promise`* - -
- - - - - - - - - - - - - - - - - - - - -## Type aliases - -### Callback - -Ƭ **Callback**: *function* - -*Defined in [subproviders/src/types.ts:131](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L131)* - -#### Type declaration: - -▸ (): *void* - -___ - - - -### ErrorCallback - -Ƭ **ErrorCallback**: *function* - -*Defined in [subproviders/src/types.ts:130](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L130)* - -#### Type declaration: - -▸ (`err`: `Error` | null, `data?`: any): *void* - -**Parameters:** - -Name | Type | ------- | ------ | -`err` | `Error` \| null | -`data?` | any | - -___ - - - -### NextCallback - -Ƭ **NextCallback**: *function* - -*Defined in [subproviders/src/types.ts:133](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L133)* - -#### Type declaration: - -▸ (`callback?`: [OnNextCompleted](#onnextcompleted)): *void* - -**Parameters:** - -Name | Type | ------- | ------ | -`callback?` | [OnNextCompleted](#onnextcompleted) | - -___ - -### OnNextCompleted - -Ƭ **OnNextCompleted**: *function* - -*Defined in [subproviders/src/types.ts:132](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L132)* - -#### Type declaration: - -▸ (`err`: `Error` | null, `result`: any, `cb`: [Callback](#callback)): *void* - -**Parameters:** - -Name | Type | ------- | ------ | -`err` | `Error` \| null | -`result` | any | -`cb` | [Callback](#callback) | - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# Interface: JSONRPCRequestPayload - - -## Properties - -### id - -• **id**: *number* - -*Defined in [ethereum-types/src/index.ts:331](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L331)* - -___ - -### jsonrpc - -• **jsonrpc**: *string* - -*Defined in [ethereum-types/src/index.ts:332](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L332)* - -___ - -### method - -• **method**: *string* - -*Defined in [ethereum-types/src/index.ts:330](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L330)* - -___ - -### params - -• **params**: *any[]* - -*Defined in [ethereum-types/src/index.ts:329](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L329)* - -
- -# Interface: JSONRPCResponseError - - -## Properties - -### code - -• **code**: *number* - -*Defined in [ethereum-types/src/index.ts:337](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L337)* - -___ - -### message - -• **message**: *string* - -*Defined in [ethereum-types/src/index.ts:336](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L336)* - -
- -# Interface: JSONRPCResponsePayload - - -## Properties - -### `Optional` error - -• **error**? : *[JSONRPCResponseError](#class-jsonrpcresponseerror)* - -*Defined in [ethereum-types/src/index.ts:344](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L344)* - -___ - -### id - -• **id**: *number* - -*Defined in [ethereum-types/src/index.ts:342](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L342)* - -___ - -### jsonrpc - -• **jsonrpc**: *string* - -*Defined in [ethereum-types/src/index.ts:343](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L343)* - -___ - -### result - -• **result**: *any* - -*Defined in [ethereum-types/src/index.ts:341](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L341)* - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# Class: ProfilerSubprovider - -This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface. -ProfilerSubprovider is used to profile Solidity code while running tests. - - -## Constructors - - - -\+ **new ProfilerSubprovider**(`artifactAdapter`: `AbstractArtifactAdapter`, `defaultFromAddress`: string, `isVerbose`: boolean): *[ProfilerSubprovider](#class-profilersubprovider)* - -*Overrides void* - -*Defined in [sol-profiler/src/profiler_subprovider.ts:30](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-profiler/src/profiler_subprovider.ts#L30)* - -Instantiates a ProfilerSubprovider instance - -**Parameters:** - -Name | Type | Default | Description | ------- | ------ | ------ | ------ | -`artifactAdapter` | `AbstractArtifactAdapter` | - | Adapter for used artifacts format (0x, truffle, giveth, etc.) | -`defaultFromAddress` | string | - | default from address to use when sending transactions | -`isVerbose` | boolean | true | If true, we will log any unknown transactions. Otherwise we will ignore them | - -**Returns:** *[ProfilerSubprovider](#class-profilersubprovider)* - -## Methods - -### emitPayloadAsync - -▸ **emitPayloadAsync**(`payload`: `Partial`): *`Promise`* - - - -Defined in subproviders/lib/src/subproviders/subprovider.d.ts:25 - -Emits a JSON RPC payload that will then be handled by the ProviderEngine instance -this subprovider is a part of. The payload will cascade down the subprovider middleware -stack until finding the responsible entity for handling the request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `Partial` | JSON RPC payload | - -**Returns:** *`Promise`* - -JSON RPC response payload - -___ - -### handleRequest - -▸ **handleRequest**(`payload`: `JSONRPCRequestPayload`, `next`: [NextCallback](#nextcallback), `_end`: [ErrorCallback](#errorcallback)): *`Promise`* - - - -*Overrides void* - -Defined in sol-tracing-utils/lib/src/trace_collection_subprovider.d.ts:42 - -This method conforms to the web3-provider-engine interface. -It is called internally by the ProviderEngine when it is this subproviders -turn to handle a JSON RPC request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `JSONRPCRequestPayload` | JSON RPC payload | -`next` | [NextCallback](#nextcallback) | Callback to call if this subprovider decides not to handle the request | -`_end` | [ErrorCallback](#errorcallback) | Callback to call if subprovider handled the request and wants to pass back the request. | - -**Returns:** *`Promise`* - -___ - -### setEngine - -▸ **setEngine**(`engine`: `Web3ProviderEngine`): *void* - - - -*Overrides void* - -Defined in sol-tracing-utils/lib/src/trace_collection_subprovider.d.ts:49 - -Set's the subprovider's engine to the ProviderEngine it is added to. -This is only called within the ProviderEngine source code, do not call -directly. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`engine` | `Web3ProviderEngine` | The ProviderEngine this subprovider is added to | - -**Returns:** *void* - -___ - -### start - -▸ **start**(): *void* - - - -Defined in sol-tracing-utils/lib/src/trace_collection_subprovider.d.ts:29 - -Starts trace collection - -**Returns:** *void* - -___ - -### stop - -▸ **stop**(): *void* - - - -Defined in sol-tracing-utils/lib/src/trace_collection_subprovider.d.ts:33 - -Stops trace collection - -**Returns:** *void* - -___ - -### writeProfilerOutputAsync - -▸ **writeProfilerOutputAsync**(): *`Promise`* - -*Defined in [sol-profiler/src/profiler_subprovider.ts:104](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-profiler/src/profiler_subprovider.ts#L104)* - -Write the test profiler results to a file in Istanbul format. - -**Returns:** *`Promise`* - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# Interface: JSONRPCRequestPayloadWithMethod - - -## Properties - -### id - -• **id**: *number* - - - -Defined in ethereum-types/lib/index.d.ts:268 - -___ - -### jsonrpc - -• **jsonrpc**: *string* - - - -Defined in ethereum-types/lib/index.d.ts:269 - -___ - -### method - -• **method**: *string* - -*Overrides void* - -*Defined in [subproviders/src/types.ts:136](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L136)* - -___ - -### params - -• **params**: *any[]* - - - -Defined in ethereum-types/lib/index.d.ts:266 - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -## Type aliases - - - - - - - - - - - - -## Type aliases - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -## Functions - -### `Const` profilerHandler - -▸ **profilerHandler**(`contractData`: `ContractData`, `subtrace`: [Subtrace](#subtrace), `pcToSourceRange`: object, `fileIndex`: number): *`Coverage`* - -*Defined in [sol-profiler/src/profiler_subprovider.ts:118](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-profiler/src/profiler_subprovider.ts#L118)* - -Computed partial coverage for a single file & subtrace for the purposes of -gas profiling. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`contractData` | `ContractData` | Contract metadata (source, srcMap, bytecode) | -`subtrace` | [Subtrace](#subtrace) | A subset of a transcation/call trace that was executed within that contract | -`pcToSourceRange` | object | A mapping from program counters to source ranges | -`fileIndex` | number | Index of a file to compute coverage for | - -**Returns:** *`Coverage`* - -Partial istanbul coverage for that file & subtrace - -
- - - -
- - - -
- - - -
- diff --git a/packages/sol-profiler/package.json b/packages/sol-profiler/package.json deleted file mode 100644 index 1ad58399b3..0000000000 --- a/packages/sol-profiler/package.json +++ /dev/null @@ -1,60 +0,0 @@ -{ - "name": "@0x/sol-profiler", - "version": "4.1.0", - "engines": { - "node": ">=6.12" - }, - "description": "Generate profiler reports for Solidity code", - "main": "lib/src/index.js", - "types": "lib/src/index.d.ts", - "scripts": { - "build": "tsc -b", - "build:ci": "yarn build", - "lint": "tslint --format stylish --project .", - "fix": "tslint --fix --format stylish --project .", - "clean": "shx rm -rf lib src/artifacts generated_docs", - "diff_docs": "git diff --exit-code ./docs", - "s3:sync_md_docs": "aws s3 sync ./docs s3://docs-markdown/${npm_package_name}/v${npm_package_version} --profile 0xproject --region us-east-1 --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers", - "docs:md": "ts-doc-gen --sourceDir='$PROJECT_FILES' --output=$MD_FILE_DIR --fileExtension=mdx --tsconfig=./typedoc-tsconfig.json", - "docs:json": "typedoc --excludePrivate --excludeExternals --excludeProtected --ignoreCompilerErrors --target ES5 --tsconfig typedoc-tsconfig.json --json $JSON_FILE_PATH $PROJECT_FILES" - }, - "config": { - "postpublish": { - "assets": [] - } - }, - "repository": { - "type": "git", - "url": "https://github.com/0xProject/0x-monorepo.git" - }, - "license": "Apache-2.0", - "bugs": { - "url": "https://github.com/0xProject/0x-monorepo/issues" - }, - "homepage": "https://github.com/0xProject/0x-monorepo/packages/sol-profiler/README.md", - "dependencies": { - "@0x/sol-tracing-utils": "^7.1.0", - "@0x/subproviders": "^6.1.1", - "@0x/typescript-typings": "^5.1.1", - "@0x/utils": "^5.5.1", - "ethereum-types": "^3.2.0", - "ethereumjs-util": "^5.1.1", - "lodash": "^4.17.11", - "web3-provider-engine": "14.0.6" - }, - "devDependencies": { - "@0x/ts-doc-gen": "^0.0.22", - "@0x/tslint-config": "^4.1.0", - "@types/node": "12.12.54", - "@types/web3-provider-engine": "^14.0.0", - "npm-run-all": "^4.1.2", - "shx": "^0.2.2", - "tslint": "5.11.0", - "typedoc": "^0.15.0", - "typescript": "3.0.1" - }, - "publishConfig": { - "access": "public" - }, - "gitHead": "4f91bfd907996b2f4dd383778b50c479c2602b56" -} diff --git a/packages/sol-profiler/src/cost_utils.ts b/packages/sol-profiler/src/cost_utils.ts deleted file mode 100644 index 86d6328a12..0000000000 --- a/packages/sol-profiler/src/cost_utils.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { constants, TraceInfo } from '@0x/sol-tracing-utils'; -import { logUtils } from '@0x/utils'; -import { OpCode } from 'ethereum-types'; -import { stripHexPrefix } from 'ethereumjs-util'; -import * as _ from 'lodash'; - -const ZERO_BYTE_CALL_DATA_COST = 4; -const NON_ZERO_BYTE_CALL_DATA_COST = 16; -const WORD_SIZE = 32; -const G_MEMORY = 3; -const G_QUAD_COEF = 512; -const HEX_BASE = 16; -const G_COPY = 3; - -export const costUtils = { - reportCallDataCost(traceInfo: TraceInfo): number { - if (traceInfo.dataIfExists === undefined) { - // No call data to report - return 0; - } - const callData = traceInfo.dataIfExists; - const callDataBuf = Buffer.from(stripHexPrefix(callData), 'hex'); - const { true: zeroBytesCountIfExist, false: nonZeroBytesCountIfExist } = _.countBy( - callDataBuf, - byte => byte === 0, - ); - const zeroBytesCost = (zeroBytesCountIfExist || 0) * ZERO_BYTE_CALL_DATA_COST; - const nonZeroBytesCost = (nonZeroBytesCountIfExist || 0) * NON_ZERO_BYTE_CALL_DATA_COST; - const callDataCost = zeroBytesCost + nonZeroBytesCost; - logUtils.header('Call data breakdown', '-'); - logUtils.table({ - 'call data size (bytes)': callDataBuf.byteLength, - callDataCost, - zeroBytesCost, - nonZeroBytesCost, - zeroBytesCountIfExist, - nonZeroBytesCountIfExist, - }); - return callDataCost; - }, - reportMemoryCost(traceInfo: TraceInfo): number { - const structLogs = traceInfo.trace.structLogs; - const MEMORY_OPCODES = [OpCode.MLoad, OpCode.MStore, OpCode.MStore8]; - const CALL_DATA_OPCODES = [OpCode.CallDataCopy]; - const memoryLogs = _.filter(structLogs, structLog => - _.includes([...MEMORY_OPCODES, ...CALL_DATA_OPCODES], structLog.op), - ); - const memoryLocationsAccessed = _.map(memoryLogs, structLog => { - if (_.includes(CALL_DATA_OPCODES, structLog.op)) { - const memoryOffsetStackOffset = constants.opCodeToParamToStackOffset[structLog.op as any].memoryOffset; - const lengthStackOffset = constants.opCodeToParamToStackOffset[structLog.op as any].length; - const memOffset = parseInt( - structLog.stack[structLog.stack.length - memoryOffsetStackOffset - 1], - HEX_BASE, - ); - const length = parseInt(structLog.stack[structLog.stack.length - lengthStackOffset - 1], HEX_BASE); - return memOffset + length; - } else { - const memoryLocationStackOffset = constants.opCodeToParamToStackOffset[structLog.op].offset; - return parseInt(structLog.stack[structLog.stack.length - memoryLocationStackOffset - 1], HEX_BASE); - } - }); - const highestMemoryLocationAccessed = _.max(memoryLocationsAccessed); - return costUtils._printMemoryCost(highestMemoryLocationAccessed); - }, - reportCopyingCost(traceInfo: TraceInfo): number { - const structLogs = traceInfo.trace.structLogs; - const COPY_OPCODES = [OpCode.CallDataCopy]; - const copyLogs = _.filter(structLogs, structLog => _.includes(COPY_OPCODES, structLog.op)); - const copyCosts = _.map(copyLogs, structLog => { - const lengthStackOffset = constants.opCodeToParamToStackOffset[structLog.op as any].length; - const length = parseInt(structLog.stack[structLog.stack.length - lengthStackOffset - 1], HEX_BASE); - return Math.ceil(length / WORD_SIZE) * G_COPY; - }); - return _.sum(copyCosts); - }, - reportOpcodesCost(traceInfo: TraceInfo): number { - const structLogs = traceInfo.trace.structLogs; - const gasCosts = _.map(structLogs, structLog => structLog.gasCost); - const gasCost = _.sum(gasCosts); - return gasCost; - }, - _printMemoryCost(highestMemoryLocationAccessed?: number): number { - if (highestMemoryLocationAccessed === undefined) { - return 0; - } - const memoryWordsUsed = Math.ceil((highestMemoryLocationAccessed + WORD_SIZE) / WORD_SIZE); - const linearMemoryCost = G_MEMORY * memoryWordsUsed; - const quadraticMemoryCost = Math.floor((memoryWordsUsed * memoryWordsUsed) / G_QUAD_COEF); - const memoryCost = linearMemoryCost + quadraticMemoryCost; - logUtils.header('Memory breakdown', '-'); - logUtils.table({ - 'memoryCost = linearMemoryCost + quadraticMemoryCost': memoryCost, - linearMemoryCost, - quadraticMemoryCost, - highestMemoryLocationAccessed, - memoryWordsUsed, - }); - return memoryCost; - }, -}; diff --git a/packages/sol-profiler/src/globals.d.ts b/packages/sol-profiler/src/globals.d.ts deleted file mode 100644 index e799b35298..0000000000 --- a/packages/sol-profiler/src/globals.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// tslint:disable:completed-docs -declare module '*.json' { - const json: any; - /* tslint:disable */ - export default json; - /* tslint:enable */ -} diff --git a/packages/sol-profiler/src/index.ts b/packages/sol-profiler/src/index.ts deleted file mode 100644 index 3182acfa34..0000000000 --- a/packages/sol-profiler/src/index.ts +++ /dev/null @@ -1,23 +0,0 @@ -export { - AbstractArtifactAdapter, - SolCompilerArtifactAdapter, - TruffleArtifactAdapter, - ContractData, - SourceCodes, - Sources, -} from '@0x/sol-tracing-utils'; - -// HACK: ProfilerSubprovider is a hacky way to do profiling using coverage tools. Not production ready -export { ProfilerSubprovider } from './profiler_subprovider'; - -export { JSONRPCRequestPayload, JSONRPCResponsePayload, JSONRPCResponseError } from 'ethereum-types'; - -export { - JSONRPCRequestPayloadWithMethod, - NextCallback, - ErrorCallback, - OnNextCompleted, - Callback, -} from '@0x/subproviders'; - -export import Web3ProviderEngine = require('web3-provider-engine'); diff --git a/packages/sol-profiler/src/profiler_subprovider.ts b/packages/sol-profiler/src/profiler_subprovider.ts deleted file mode 100644 index 9367f05e73..0000000000 --- a/packages/sol-profiler/src/profiler_subprovider.ts +++ /dev/null @@ -1,163 +0,0 @@ -import { - AbstractArtifactAdapter, - collectCoverageEntries, - ContractData, - Coverage, - SingleFileSubtraceHandler, - SourceRange, - Subtrace, - SubTraceInfo, - TraceCollector, - TraceInfo, - TraceInfoSubprovider, - utils, -} from '@0x/sol-tracing-utils'; -import { logUtils } from '@0x/utils'; -import { stripHexPrefix } from 'ethereumjs-util'; -import * as _ from 'lodash'; - -import { costUtils } from './cost_utils'; - -const CREATE_COST = 32000; -const BASE_COST = 21000; -const DEPLOYED_BYTE_COST = 200; - -/** - * This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface. - * ProfilerSubprovider is used to profile Solidity code while running tests. - */ -export class ProfilerSubprovider extends TraceInfoSubprovider { - private readonly _profilerCollector: TraceCollector; - /** - * Instantiates a ProfilerSubprovider instance - * @param artifactAdapter Adapter for used artifacts format (0x, truffle, giveth, etc.) - * @param defaultFromAddress default from address to use when sending transactions - * @param isVerbose If true, we will log any unknown transactions. Otherwise we will ignore them - */ - constructor(artifactAdapter: AbstractArtifactAdapter, defaultFromAddress: string, isVerbose: boolean = true) { - const traceCollectionSubproviderConfig = { - shouldCollectTransactionTraces: true, - shouldCollectGasEstimateTraces: false, - shouldCollectCallTraces: false, - }; - super(defaultFromAddress, traceCollectionSubproviderConfig); - this._profilerCollector = new TraceCollector(artifactAdapter, isVerbose, profilerHandler); - } - protected async _handleSubTraceInfoAsync(subTraceInfo: SubTraceInfo): Promise { - await this._profilerCollector.computeSingleTraceCoverageAsync(subTraceInfo); - } - // tslint:disable prefer-function-over-method - protected async _handleTraceInfoAsync(traceInfo: TraceInfo): Promise { - const receipt = await this._web3Wrapper.getTransactionReceiptIfExistsAsync(traceInfo.txHash); - if (receipt === undefined) { - return; - } - if (receipt.gasUsed === BASE_COST) { - // Value transfer - return; - } - logUtils.header(`Profiling data for ${traceInfo.txHash}`); - const callDataCost = costUtils.reportCallDataCost(traceInfo); - const memoryCost = costUtils.reportMemoryCost(traceInfo); - const opcodesCost = costUtils.reportOpcodesCost(traceInfo); - const dataCopyingCost = costUtils.reportCopyingCost(traceInfo); - const newContractCost = CREATE_COST; - const transactionBaseCost = BASE_COST; - let totalCost = callDataCost + opcodesCost + BASE_COST; - logUtils.header('Final breakdown', '-'); - if (_.isString(receipt.contractAddress)) { - const code = await this._web3Wrapper.getContractCodeAsync(receipt.contractAddress); - const codeBuff = Buffer.from(stripHexPrefix(code), 'hex'); - const codeLength = codeBuff.length; - const contractSizeCost = codeLength * DEPLOYED_BYTE_COST; - totalCost += contractSizeCost + CREATE_COST; - logUtils.table({ - 'totalCost = callDataCost + opcodesCost + transactionBaseCost + newContractCost + contractSizeCost': totalCost, - callDataCost, - 'opcodesCost (including memoryCost and dataCopyingCost)': opcodesCost, - memoryCost, - dataCopyingCost, - transactionBaseCost, - contractSizeCost, - newContractCost, - }); - } else { - logUtils.table({ - 'totalCost = callDataCost + opcodesCost + transactionBaseCost': totalCost, - callDataCost, - 'opcodesCost (including memoryCost and dataCopyingCost)': opcodesCost, - memoryCost, - dataCopyingCost, - transactionBaseCost, - }); - } - const unknownGas = receipt.gasUsed - totalCost; - if (unknownGas !== 0) { - logUtils.warn( - `Unable to find the cause for ${unknownGas} gas. It's most probably an issue in sol-profiler. Please report on Github.`, - ); - } - } - /** - * Write the test profiler results to a file in Istanbul format. - */ - public async writeProfilerOutputAsync(): Promise { - await this._profilerCollector.writeOutputAsync(); - } -} - -/** - * Computed partial coverage for a single file & subtrace for the purposes of - * gas profiling. - * @param contractData Contract metadata (source, srcMap, bytecode) - * @param subtrace A subset of a transcation/call trace that was executed within that contract - * @param pcToSourceRange A mapping from program counters to source ranges - * @param fileIndex Index of a file to compute coverage for - * @return Partial istanbul coverage for that file & subtrace - */ -export const profilerHandler: SingleFileSubtraceHandler = ( - contractData: ContractData, - subtrace: Subtrace, - pcToSourceRange: { [programCounter: number]: SourceRange }, - fileIndex: number, -): Coverage => { - const absoluteFileName = contractData.sources[fileIndex]; - const profilerEntriesDescription = collectCoverageEntries(contractData.sourceCodes[fileIndex]); - const statementToGasConsumed: { [statementId: string]: number } = {}; - const statementIds = _.keys(profilerEntriesDescription.statementMap); - // `interestingStructLogs` are those that map back to source ranges within the current file. - // It also doesn't include any that cannot be mapped back - // This is a perf optimization reducing the work done in the loop over `statementIds`. - // TODO(logvinov): Optimize the loop below. - const interestingStructLogs = _.filter(subtrace, structLog => { - const sourceRange = pcToSourceRange[structLog.pc]; - if (sourceRange === undefined) { - return false; - } - return sourceRange.fileName === absoluteFileName; - }); - for (const statementId of statementIds) { - const statementDescription = profilerEntriesDescription.statementMap[statementId]; - const totalGasCost = _.sum( - _.map(interestingStructLogs, structLog => { - const sourceRange = pcToSourceRange[structLog.pc]; - if (utils.isRangeInside(sourceRange.location, statementDescription)) { - return structLog.gasCost; - } else { - return 0; - } - }), - ); - statementToGasConsumed[statementId] = totalGasCost; - } - const partialProfilerOutput = { - [absoluteFileName]: { - ...profilerEntriesDescription, - path: absoluteFileName, - f: {}, // I's meaningless in profiling context - s: statementToGasConsumed, - b: {}, // I's meaningless in profiling context - }, - }; - return partialProfilerOutput; -}; diff --git a/packages/sol-profiler/tsconfig.json b/packages/sol-profiler/tsconfig.json deleted file mode 100644 index 233008d61c..0000000000 --- a/packages/sol-profiler/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../tsconfig", - "compilerOptions": { - "outDir": "lib", - "rootDir": "." - }, - "include": ["./src/**/*"] -} diff --git a/packages/sol-profiler/tslint.json b/packages/sol-profiler/tslint.json deleted file mode 100644 index dd9053357e..0000000000 --- a/packages/sol-profiler/tslint.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": ["@0x/tslint-config"] -} diff --git a/packages/sol-profiler/typedoc-tsconfig.json b/packages/sol-profiler/typedoc-tsconfig.json deleted file mode 100644 index a4c669cb6d..0000000000 --- a/packages/sol-profiler/typedoc-tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "../../typedoc-tsconfig", - "compilerOptions": { - "outDir": "lib" - }, - "include": ["./src/**/*"] -} diff --git a/packages/sol-resolver/CHANGELOG.json b/packages/sol-resolver/CHANGELOG.json deleted file mode 100644 index 0faccb44e4..0000000000 --- a/packages/sol-resolver/CHANGELOG.json +++ /dev/null @@ -1,488 +0,0 @@ -[ - { - "version": "3.1.0", - "changes": [ - { - "note": "Make sol-profiler (mostly) work again", - "pr": 2607 - } - ], - "timestamp": 1594788383 - }, - { - "timestamp": 1592969527, - "version": "3.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1581204851, - "version": "3.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1576540892, - "version": "3.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1575931811, - "version": "3.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.0.0", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1575296764 - }, - { - "version": "2.1.0-beta.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1575290197 - }, - { - "version": "2.1.0-beta.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1574030254 - }, - { - "version": "2.1.0-beta.1", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1573159180 - }, - { - "version": "2.1.0-beta.0", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1570135330 - }, - { - "timestamp": 1568744790, - "version": "2.0.11", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1567521715, - "version": "2.0.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563957393, - "version": "2.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563006338, - "version": "2.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1554997931 - }, - { - "timestamp": 1553183790, - "version": "2.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1553091633, - "version": "2.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551220833, - "version": "2.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551130135, - "version": "2.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1549547375 - }, - { - "timestamp": 1549452781, - "version": "2.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.0", - "changes": [ - { - "note": "Upgrade the bignumber.js to v8.0.2", - "pr": 1517 - } - ], - "timestamp": 1549373905 - }, - { - "timestamp": 1547561734, - "version": "1.2.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547225310, - "version": "1.2.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.2.1", - "changes": [ - { - "note": "Add `absolutePath` to `ContractSource` type", - "pr": 1461 - }, - { - "note": "Add `SpyResolver` that records all resolved contracts data", - "pr": 1461 - } - ], - "timestamp": 1547040760 - }, - { - "version": "1.1.1", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544739608 - }, - { - "version": "1.1.0", - "changes": [ - { - "note": "NPMResolver now supports scoped packages", - "pr": 1311 - } - ], - "timestamp": 1544570656 - }, - { - "timestamp": 1542821676, - "version": "1.0.17", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.16", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1541740904 - }, - { - "timestamp": 1539871071, - "version": "1.0.15", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1538693146, - "version": "1.0.14", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1538475601, - "version": "1.0.13", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1538157789, - "version": "1.0.12", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537907159, - "version": "1.0.11", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537875740, - "version": "1.0.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537541580, - "version": "1.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1536142250, - "version": "1.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1535377027, - "version": "1.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1535133899, - "version": "1.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.5", - "changes": [ - { - "note": "Fix a bug where RelativeFSResolver would crash when trying to read a directory", - "pr": 909 - }, - { - "note": "Fix a bug where NpmResolver would crash when trying to read a directory", - "pr": 961 - } - ], - "timestamp": 1534210131 - }, - { - "timestamp": 1532619515, - "version": "1.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532614997, - "version": "1.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532605697, - "version": "1.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532357734, - "version": "1.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532043000, - "version": "1.0.0", - "changes": [ - { - "note": "Fix a bug in FsResolver where it tries to read directories as files", - "pr": 589 - }, - { - "note": "Fix a bug in NameResolver where it is not ignoring .sol files", - "pr": 589 - } - ] - }, - { - "timestamp": 1531149657, - "version": "0.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1529397769, - "version": "0.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.0.6", - "changes": [ - { - "note": "Incorrect publish that was unpublished" - } - ], - "timestamp": 1527810075 - }, - { - "timestamp": 1527009133, - "version": "0.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1525477860, - "version": "0.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1525428773, - "version": "0.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1524044013, - "version": "0.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - } -] diff --git a/packages/sol-resolver/CHANGELOG.md b/packages/sol-resolver/CHANGELOG.md deleted file mode 100644 index 4c62084e8b..0000000000 --- a/packages/sol-resolver/CHANGELOG.md +++ /dev/null @@ -1,217 +0,0 @@ - - -CHANGELOG - -## v3.1.0 - _July 15, 2020_ - - * Make sol-profiler (mostly) work again (#2607) - -## v3.0.4 - _June 24, 2020_ - - * Dependencies updated - -## v3.0.3 - _February 8, 2020_ - - * Dependencies updated - -## v3.0.2 - _December 17, 2019_ - - * Dependencies updated - -## v3.0.1 - _December 9, 2019_ - - * Dependencies updated - -## v3.0.0 - _December 2, 2019_ - - * Dependencies updated - -## v2.1.0-beta.3 - _December 2, 2019_ - - * Dependencies updated - -## v2.1.0-beta.2 - _November 17, 2019_ - - * Dependencies updated - -## v2.1.0-beta.1 - _November 7, 2019_ - - * Dependencies updated - -## v2.1.0-beta.0 - _October 3, 2019_ - - * Dependencies updated - -## v2.0.11 - _September 17, 2019_ - - * Dependencies updated - -## v2.0.10 - _September 3, 2019_ - - * Dependencies updated - -## v2.0.9 - _July 24, 2019_ - - * Dependencies updated - -## v2.0.8 - _July 13, 2019_ - - * Dependencies updated - -## v2.0.7 - _April 11, 2019_ - - * Dependencies updated - -## v2.0.6 - _March 21, 2019_ - - * Dependencies updated - -## v2.0.5 - _March 20, 2019_ - - * Dependencies updated - -## v2.0.4 - _February 26, 2019_ - - * Dependencies updated - -## v2.0.3 - _February 25, 2019_ - - * Dependencies updated - -## v2.0.2 - _February 7, 2019_ - - * Dependencies updated - -## v2.0.1 - _February 6, 2019_ - - * Dependencies updated - -## v2.0.0 - _February 5, 2019_ - - * Upgrade the bignumber.js to v8.0.2 (#1517) - -## v1.2.3 - _January 15, 2019_ - - * Dependencies updated - -## v1.2.2 - _January 11, 2019_ - - * Dependencies updated - -## v1.2.1 - _January 9, 2019_ - - * Add `absolutePath` to `ContractSource` type (#1461) - * Add `SpyResolver` that records all resolved contracts data (#1461) - -## v1.1.1 - _December 13, 2018_ - - * Dependencies updated - -## v1.1.0 - _December 11, 2018_ - - * NPMResolver now supports scoped packages (#1311) - -## v1.0.17 - _November 21, 2018_ - - * Dependencies updated - -## v1.0.16 - _November 9, 2018_ - - * Dependencies updated - -## v1.0.15 - _October 18, 2018_ - - * Dependencies updated - -## v1.0.14 - _October 4, 2018_ - - * Dependencies updated - -## v1.0.13 - _October 2, 2018_ - - * Dependencies updated - -## v1.0.12 - _September 28, 2018_ - - * Dependencies updated - -## v1.0.11 - _September 25, 2018_ - - * Dependencies updated - -## v1.0.10 - _September 25, 2018_ - - * Dependencies updated - -## v1.0.9 - _September 21, 2018_ - - * Dependencies updated - -## v1.0.8 - _September 5, 2018_ - - * Dependencies updated - -## v1.0.7 - _August 27, 2018_ - - * Dependencies updated - -## v1.0.6 - _August 24, 2018_ - - * Dependencies updated - -## v1.0.5 - _August 14, 2018_ - - * Fix a bug where RelativeFSResolver would crash when trying to read a directory (#909) - * Fix a bug where NpmResolver would crash when trying to read a directory (#961) - -## v1.0.4 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.3 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.2 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.1 - _July 23, 2018_ - - * Dependencies updated - -## v1.0.0 - _July 19, 2018_ - - * Fix a bug in FsResolver where it tries to read directories as files (#589) - * Fix a bug in NameResolver where it is not ignoring .sol files (#589) - -## v0.0.8 - _July 9, 2018_ - - * Dependencies updated - -## v0.0.7 - _June 19, 2018_ - - * Dependencies updated - -## v0.0.6 - _May 31, 2018_ - - * Incorrect publish that was unpublished - -## v0.0.5 - _May 22, 2018_ - - * Dependencies updated - -## v0.0.4 - _May 4, 2018_ - - * Dependencies updated - -## v0.0.3 - _May 4, 2018_ - - * Dependencies updated - -## v0.0.2 - _April 18, 2018_ - - * Dependencies updated diff --git a/packages/sol-resolver/README.md b/packages/sol-resolver/README.md deleted file mode 100644 index 2ab336bc9c..0000000000 --- a/packages/sol-resolver/README.md +++ /dev/null @@ -1,67 +0,0 @@ -## @0x/sol-resolver - -A Solidity import resolver used by [sol-compiler](https://github.com/0xProject/0x-monorepo/tree/development/packages/sol-compiler). - -## Installation - -```bash -yarn add @0x/sol-resolver -``` - -**Import** - -```javascript -import { Resolver } from '@0x/sol-resolver'; -``` - -or - -```javascript -var Resolver = require('@0x/sol-resolver').Resolver; -``` - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install dependencies - -If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: - -```bash -yarn config set workspaces-experimental true -``` - -Then install dependencies - -```bash -yarn install -``` - -### Build - -To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory: - -```bash -PKG=@0x/sol-resolver yarn build -``` - -Or continuously rebuild on change: - -```bash -PKG=@0x/sol-resolver yarn watch -``` - -### Clean - -```bash -yarn clean -``` - -### Lint - -```bash -yarn lint -``` diff --git a/packages/sol-resolver/package.json b/packages/sol-resolver/package.json deleted file mode 100644 index 711e18b0fc..0000000000 --- a/packages/sol-resolver/package.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "name": "@0x/sol-resolver", - "version": "3.1.0", - "engines": { - "node": ">=6.12" - }, - "description": "Import resolver for smart contracts dependencies", - "main": "lib/index.js", - "types": "lib/index.d.ts", - "scripts": { - "build": "tsc -b", - "build:ci": "yarn build", - "clean": "shx rm -rf lib", - "lint": "tslint --format stylish --project .", - "fix": "tslint --format stylish --fix --project ." - }, - "repository": { - "type": "git", - "url": "https://github.com/0xProject/0x-monorepo.git" - }, - "license": "Apache-2.0", - "bugs": { - "url": "https://github.com/0xProject/0x-monorepo/issues" - }, - "homepage": "https://github.com/0xProject/0x-monorepo/packages/resolver/README.md", - "devDependencies": { - "@0x/tslint-config": "^4.1.0", - "make-promises-safe": "^1.1.0", - "shx": "^0.2.2", - "tslint": "5.11.0", - "typescript": "3.0.1" - }, - "dependencies": { - "@0x/types": "^3.2.0", - "@0x/typescript-typings": "^5.1.1", - "lodash": "^4.17.11" - }, - "publishConfig": { - "access": "public" - }, - "gitHead": "4f91bfd907996b2f4dd383778b50c479c2602b56" -} diff --git a/packages/sol-resolver/src/globals.d.ts b/packages/sol-resolver/src/globals.d.ts deleted file mode 100644 index e799b35298..0000000000 --- a/packages/sol-resolver/src/globals.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// tslint:disable:completed-docs -declare module '*.json' { - const json: any; - /* tslint:disable */ - export default json; - /* tslint:enable */ -} diff --git a/packages/sol-resolver/src/index.ts b/packages/sol-resolver/src/index.ts deleted file mode 100644 index f55aca0709..0000000000 --- a/packages/sol-resolver/src/index.ts +++ /dev/null @@ -1,10 +0,0 @@ -export { ContractSource, ContractSources } from './types'; -export { FallthroughResolver } from './resolvers/fallthrough_resolver'; -export { URLResolver } from './resolvers/url_resolver'; -export { NPMResolver } from './resolvers/npm_resolver'; -export { FSResolver } from './resolvers/fs_resolver'; -export { RelativeFSResolver } from './resolvers/relative_fs_resolver'; -export { NameResolver } from './resolvers/name_resolver'; -export { SpyResolver } from './resolvers/spy_resolver'; -export { EnumerableResolver } from './resolvers/enumerable_resolver'; -export { Resolver } from './resolvers/resolver'; diff --git a/packages/sol-resolver/src/resolvers/enumerable_resolver.ts b/packages/sol-resolver/src/resolvers/enumerable_resolver.ts deleted file mode 100644 index 0efa43e7ce..0000000000 --- a/packages/sol-resolver/src/resolvers/enumerable_resolver.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { ContractSource } from '../types'; - -import { Resolver } from './resolver'; - -export abstract class EnumerableResolver extends Resolver { - public abstract getAll(): ContractSource[]; -} diff --git a/packages/sol-resolver/src/resolvers/fallthrough_resolver.ts b/packages/sol-resolver/src/resolvers/fallthrough_resolver.ts deleted file mode 100644 index ed2ff88460..0000000000 --- a/packages/sol-resolver/src/resolvers/fallthrough_resolver.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { ContractSource } from '../types'; - -import { Resolver } from './resolver'; - -export class FallthroughResolver extends Resolver { - private readonly _resolvers: Resolver[] = []; - public appendResolver(resolver: Resolver): void { - this._resolvers.push(resolver); - } - public resolveIfExists(importPath: string): ContractSource | undefined { - for (const resolver of this._resolvers) { - const contractSourceIfExists = resolver.resolveIfExists(importPath); - if (contractSourceIfExists !== undefined) { - return contractSourceIfExists; - } - } - return undefined; - } -} diff --git a/packages/sol-resolver/src/resolvers/fs_resolver.ts b/packages/sol-resolver/src/resolvers/fs_resolver.ts deleted file mode 100644 index 064d83d330..0000000000 --- a/packages/sol-resolver/src/resolvers/fs_resolver.ts +++ /dev/null @@ -1,18 +0,0 @@ -import * as fs from 'fs'; -import * as path from 'path'; - -import { ContractSource } from '../types'; - -import { Resolver } from './resolver'; - -export class FSResolver extends Resolver { - // tslint:disable-next-line:prefer-function-over-method - public resolveIfExists(importPath: string): ContractSource | undefined { - if (fs.existsSync(importPath) && fs.lstatSync(importPath).isFile()) { - const fileContent = fs.readFileSync(importPath).toString('ascii'); - const absolutePath = path.resolve(importPath); - return { source: fileContent, path: importPath, absolutePath } as any; - } - return undefined; - } -} diff --git a/packages/sol-resolver/src/resolvers/name_resolver.ts b/packages/sol-resolver/src/resolvers/name_resolver.ts deleted file mode 100644 index 0836f1528b..0000000000 --- a/packages/sol-resolver/src/resolvers/name_resolver.ts +++ /dev/null @@ -1,67 +0,0 @@ -import * as fs from 'fs'; -import * as path from 'path'; - -import { ContractSource } from '../types'; - -import { EnumerableResolver } from './enumerable_resolver'; - -const SOLIDITY_FILE_EXTENSION = '.sol'; - -export class NameResolver extends EnumerableResolver { - private readonly _contractsDir: string; - constructor(contractsDir: string) { - super(); - this._contractsDir = contractsDir; - } - public resolveIfExists(lookupContractName: string): ContractSource | undefined { - const lookupContractNameNormalized = path.basename(lookupContractName, SOLIDITY_FILE_EXTENSION); - let contractSource: ContractSource | undefined; - const onFile = (filePath: string) => { - const contractName = path.basename(filePath, SOLIDITY_FILE_EXTENSION); - if (contractName === lookupContractNameNormalized) { - const absoluteContractPath = path.join(this._contractsDir, filePath); - const source = fs.readFileSync(absoluteContractPath).toString('ascii'); - contractSource = { source, path: filePath, absolutePath: absoluteContractPath }; - return true; - } - return undefined; - }; - this._traverseContractsDir(this._contractsDir, onFile); - return contractSource; - } - public getAll(): ContractSource[] { - const contractSources: ContractSource[] = []; - const onFile = (filePath: string) => { - const absoluteContractPath = path.join(this._contractsDir, filePath); - const source = fs.readFileSync(absoluteContractPath).toString('ascii'); - const contractSource = { source, path: filePath, absolutePath: absoluteContractPath }; - contractSources.push(contractSource); - }; - this._traverseContractsDir(this._contractsDir, onFile); - return contractSources; - } - // tslint:disable-next-line:prefer-function-over-method - private _traverseContractsDir(dirPath: string, onFile: (filePath: string) => true | void): boolean { - let dirContents: string[] = []; - try { - dirContents = fs.readdirSync(dirPath); - } catch (err) { - throw new Error(`No directory found at ${dirPath}`); - } - for (const fileName of dirContents) { - const absoluteEntryPath = path.join(dirPath, fileName); - const isDirectory = fs.lstatSync(absoluteEntryPath).isDirectory(); - const entryPath = path.relative(this._contractsDir, absoluteEntryPath); - let isComplete; - if (isDirectory) { - isComplete = this._traverseContractsDir(absoluteEntryPath, onFile); - } else if (fileName.endsWith(SOLIDITY_FILE_EXTENSION)) { - isComplete = onFile(entryPath); - } - if (isComplete) { - return isComplete; - } - } - return false; - } -} diff --git a/packages/sol-resolver/src/resolvers/npm_resolver.ts b/packages/sol-resolver/src/resolvers/npm_resolver.ts deleted file mode 100644 index c5b509f5cb..0000000000 --- a/packages/sol-resolver/src/resolvers/npm_resolver.ts +++ /dev/null @@ -1,41 +0,0 @@ -import * as fs from 'fs'; -import * as _ from 'lodash'; -import * as path from 'path'; - -import { ContractSource } from '../types'; - -import { Resolver } from './resolver'; - -export class NPMResolver extends Resolver { - private readonly _packagePath: string; - constructor(packagePath: string) { - super(); - this._packagePath = packagePath; - } - public resolveIfExists(importPath: string): ContractSource | undefined { - if (!importPath.startsWith('/')) { - let packageName; - let packageScopeIfExists; - let other; - if (_.startsWith(importPath, '@')) { - [packageScopeIfExists, packageName, ...other] = importPath.split('/'); - } else { - [packageName, ...other] = importPath.split('/'); - } - const pathWithinPackage = path.join(...other); - let currentPath = this._packagePath; - const ROOT_PATH = '/'; - while (currentPath !== ROOT_PATH) { - const packagePath = - packageScopeIfExists === undefined ? packageName : path.join(packageScopeIfExists, packageName); - const lookupPath = path.join(currentPath, 'node_modules', packagePath, pathWithinPackage); - if (fs.existsSync(lookupPath) && fs.lstatSync(lookupPath).isFile()) { - const fileContent = fs.readFileSync(lookupPath).toString('ascii'); - return { source: fileContent, path: importPath, absolutePath: lookupPath }; - } - currentPath = path.dirname(currentPath); - } - } - return undefined; - } -} diff --git a/packages/sol-resolver/src/resolvers/relative_fs_resolver.ts b/packages/sol-resolver/src/resolvers/relative_fs_resolver.ts deleted file mode 100644 index 30a80bc719..0000000000 --- a/packages/sol-resolver/src/resolvers/relative_fs_resolver.ts +++ /dev/null @@ -1,23 +0,0 @@ -import * as fs from 'fs'; -import * as path from 'path'; - -import { ContractSource } from '../types'; - -import { Resolver } from './resolver'; - -export class RelativeFSResolver extends Resolver { - private readonly _contractsDir: string; - constructor(contractsDir: string) { - super(); - this._contractsDir = contractsDir; - } - // tslint:disable-next-line:prefer-function-over-method - public resolveIfExists(importPath: string): ContractSource | undefined { - const filePath = path.resolve(path.join(this._contractsDir, importPath)); - if (fs.existsSync(filePath) && !fs.lstatSync(filePath).isDirectory()) { - const fileContent = fs.readFileSync(filePath).toString('ascii'); - return { source: fileContent, path: importPath, absolutePath: filePath }; - } - return undefined; - } -} diff --git a/packages/sol-resolver/src/resolvers/resolver.ts b/packages/sol-resolver/src/resolvers/resolver.ts deleted file mode 100644 index efbfb405a7..0000000000 --- a/packages/sol-resolver/src/resolvers/resolver.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { ContractSource } from '../types'; - -export abstract class Resolver { - public abstract resolveIfExists(importPath: string): ContractSource | undefined; - public resolve(importPath: string): ContractSource { - const contractSourceIfExists = this.resolveIfExists(importPath); - if (contractSourceIfExists === undefined) { - throw new Error(`Failed to resolve ${importPath}`); - } - return contractSourceIfExists; - } -} diff --git a/packages/sol-resolver/src/resolvers/spy_resolver.ts b/packages/sol-resolver/src/resolvers/spy_resolver.ts deleted file mode 100644 index b596c7ada3..0000000000 --- a/packages/sol-resolver/src/resolvers/spy_resolver.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { ContractSource } from '../types'; - -import { Resolver } from './resolver'; - -/** - * This resolver is a passthrough proxy to any resolver that records all the resolved contracts sources. - * You can access them later using the `resolvedContractSources` public field. - */ -export class SpyResolver extends Resolver { - public resolvedContractSources: ContractSource[] = []; - private readonly _resolver: Resolver; - constructor(resolver: Resolver) { - super(); - this._resolver = resolver; - } - public resolveIfExists(importPath: string): ContractSource | undefined { - const contractSourceIfExists = this._resolver.resolveIfExists(importPath); - if (contractSourceIfExists !== undefined) { - this.resolvedContractSources.push(contractSourceIfExists); - } - return contractSourceIfExists; - } -} diff --git a/packages/sol-resolver/src/resolvers/url_resolver.ts b/packages/sol-resolver/src/resolvers/url_resolver.ts deleted file mode 100644 index 05f934d124..0000000000 --- a/packages/sol-resolver/src/resolvers/url_resolver.ts +++ /dev/null @@ -1,18 +0,0 @@ -import * as fs from 'fs'; - -import { ContractSource } from '../types'; - -import { Resolver } from './resolver'; - -export class URLResolver extends Resolver { - // tslint:disable-next-line:prefer-function-over-method - public resolveIfExists(importPath: string): ContractSource | undefined { - const FILE_URL_PREXIF = 'file://'; - if (importPath.startsWith(FILE_URL_PREXIF)) { - const filePath = importPath.substr(FILE_URL_PREXIF.length); - const fileContent = fs.readFileSync(filePath).toString('ascii'); - return { source: fileContent, path: importPath, absolutePath: filePath }; - } - return undefined; - } -} diff --git a/packages/sol-resolver/src/types.ts b/packages/sol-resolver/src/types.ts deleted file mode 100644 index b4ba164c81..0000000000 --- a/packages/sol-resolver/src/types.ts +++ /dev/null @@ -1,9 +0,0 @@ -export interface ContractSource { - source: string; - path: string; - absolutePath: string; -} - -export interface ContractSources { - [key: string]: ContractSource; -} diff --git a/packages/sol-resolver/tsconfig.json b/packages/sol-resolver/tsconfig.json deleted file mode 100644 index 56689eaa34..0000000000 --- a/packages/sol-resolver/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../tsconfig", - "compilerOptions": { - "outDir": "lib", - "rootDir": "src" - }, - "include": ["src/**/*"] -} diff --git a/packages/sol-resolver/tslint.json b/packages/sol-resolver/tslint.json deleted file mode 100644 index dd9053357e..0000000000 --- a/packages/sol-resolver/tslint.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": ["@0x/tslint-config"] -} diff --git a/packages/sol-trace/.npmignore b/packages/sol-trace/.npmignore deleted file mode 100644 index ea588d4859..0000000000 --- a/packages/sol-trace/.npmignore +++ /dev/null @@ -1,9 +0,0 @@ -# Blacklist all files -.* -* -# Whitelist lib -!lib/**/* -# Blacklist tests and publish scripts -/lib/test/* -/lib/monorepo_scripts/ -# Package specific ignore diff --git a/packages/sol-trace/CHANGELOG.json b/packages/sol-trace/CHANGELOG.json deleted file mode 100644 index 1936954d55..0000000000 --- a/packages/sol-trace/CHANGELOG.json +++ /dev/null @@ -1,372 +0,0 @@ -[ - { - "timestamp": 1594788383, - "version": "3.0.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1592969527, - "version": "3.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1582623685, - "version": "3.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1581204851, - "version": "3.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1580988106, - "version": "3.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1580811564, - "version": "3.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1579682890, - "version": "3.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1578272714, - "version": "3.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1576540892, - "version": "3.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1575931811, - "version": "3.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.0.0", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1575296764 - }, - { - "version": "2.1.0-beta.4", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1575290197 - }, - { - "version": "2.1.0-beta.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1574238768 - }, - { - "version": "2.1.0-beta.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1574030254 - }, - { - "version": "2.1.0-beta.1", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1573159180 - }, - { - "version": "2.1.0-beta.0", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1570135330 - }, - { - "timestamp": 1568744790, - "version": "2.0.20", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1567521715, - "version": "2.0.19", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1566446343, - "version": "2.0.18", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1565296576, - "version": "2.0.17", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1564604963, - "version": "2.0.16", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563957393, - "version": "2.0.15", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563006338, - "version": "2.0.14", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1558712885, - "version": "2.0.13", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1557507213, - "version": "2.0.12", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.11", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1554997931 - }, - { - "timestamp": 1553183790, - "version": "2.0.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1553091633, - "version": "2.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551479279, - "version": "2.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551299797, - "version": "2.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551220833, - "version": "2.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551130135, - "version": "2.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1549733923, - "version": "2.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1549547375 - }, - { - "timestamp": 1549452781, - "version": "2.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.1", - "changes": [ - { - "note": "Improve error messages when unable to find matching bytecode", - "pr": 1558 - } - ], - "timestamp": 1549373905 - }, - { - "version": "2.0.0", - "changes": [ - { - "note": "Upgrade the bignumber.js to v8.0.2", - "pr": 1517 - } - ] - }, - { - "timestamp": 1547747677, - "version": "1.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547561734, - "version": "1.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547225310, - "version": "1.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.0", - "changes": [ - { - "note": "Initial release as a separate package. For historical entries see @0x/sol-tracing-utils", - "pr": 1492 - } - ] - } -] diff --git a/packages/sol-trace/CHANGELOG.md b/packages/sol-trace/CHANGELOG.md deleted file mode 100644 index 38ff456f35..0000000000 --- a/packages/sol-trace/CHANGELOG.md +++ /dev/null @@ -1,170 +0,0 @@ - - -CHANGELOG - -## v3.0.10 - _July 15, 2020_ - - * Dependencies updated - -## v3.0.9 - _June 24, 2020_ - - * Dependencies updated - -## v3.0.8 - _February 25, 2020_ - - * Dependencies updated - -## v3.0.7 - _February 8, 2020_ - - * Dependencies updated - -## v3.0.6 - _February 6, 2020_ - - * Dependencies updated - -## v3.0.5 - _February 4, 2020_ - - * Dependencies updated - -## v3.0.4 - _January 22, 2020_ - - * Dependencies updated - -## v3.0.3 - _January 6, 2020_ - - * Dependencies updated - -## v3.0.2 - _December 17, 2019_ - - * Dependencies updated - -## v3.0.1 - _December 9, 2019_ - - * Dependencies updated - -## v3.0.0 - _December 2, 2019_ - - * Dependencies updated - -## v2.1.0-beta.4 - _December 2, 2019_ - - * Dependencies updated - -## v2.1.0-beta.3 - _November 20, 2019_ - - * Dependencies updated - -## v2.1.0-beta.2 - _November 17, 2019_ - - * Dependencies updated - -## v2.1.0-beta.1 - _November 7, 2019_ - - * Dependencies updated - -## v2.1.0-beta.0 - _October 3, 2019_ - - * Dependencies updated - -## v2.0.20 - _September 17, 2019_ - - * Dependencies updated - -## v2.0.19 - _September 3, 2019_ - - * Dependencies updated - -## v2.0.18 - _August 22, 2019_ - - * Dependencies updated - -## v2.0.17 - _August 8, 2019_ - - * Dependencies updated - -## v2.0.16 - _July 31, 2019_ - - * Dependencies updated - -## v2.0.15 - _July 24, 2019_ - - * Dependencies updated - -## v2.0.14 - _July 13, 2019_ - - * Dependencies updated - -## v2.0.13 - _May 24, 2019_ - - * Dependencies updated - -## v2.0.12 - _May 10, 2019_ - - * Dependencies updated - -## v2.0.11 - _April 11, 2019_ - - * Dependencies updated - -## v2.0.10 - _March 21, 2019_ - - * Dependencies updated - -## v2.0.9 - _March 20, 2019_ - - * Dependencies updated - -## v2.0.8 - _March 1, 2019_ - - * Dependencies updated - -## v2.0.7 - _February 27, 2019_ - - * Dependencies updated - -## v2.0.6 - _February 26, 2019_ - - * Dependencies updated - -## v2.0.5 - _February 25, 2019_ - - * Dependencies updated - -## v2.0.4 - _February 9, 2019_ - - * Dependencies updated - -## v2.0.3 - _February 7, 2019_ - - * Dependencies updated - -## v2.0.2 - _February 6, 2019_ - - * Dependencies updated - -## v2.0.1 - _February 5, 2019_ - - * Improve error messages when unable to find matching bytecode (#1558) - -## v2.0.0 - _Invalid date_ - - * Upgrade the bignumber.js to v8.0.2 (#1517) - -## v1.0.3 - _January 17, 2019_ - - * Dependencies updated - -## v1.0.2 - _January 15, 2019_ - - * Dependencies updated - -## v1.0.1 - _January 11, 2019_ - - * Dependencies updated - -## v1.0.0 - _Invalid date_ - - * Initial release as a separate package. For historical entries see @0x/sol-tracing-utils (#1492) diff --git a/packages/sol-trace/README.md b/packages/sol-trace/README.md deleted file mode 100644 index bde4a92573..0000000000 --- a/packages/sol-trace/README.md +++ /dev/null @@ -1,75 +0,0 @@ -## @0x/sol-trace - -Prints a stack trace when a revert is encountered. - -### Read the [Documentation](https://0x.org/docs/tools/sol-trace). - -## Installation - -```bash -yarn add @0x/sol-trace -``` - -**Import** - -```javascript -import { RevertTraceSubprovider } from '@0x/sol-trace'; -``` - -or - -```javascript -var RevertTraceSubprovider = require('@0x/sol-trace').RevertTraceSubprovider; -``` - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install dependencies - -If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: - -```bash -yarn config set workspaces-experimental true -``` - -Then install dependencies - -```bash -yarn install -``` - -### Build - -To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory: - -```bash -PKG=@0x/sol-trace yarn build -``` - -Or continuously rebuild on change: - -```bash -PKG=@0x/sol-trace yarn watch -``` - -### Clean - -```bash -yarn clean -``` - -### Lint - -```bash -yarn lint -``` - -### Run Tests - -```bash -yarn test -``` diff --git a/packages/sol-trace/docs/reference.mdx b/packages/sol-trace/docs/reference.mdx deleted file mode 100644 index 1ff8930b3b..0000000000 --- a/packages/sol-trace/docs/reference.mdx +++ /dev/null @@ -1,701 +0,0 @@ - - -# Class: AbstractArtifactAdapter - - -## Methods - -### `Abstract` collectContractsDataAsync - -▸ **collectContractsDataAsync**(): *`Promise`* - -*Defined in [sol-tracing-utils/src/artifact_adapters/abstract_artifact_adapter.ts:4](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-tracing-utils/src/artifact_adapters/abstract_artifact_adapter.ts#L4)* - -**Returns:** *`Promise`* - -
- -# Class: SolCompilerArtifactAdapter - - -## Constructors - - - -\+ **new SolCompilerArtifactAdapter**(`artifactsPath?`: undefined | string, `sourcesPath?`: undefined | string): *[SolCompilerArtifactAdapter](#class-solcompilerartifactadapter)* - -*Defined in [sol-tracing-utils/src/artifact_adapters/sol_compiler_artifact_adapter.ts:18](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-tracing-utils/src/artifact_adapters/sol_compiler_artifact_adapter.ts#L18)* - -Instantiates a SolCompilerArtifactAdapter - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`artifactsPath?` | undefined \| string | Path to your artifacts directory | -`sourcesPath?` | undefined \| string | Path to your contract sources directory | - -**Returns:** *[SolCompilerArtifactAdapter](#class-solcompilerartifactadapter)* - -## Methods - -### collectContractsDataAsync - -▸ **collectContractsDataAsync**(): *`Promise`* - -*Overrides [AbstractArtifactAdapter](_sol_tracing_utils_src_artifact_adapters_abstract_artifact_adapter_.abstractartifactadapter.md).[collectContractsDataAsync](#abstract-collectcontractsdataasync)* - -*Defined in [sol-tracing-utils/src/artifact_adapters/sol_compiler_artifact_adapter.ts:44](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-tracing-utils/src/artifact_adapters/sol_compiler_artifact_adapter.ts#L44)* - -**Returns:** *`Promise`* - -
- -# Class: TruffleArtifactAdapter - - -## Constructors - - - -\+ **new TruffleArtifactAdapter**(`projectRoot`: string, `solcVersion`: string): *[TruffleArtifactAdapter](#class-truffleartifactadapter)* - -*Defined in [sol-tracing-utils/src/artifact_adapters/truffle_artifact_adapter.ts:29](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-tracing-utils/src/artifact_adapters/truffle_artifact_adapter.ts#L29)* - -Instantiates a TruffleArtifactAdapter - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`projectRoot` | string | Path to the truffle project's root directory | -`solcVersion` | string | Solidity version with which to compile all the contracts | - -**Returns:** *[TruffleArtifactAdapter](#class-truffleartifactadapter)* - -## Methods - -### collectContractsDataAsync - -▸ **collectContractsDataAsync**(): *`Promise`* - -*Overrides [AbstractArtifactAdapter](_sol_tracing_utils_src_artifact_adapters_abstract_artifact_adapter_.abstractartifactadapter.md).[collectContractsDataAsync](#abstract-collectcontractsdataasync)* - -*Defined in [sol-tracing-utils/src/artifact_adapters/truffle_artifact_adapter.ts:40](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-tracing-utils/src/artifact_adapters/truffle_artifact_adapter.ts#L40)* - -**Returns:** *`Promise`* - -
- - - - - - - - - - - - - - - - - - - - -## Type aliases - -### Callback - -Ƭ **Callback**: *function* - -*Defined in [subproviders/src/types.ts:131](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L131)* - -#### Type declaration: - -▸ (): *void* - -___ - - - -### ErrorCallback - -Ƭ **ErrorCallback**: *function* - -*Defined in [subproviders/src/types.ts:130](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L130)* - -#### Type declaration: - -▸ (`err`: `Error` | null, `data?`: any): *void* - -**Parameters:** - -Name | Type | ------- | ------ | -`err` | `Error` \| null | -`data?` | any | - -___ - - - -### NextCallback - -Ƭ **NextCallback**: *function* - -*Defined in [subproviders/src/types.ts:133](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L133)* - -#### Type declaration: - -▸ (`callback?`: [OnNextCompleted](#onnextcompleted)): *void* - -**Parameters:** - -Name | Type | ------- | ------ | -`callback?` | [OnNextCompleted](#onnextcompleted) | - -___ - -### OnNextCompleted - -Ƭ **OnNextCompleted**: *function* - -*Defined in [subproviders/src/types.ts:132](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L132)* - -#### Type declaration: - -▸ (`err`: `Error` | null, `result`: any, `cb`: [Callback](#callback)): *void* - -**Parameters:** - -Name | Type | ------- | ------ | -`err` | `Error` \| null | -`result` | any | -`cb` | [Callback](#callback) | - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# Interface: JSONRPCRequestPayload - - -## Properties - -### id - -• **id**: *number* - -*Defined in [ethereum-types/src/index.ts:331](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L331)* - -___ - -### jsonrpc - -• **jsonrpc**: *string* - -*Defined in [ethereum-types/src/index.ts:332](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L332)* - -___ - -### method - -• **method**: *string* - -*Defined in [ethereum-types/src/index.ts:330](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L330)* - -___ - -### params - -• **params**: *any[]* - -*Defined in [ethereum-types/src/index.ts:329](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L329)* - -
- -# Interface: JSONRPCResponseError - - -## Properties - -### code - -• **code**: *number* - -*Defined in [ethereum-types/src/index.ts:337](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L337)* - -___ - -### message - -• **message**: *string* - -*Defined in [ethereum-types/src/index.ts:336](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L336)* - -
- -# Interface: JSONRPCResponsePayload - - -## Properties - -### `Optional` error - -• **error**? : *[JSONRPCResponseError](#class-jsonrpcresponseerror)* - -*Defined in [ethereum-types/src/index.ts:344](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L344)* - -___ - -### id - -• **id**: *number* - -*Defined in [ethereum-types/src/index.ts:342](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L342)* - -___ - -### jsonrpc - -• **jsonrpc**: *string* - -*Defined in [ethereum-types/src/index.ts:343](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L343)* - -___ - -### result - -• **result**: *any* - -*Defined in [ethereum-types/src/index.ts:341](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L341)* - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# Class: RevertTraceSubprovider - -This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface. -It is used to report call stack traces whenever a revert occurs. - - -## Constructors - - - -\+ **new RevertTraceSubprovider**(`artifactAdapter`: `AbstractArtifactAdapter`, `defaultFromAddress`: string, `isVerbose`: boolean): *[RevertTraceSubprovider](#class-reverttracesubprovider)* - -*Overrides void* - -*Defined in [sol-trace/src/revert_trace_subprovider.ts:27](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/sol-trace/src/revert_trace_subprovider.ts#L27)* - -Instantiates a RevertTraceSubprovider instance - -**Parameters:** - -Name | Type | Default | Description | ------- | ------ | ------ | ------ | -`artifactAdapter` | `AbstractArtifactAdapter` | - | Adapter for used artifacts format (0x, truffle, giveth, etc.) | -`defaultFromAddress` | string | - | default from address to use when sending transactions | -`isVerbose` | boolean | true | If true, we will log any unknown transactions. Otherwise we will ignore them | - -**Returns:** *[RevertTraceSubprovider](#class-reverttracesubprovider)* - -## Methods - -### emitPayloadAsync - -▸ **emitPayloadAsync**(`payload`: `Partial`): *`Promise`* - - - -Defined in subproviders/lib/src/subproviders/subprovider.d.ts:25 - -Emits a JSON RPC payload that will then be handled by the ProviderEngine instance -this subprovider is a part of. The payload will cascade down the subprovider middleware -stack until finding the responsible entity for handling the request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `Partial` | JSON RPC payload | - -**Returns:** *`Promise`* - -JSON RPC response payload - -___ - -### handleRequest - -▸ **handleRequest**(`payload`: `JSONRPCRequestPayload`, `next`: [NextCallback](#nextcallback), `_end`: [ErrorCallback](#errorcallback)): *`Promise`* - - - -*Overrides void* - -Defined in sol-tracing-utils/lib/src/trace_collection_subprovider.d.ts:42 - -This method conforms to the web3-provider-engine interface. -It is called internally by the ProviderEngine when it is this subproviders -turn to handle a JSON RPC request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `JSONRPCRequestPayload` | JSON RPC payload | -`next` | [NextCallback](#nextcallback) | Callback to call if this subprovider decides not to handle the request | -`_end` | [ErrorCallback](#errorcallback) | Callback to call if subprovider handled the request and wants to pass back the request. | - -**Returns:** *`Promise`* - -___ - -### setEngine - -▸ **setEngine**(`engine`: `Web3ProviderEngine`): *void* - - - -*Overrides void* - -Defined in sol-tracing-utils/lib/src/trace_collection_subprovider.d.ts:49 - -Set's the subprovider's engine to the ProviderEngine it is added to. -This is only called within the ProviderEngine source code, do not call -directly. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`engine` | `Web3ProviderEngine` | The ProviderEngine this subprovider is added to | - -**Returns:** *void* - -___ - -### start - -▸ **start**(): *void* - - - -Defined in sol-tracing-utils/lib/src/trace_collection_subprovider.d.ts:29 - -Starts trace collection - -**Returns:** *void* - -___ - -### stop - -▸ **stop**(): *void* - - - -Defined in sol-tracing-utils/lib/src/trace_collection_subprovider.d.ts:33 - -Stops trace collection - -**Returns:** *void* - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# Interface: JSONRPCRequestPayloadWithMethod - - -## Properties - -### id - -• **id**: *number* - - - -Defined in ethereum-types/lib/index.d.ts:268 - -___ - -### jsonrpc - -• **jsonrpc**: *string* - - - -Defined in ethereum-types/lib/index.d.ts:269 - -___ - -### method - -• **method**: *string* - -*Overrides void* - -*Defined in [subproviders/src/types.ts:136](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L136)* - -___ - -### params - -• **params**: *any[]* - - - -Defined in ethereum-types/lib/index.d.ts:266 - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -## Type aliases - - - - - - - - - - - - -## Type aliases - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - -
- - - -
- - - -
- diff --git a/packages/sol-trace/package.json b/packages/sol-trace/package.json deleted file mode 100644 index 3c88e9b460..0000000000 --- a/packages/sol-trace/package.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "name": "@0x/sol-trace", - "version": "3.0.10", - "engines": { - "node": ">=6.12" - }, - "description": "Prints stack trace on Solidity revert", - "main": "lib/src/index.js", - "types": "lib/src/index.d.ts", - "scripts": { - "build": "tsc -b", - "build:ci": "yarn build", - "lint": "tslint --format stylish --project .", - "fix": "tslint --fix --format stylish --project .", - "clean": "shx rm -rf lib src/artifacts generated_docs", - "diff_docs": "git diff --exit-code ./docs", - "s3:sync_md_docs": "aws s3 sync ./docs s3://docs-markdown/${npm_package_name}/v${npm_package_version} --profile 0xproject --region us-east-1 --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers", - "docs:md": "ts-doc-gen --sourceDir='$PROJECT_FILES' --output=$MD_FILE_DIR --fileExtension=mdx --tsconfig=./typedoc-tsconfig.json", - "docs:json": "typedoc --excludePrivate --excludeExternals --excludeProtected --ignoreCompilerErrors --target ES5 --tsconfig typedoc-tsconfig.json --json $JSON_FILE_PATH $PROJECT_FILES" - }, - "config": { - "postpublish": { - "assets": [] - } - }, - "repository": { - "type": "git", - "url": "https://github.com/0xProject/0x-monorepo.git" - }, - "license": "Apache-2.0", - "bugs": { - "url": "https://github.com/0xProject/0x-monorepo/issues" - }, - "homepage": "https://github.com/0xProject/0x-monorepo/packages/sol-trace/README.md", - "dependencies": { - "@0x/sol-tracing-utils": "^7.1.0", - "@0x/subproviders": "^6.1.1", - "@0x/typescript-typings": "^5.1.1", - "chalk": "^2.3.0", - "ethereum-types": "^3.2.0", - "ethereumjs-util": "^5.1.1", - "lodash": "^4.17.11", - "loglevel": "^1.6.1", - "web3-provider-engine": "14.0.6" - }, - "devDependencies": { - "@0x/ts-doc-gen": "^0.0.22", - "@0x/tslint-config": "^4.1.0", - "@types/loglevel": "^1.5.3", - "@types/node": "12.12.54", - "@types/web3-provider-engine": "^14.0.0", - "npm-run-all": "^4.1.2", - "shx": "^0.2.2", - "tslint": "5.11.0", - "typedoc": "^0.15.0", - "typescript": "3.0.1" - }, - "publishConfig": { - "access": "public" - }, - "gitHead": "4f91bfd907996b2f4dd383778b50c479c2602b56" -} diff --git a/packages/sol-trace/src/globals.d.ts b/packages/sol-trace/src/globals.d.ts deleted file mode 100644 index e799b35298..0000000000 --- a/packages/sol-trace/src/globals.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// tslint:disable:completed-docs -declare module '*.json' { - const json: any; - /* tslint:disable */ - export default json; - /* tslint:enable */ -} diff --git a/packages/sol-trace/src/index.ts b/packages/sol-trace/src/index.ts deleted file mode 100644 index ee45de51e9..0000000000 --- a/packages/sol-trace/src/index.ts +++ /dev/null @@ -1,22 +0,0 @@ -export { - AbstractArtifactAdapter, - TruffleArtifactAdapter, - SolCompilerArtifactAdapter, - ContractData, - SourceCodes, - Sources, -} from '@0x/sol-tracing-utils'; - -export { RevertTraceSubprovider } from './revert_trace_subprovider'; - -export { JSONRPCRequestPayload, JSONRPCResponsePayload, JSONRPCResponseError } from 'ethereum-types'; - -export { - JSONRPCRequestPayloadWithMethod, - NextCallback, - ErrorCallback, - OnNextCompleted, - Callback, -} from '@0x/subproviders'; - -export import Web3ProviderEngine = require('web3-provider-engine'); diff --git a/packages/sol-trace/src/revert_trace_subprovider.ts b/packages/sol-trace/src/revert_trace_subprovider.ts deleted file mode 100644 index 5e2bebea94..0000000000 --- a/packages/sol-trace/src/revert_trace_subprovider.ts +++ /dev/null @@ -1,170 +0,0 @@ -import { - AbstractArtifactAdapter, - constants, - ContractData, - EvmCallStack, - getRevertTrace, - getSourceRangeSnippet, - parseSourceMap, - SourceRange, - SourceSnippet, - TraceCollectionSubprovider, - utils, -} from '@0x/sol-tracing-utils'; -import chalk from 'chalk'; -import { stripHexPrefix } from 'ethereumjs-util'; -import * as _ from 'lodash'; -import { getLogger, levels, Logger } from 'loglevel'; - -/** - * This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface. - * It is used to report call stack traces whenever a revert occurs. - */ -export class RevertTraceSubprovider extends TraceCollectionSubprovider { - // Lock is used to not accept normal transactions while doing call/snapshot magic because they'll be reverted later otherwise - private _contractsData!: ContractData[]; - private readonly _artifactAdapter: AbstractArtifactAdapter; - private readonly _logger: Logger; - - /** - * Instantiates a RevertTraceSubprovider instance - * @param artifactAdapter Adapter for used artifacts format (0x, truffle, giveth, etc.) - * @param defaultFromAddress default from address to use when sending transactions - * @param isVerbose If true, we will log any unknown transactions. Otherwise we will ignore them - */ - constructor(artifactAdapter: AbstractArtifactAdapter, defaultFromAddress: string, isVerbose: boolean = true) { - const traceCollectionSubproviderConfig = { - shouldCollectTransactionTraces: true, - shouldCollectGasEstimateTraces: true, - shouldCollectCallTraces: true, - }; - super(defaultFromAddress, traceCollectionSubproviderConfig); - this._artifactAdapter = artifactAdapter; - this._logger = getLogger('sol-trace'); - this._logger.setLevel(isVerbose ? levels.TRACE : levels.ERROR); - } - // tslint:disable-next-line:no-unused-variable - protected async _recordTxTraceAsync(address: string, data: string | undefined, txHash: string): Promise { - await this._web3Wrapper.awaitTransactionMinedAsync(txHash, 0); - const trace = await this._web3Wrapper.getTransactionTraceAsync(txHash, { - disableMemory: true, - disableStack: false, - disableStorage: true, - }); - const evmCallStack = getRevertTrace(trace.structLogs, address); - if (evmCallStack.length > 0) { - // if getRevertTrace returns a call stack it means there was a - // revert. - await this._printStackTraceAsync(evmCallStack); - } - } - private async _printStackTraceAsync(evmCallStack: EvmCallStack): Promise { - const sourceSnippets: SourceSnippet[] = []; - if (this._contractsData === undefined) { - this._contractsData = await this._artifactAdapter.collectContractsDataAsync(); - } - for (const evmCallStackEntry of evmCallStack) { - const isContractCreation = evmCallStackEntry.address === constants.NEW_CONTRACT; - if (isContractCreation) { - this._logger.error('Contract creation not supported'); - continue; - } - const bytecode = await this._web3Wrapper.getContractCodeAsync(evmCallStackEntry.address); - const contractData = utils.getContractDataIfExists(this._contractsData, bytecode); - if (contractData === undefined) { - const shortenHex = (hex: string) => { - /** - * Length choosen so that both error messages are of the same length - * and it's enough data to figure out which artifact has a problem. - */ - const length = 18; - return `${hex.substr(0, length + 2)}...${hex.substr(hex.length - length, length)}`; - }; - const errMsg = isContractCreation - ? `Unable to find matching bytecode for contract creation ${chalk.bold( - shortenHex(bytecode), - )}, please check your artifacts. Ignoring...` - : `Unable to find matching bytecode for contract address ${chalk.bold( - evmCallStackEntry.address, - )}, please check your artifacts. Ignoring...`; - this._logger.warn(errMsg); - continue; - } - const bytecodeHex = stripHexPrefix(bytecode); - const sourceMap = isContractCreation ? contractData.sourceMap : contractData.sourceMapRuntime; - - const pcToSourceRange = parseSourceMap( - contractData.sourceCodes, - sourceMap, - bytecodeHex, - contractData.sources, - ); - // tslint:disable-next-line:no-unnecessary-initializer - let sourceRange: SourceRange | undefined = undefined; - let pc = evmCallStackEntry.structLog.pc; - // Sometimes there is not a mapping for this pc (e.g. if the revert - // actually happens in assembly). In that case, we want to keep - // searching backwards by decrementing the pc until we find a - // mapped source range. - while (sourceRange === undefined && pc > 0) { - sourceRange = pcToSourceRange[pc]; - pc -= 1; - } - if (sourceRange === undefined) { - this._logger.warn( - `could not find matching sourceRange for structLog: ${JSON.stringify( - _.omit(evmCallStackEntry.structLog, 'stack'), - )}`, - ); - continue; - } - - const fileNameToFileIndex = _.invert(contractData.sources); - const fileIndex = _.parseInt(fileNameToFileIndex[sourceRange.fileName]); - const sourceSnippet = getSourceRangeSnippet(sourceRange, contractData.sourceCodes[fileIndex]); - sourceSnippets.push(sourceSnippet); - } - const filteredSnippets = filterSnippets(sourceSnippets); - if (filteredSnippets.length > 0) { - this._logger.error('\n\nStack trace for REVERT:\n'); - _.forEach(_.reverse(filteredSnippets), snippet => { - const traceString = getStackTraceString(snippet); - this._logger.error(traceString); - }); - this._logger.error('\n'); - } else { - this._logger.error('REVERT detected but could not determine stack trace'); - } - } -} - -// removes duplicates and if statements -function filterSnippets(sourceSnippets: SourceSnippet[]): SourceSnippet[] { - if (sourceSnippets.length === 0) { - return []; - } - const results: SourceSnippet[] = [sourceSnippets[0]]; - let prev = sourceSnippets[0]; - for (const sourceSnippet of sourceSnippets) { - if (sourceSnippet.source === prev.source) { - prev = sourceSnippet; - continue; - } - results.push(sourceSnippet); - prev = sourceSnippet; - } - return results; -} - -function getStackTraceString(sourceSnippet: SourceSnippet): string { - let result = `${sourceSnippet.fileName}:${sourceSnippet.range.start.line}:${sourceSnippet.range.start.column}`; - const snippetString = getSourceSnippetString(sourceSnippet); - if (snippetString !== '') { - result += `:\n ${snippetString}`; - } - return result; -} - -function getSourceSnippetString(sourceSnippet: SourceSnippet): string { - return `${sourceSnippet.source}`; -} diff --git a/packages/sol-trace/tsconfig.json b/packages/sol-trace/tsconfig.json deleted file mode 100644 index 233008d61c..0000000000 --- a/packages/sol-trace/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../tsconfig", - "compilerOptions": { - "outDir": "lib", - "rootDir": "." - }, - "include": ["./src/**/*"] -} diff --git a/packages/sol-trace/tslint.json b/packages/sol-trace/tslint.json deleted file mode 100644 index dd9053357e..0000000000 --- a/packages/sol-trace/tslint.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": ["@0x/tslint-config"] -} diff --git a/packages/sol-trace/typedoc-tsconfig.json b/packages/sol-trace/typedoc-tsconfig.json deleted file mode 100644 index a4c669cb6d..0000000000 --- a/packages/sol-trace/typedoc-tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "../../typedoc-tsconfig", - "compilerOptions": { - "outDir": "lib" - }, - "include": ["./src/**/*"] -} diff --git a/packages/sol-tracing-utils/.npmignore b/packages/sol-tracing-utils/.npmignore deleted file mode 100644 index 760ab23334..0000000000 --- a/packages/sol-tracing-utils/.npmignore +++ /dev/null @@ -1,10 +0,0 @@ -# Blacklist all files -.* -* -# Whitelist lib -!lib/**/* -# Blacklist tests and publish scripts -/lib/test/* -/lib/monorepo_scripts/ -# Package specific ignore - diff --git a/packages/sol-tracing-utils/CHANGELOG.json b/packages/sol-tracing-utils/CHANGELOG.json deleted file mode 100644 index 11d8c46767..0000000000 --- a/packages/sol-tracing-utils/CHANGELOG.json +++ /dev/null @@ -1,816 +0,0 @@ -[ - { - "version": "7.1.0", - "changes": [ - { - "note": "Make sol-profiler (mostly) work again", - "pr": 2607 - } - ], - "timestamp": 1594788383 - }, - { - "timestamp": 1592969527, - "version": "7.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1582623685, - "version": "7.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1581204851, - "version": "7.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1580988106, - "version": "7.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1580811564, - "version": "7.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1579682890, - "version": "7.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1578272714, - "version": "7.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1576540892, - "version": "7.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1575931811, - "version": "7.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "7.0.0", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1575296764 - }, - { - "version": "6.1.0-beta.4", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1575290197 - }, - { - "version": "6.1.0-beta.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1574238768 - }, - { - "version": "6.1.0-beta.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1574030254 - }, - { - "version": "6.1.0-beta.1", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1573159180 - }, - { - "version": "6.1.0-beta.0", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1570135330 - }, - { - "timestamp": 1568744790, - "version": "6.0.19", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1567521715, - "version": "6.0.18", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1566446343, - "version": "6.0.17", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1565296576, - "version": "6.0.16", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1564604963, - "version": "6.0.15", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563957393, - "version": "6.0.14", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563006338, - "version": "6.0.13", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1558712885, - "version": "6.0.12", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1557507213, - "version": "6.0.11", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "6.0.10", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1554997931 - }, - { - "timestamp": 1553183790, - "version": "6.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "6.0.8", - "changes": [ - { - "note": "Update solidity-parser-antlr to 0.4.2", - "pr": 1719 - } - ], - "timestamp": 1553091633 - }, - { - "version": "6.0.7", - "changes": [ - { - "note": "Fix a bug when `TruffleArtifactAdapter` wasn't correctly parsing solc config in pre-5.0 versions of Truffle", - "pr": 1663 - }, - { - "note": "Fix a bug when `opCodes` gas costs were incorrect or `NaN`", - "pr": 1663 - } - ], - "timestamp": 1551479279 - }, - { - "version": "6.0.6", - "changes": [ - { - "note": "Fix a bug when `TruffleArtifactAdapter` wasn't parsing solc config in the newest version of trufle", - "pr": 1654 - } - ], - "timestamp": 1551299797 - }, - { - "timestamp": 1551220833, - "version": "6.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551130135, - "version": "6.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1549733923, - "version": "6.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "6.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1549547375 - }, - { - "timestamp": 1549452781, - "version": "6.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "6.0.0", - "changes": [ - { - "note": "`SolCompilerArtifactAdapter` now uses `SolResolver` under the hood which allows to resolve `NPM` dependencies properly", - "pr": 1535 - }, - { - "note": "Cache the `utils.getContractDataIfExists` leading to faster execution", - "pr": 1535 - }, - { - "note": "`SolCompilerArtifactAdapter` now doesn't return the `ContractData` for interfaces", - "pr": 1535 - }, - { - "note": "Print resasonable error message on bytecode collision", - "pr": 1535 - }, - { - "note": "Fix the bug in `ASTVisitor` causing the 'cannot read property `range` of `null`' error", - "pr": 1557 - }, - { - "note": "Improve error messages when unable to find matching bytecode", - "pr": 1558 - }, - { - "note": "Fix default gas limit for fake txs in `TraceCollectionSubprovider`", - "pr": 1583 - }, - { - "note": "Fix a big when we were not intercepting `eth_sendRawTransaction`", - "pr": 1584 - } - ], - "timestamp": 1549373905 - }, - { - "version": "5.0.0", - "changes": [ - { - "note": "Upgrade the bignumber.js to v8.0.2", - "pr": 1517 - } - ] - }, - { - "version": "4.0.1", - "changes": [ - { - "note": "Fix a bug where a custom `Geth` tracer didn't return stack entries for `DELEGATECALL`", - "pr": 1521 - }, - { - "note": "Fix a bug where `TraceCollectionSubprovider` was hanging on the fake `Geth` snapshot transaction", - "pr": 1521 - }, - { - "note": "Fix/simplify handling of revert trace snippets", - "pr": 1521 - } - ], - "timestamp": 1547747677 - }, - { - "version": "4.0.0", - "changes": [ - { - "note": "Fix a bug with incorrect parsing of `sourceMaps` due to sources being in an array instead of a map", - "pr": 1498 - }, - { - "note": "Change the types of `ContractData.sources` and `ContractData.sourceCodes` to be objects instead of arrays", - "pr": 1498 - }, - { - "note": "Use custom JS tracer to speed up tracing on clients that support it (e.g., Geth)", - "pr": 1498 - }, - { - "note": "Log errors encountered in `TraceCollectionSubprovider`", - "pr": 1498 - }, - { - "note": "Add support for assembly statements", - "pr": 1498 - } - ], - "timestamp": 1547561734 - }, - { - "version": "3.0.0", - "changes": [ - { - "note": "Move out specific tools and leave just the shared parts of the codebase", - "pr": 1492 - } - ], - "timestamp": 1547225310 - }, - { - "timestamp": 1547040760, - "version": "2.1.17", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.1.16", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544739608 - }, - { - "version": "2.1.15", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544570656 - }, - { - "timestamp": 1543401373, - "version": "2.1.14", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542821676, - "version": "2.1.13", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542208198, - "version": "2.1.12", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542134075, - "version": "2.1.11", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542028948, - "version": "2.1.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.1.9", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1541740904 - }, - { - "version": "2.1.8", - "changes": [ - { - "note": "Make @types/solidity-parser-antlr a 'dependency' so it's available to users of the library", - "pr": 1105 - } - ], - "timestamp": 1539871071 - }, - { - "version": "2.1.7", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1538693146 - }, - { - "timestamp": 1538157789, - "version": "2.1.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537907159, - "version": "2.1.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537875740, - "version": "2.1.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537541580, - "version": "2.1.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1536142250, - "version": "2.1.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1535377027, - "version": "2.1.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.1.0", - "changes": [ - { - "note": "Export types: `JSONRPCRequestPayload`, `Provider`, `JSONRPCErrorCallback`, `JSONRPCResponsePayload`, `JSONRPCRequestPayloadWithMethod`, `NextCallback`, `ErrorCallback`, `OnNextCompleted` and `Callback`", - "pr": 924 - } - ], - "timestamp": 1535133899 - }, - { - "version": "2.0.0", - "changes": [ - { - "note": "Fix a bug when eth_call coverage was not computed because of silent schema validation failures", - "pr": 938 - }, - { - "note": "Make `TruffleArtifactAdapter` read the `truffle.js` config for `solc` settings", - "pr": 938 - }, - { - "note": "Change the first param of `TruffleArtifactAdapter` to be the `projectRoot` instead of `sourcesDir`", - "pr": 938 - }, - { - "note": "Throw a helpful error message if truffle artifacts were generated with a different solc version than the one passed in", - "pr": 938 - } - ], - "timestamp": 1534210131 - }, - { - "version": "1.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1532619515 - }, - { - "timestamp": 1532605697, - "version": "1.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532357734, - "version": "1.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532043000, - "version": "1.0.0", - "changes": [ - { - "note": "Add artifact adapter as a parameter for `CoverageSubprovider`. Export `AbstractArtifactAdapter`", - "pr": 589 - }, - { - "note": "Implement `SolCompilerArtifactAdapter` and `TruffleArtifactAdapter`", - "pr": 589 - }, - { - "note": "Properly parse multi-level traces", - "pr": 589 - }, - { - "note": "Add support for solidity libraries", - "pr": 589 - }, - { - "note": "Fixed a bug causing `RegExp` to crash if contract code is longer that 32767 characters", - "pr": 675 - }, - { - "note": "Fixed a bug caused by Geth debug trace depth being 1indexed", - "pr": 675 - }, - { - "note": "Fixed a bug when the tool crashed on empty traces", - "pr": 675 - }, - { - "note": "Use `BlockchainLifecycle` to support reverts on Geth", - "pr": 675 - }, - { - "note": "Add `ProfilerSubprovider` as a hacky way to profile code using coverage tools", - "pr": 675 - }, - { - "note": "Collect traces from `estimate_gas` calls", - "pr": 675 - }, - { - "note": "Fix a race condition caused by not awaiting the transaction before getting a trace", - "pr": 675 - }, - { - "note": "Add `start`/`stop` functionality to `CoverageSubprovider` and `ProfilerSubprovider`", - "pr": 675 - }, - { - "note": "Skip interface artifacts with a warning instead of failing", - "pr": 675 - }, - { - "note": "Fix `solcVersion` regex in parameter validation", - "pr": 690 - }, - { - "note": "Fix a bug when in `TruffleArtifactsAdapter` causing it to throw if `compiler.json` is not there", - "pr": 690 - }, - { - "note": "HUGE perf improvements", - "pr": 690 - }, - { - "note": "Create `RevertTraceSubprovider` which prints a stack trace when a `REVERT` is detected", - "pr": 705 - }, - { - "note": "Add source code snippets to stack traces printed by `RevertTraceSubprovider`", - "pr": 725 - } - ] - }, - { - "timestamp": 1531919263, - "version": "0.1.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1531149657, - "version": "0.1.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1529397769, - "version": "0.1.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.1.0", - "changes": [ - { - "note": "Incorrect publish that was unpublished" - } - ], - "timestamp": 1527810075 - }, - { - "timestamp": 1527009134, - "version": "0.0.11", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1525477860, - "version": "0.0.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1525428773, - "version": "0.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1524044013, - "version": "0.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1523462196, - "version": "0.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1522673609, - "version": "0.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1522658513, - "version": "0.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - } -] diff --git a/packages/sol-tracing-utils/CHANGELOG.md b/packages/sol-tracing-utils/CHANGELOG.md deleted file mode 100644 index c4f01b4e4b..0000000000 --- a/packages/sol-tracing-utils/CHANGELOG.md +++ /dev/null @@ -1,336 +0,0 @@ - - -CHANGELOG - -## v7.1.0 - _July 15, 2020_ - - * Make sol-profiler (mostly) work again (#2607) - -## v7.0.9 - _June 24, 2020_ - - * Dependencies updated - -## v7.0.8 - _February 25, 2020_ - - * Dependencies updated - -## v7.0.7 - _February 8, 2020_ - - * Dependencies updated - -## v7.0.6 - _February 6, 2020_ - - * Dependencies updated - -## v7.0.5 - _February 4, 2020_ - - * Dependencies updated - -## v7.0.4 - _January 22, 2020_ - - * Dependencies updated - -## v7.0.3 - _January 6, 2020_ - - * Dependencies updated - -## v7.0.2 - _December 17, 2019_ - - * Dependencies updated - -## v7.0.1 - _December 9, 2019_ - - * Dependencies updated - -## v7.0.0 - _December 2, 2019_ - - * Dependencies updated - -## v6.1.0-beta.4 - _December 2, 2019_ - - * Dependencies updated - -## v6.1.0-beta.3 - _November 20, 2019_ - - * Dependencies updated - -## v6.1.0-beta.2 - _November 17, 2019_ - - * Dependencies updated - -## v6.1.0-beta.1 - _November 7, 2019_ - - * Dependencies updated - -## v6.1.0-beta.0 - _October 3, 2019_ - - * Dependencies updated - -## v6.0.19 - _September 17, 2019_ - - * Dependencies updated - -## v6.0.18 - _September 3, 2019_ - - * Dependencies updated - -## v6.0.17 - _August 22, 2019_ - - * Dependencies updated - -## v6.0.16 - _August 8, 2019_ - - * Dependencies updated - -## v6.0.15 - _July 31, 2019_ - - * Dependencies updated - -## v6.0.14 - _July 24, 2019_ - - * Dependencies updated - -## v6.0.13 - _July 13, 2019_ - - * Dependencies updated - -## v6.0.12 - _May 24, 2019_ - - * Dependencies updated - -## v6.0.11 - _May 10, 2019_ - - * Dependencies updated - -## v6.0.10 - _April 11, 2019_ - - * Dependencies updated - -## v6.0.9 - _March 21, 2019_ - - * Dependencies updated - -## v6.0.8 - _March 20, 2019_ - - * Update solidity-parser-antlr to 0.4.2 (#1719) - -## v6.0.7 - _March 1, 2019_ - - * Fix a bug when `TruffleArtifactAdapter` wasn't correctly parsing solc config in pre-5.0 versions of Truffle (#1663) - * Fix a bug when `opCodes` gas costs were incorrect or `NaN` (#1663) - -## v6.0.6 - _February 27, 2019_ - - * Fix a bug when `TruffleArtifactAdapter` wasn't parsing solc config in the newest version of trufle (#1654) - -## v6.0.5 - _February 26, 2019_ - - * Dependencies updated - -## v6.0.4 - _February 25, 2019_ - - * Dependencies updated - -## v6.0.3 - _February 9, 2019_ - - * Dependencies updated - -## v6.0.2 - _February 7, 2019_ - - * Dependencies updated - -## v6.0.1 - _February 6, 2019_ - - * Dependencies updated - -## v6.0.0 - _February 5, 2019_ - - * `SolCompilerArtifactAdapter` now uses `SolResolver` under the hood which allows to resolve `NPM` dependencies properly (#1535) - * Cache the `utils.getContractDataIfExists` leading to faster execution (#1535) - * `SolCompilerArtifactAdapter` now doesn't return the `ContractData` for interfaces (#1535) - * Print resasonable error message on bytecode collision (#1535) - * Fix the bug in `ASTVisitor` causing the 'cannot read property `range` of `null`' error (#1557) - * Improve error messages when unable to find matching bytecode (#1558) - * Fix default gas limit for fake txs in `TraceCollectionSubprovider` (#1583) - * Fix a big when we were not intercepting `eth_sendRawTransaction` (#1584) - -## v5.0.0 - _Invalid date_ - - * Upgrade the bignumber.js to v8.0.2 (#1517) - -## v4.0.1 - _January 17, 2019_ - - * Fix a bug where a custom `Geth` tracer didn't return stack entries for `DELEGATECALL` (#1521) - * Fix a bug where `TraceCollectionSubprovider` was hanging on the fake `Geth` snapshot transaction (#1521) - * Fix/simplify handling of revert trace snippets (#1521) - -## v4.0.0 - _January 15, 2019_ - - * Fix a bug with incorrect parsing of `sourceMaps` due to sources being in an array instead of a map (#1498) - * Change the types of `ContractData.sources` and `ContractData.sourceCodes` to be objects instead of arrays (#1498) - * Use custom JS tracer to speed up tracing on clients that support it (e.g., Geth) (#1498) - * Log errors encountered in `TraceCollectionSubprovider` (#1498) - * Add support for assembly statements (#1498) - -## v3.0.0 - _January 11, 2019_ - - * Move out specific tools and leave just the shared parts of the codebase (#1492) - -## v2.1.17 - _January 9, 2019_ - - * Dependencies updated - -## v2.1.16 - _December 13, 2018_ - - * Dependencies updated - -## v2.1.15 - _December 11, 2018_ - - * Dependencies updated - -## v2.1.14 - _November 28, 2018_ - - * Dependencies updated - -## v2.1.13 - _November 21, 2018_ - - * Dependencies updated - -## v2.1.12 - _November 14, 2018_ - - * Dependencies updated - -## v2.1.11 - _November 13, 2018_ - - * Dependencies updated - -## v2.1.10 - _November 12, 2018_ - - * Dependencies updated - -## v2.1.9 - _November 9, 2018_ - - * Dependencies updated - -## v2.1.8 - _October 18, 2018_ - - * Make @types/solidity-parser-antlr a 'dependency' so it's available to users of the library (#1105) - -## v2.1.7 - _October 4, 2018_ - - * Dependencies updated - -## v2.1.6 - _September 28, 2018_ - - * Dependencies updated - -## v2.1.5 - _September 25, 2018_ - - * Dependencies updated - -## v2.1.4 - _September 25, 2018_ - - * Dependencies updated - -## v2.1.3 - _September 21, 2018_ - - * Dependencies updated - -## v2.1.2 - _September 5, 2018_ - - * Dependencies updated - -## v2.1.1 - _August 27, 2018_ - - * Dependencies updated - -## v2.1.0 - _August 24, 2018_ - - * Export types: `JSONRPCRequestPayload`, `Provider`, `JSONRPCErrorCallback`, `JSONRPCResponsePayload`, `JSONRPCRequestPayloadWithMethod`, `NextCallback`, `ErrorCallback`, `OnNextCompleted` and `Callback` (#924) - -## v2.0.0 - _August 14, 2018_ - - * Fix a bug when eth_call coverage was not computed because of silent schema validation failures (#938) - * Make `TruffleArtifactAdapter` read the `truffle.js` config for `solc` settings (#938) - * Change the first param of `TruffleArtifactAdapter` to be the `projectRoot` instead of `sourcesDir` (#938) - * Throw a helpful error message if truffle artifacts were generated with a different solc version than the one passed in (#938) - -## v1.0.3 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.2 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.1 - _July 23, 2018_ - - * Dependencies updated - -## v1.0.0 - _July 19, 2018_ - - * Add artifact adapter as a parameter for `CoverageSubprovider`. Export `AbstractArtifactAdapter` (#589) - * Implement `SolCompilerArtifactAdapter` and `TruffleArtifactAdapter` (#589) - * Properly parse multi-level traces (#589) - * Add support for solidity libraries (#589) - * Fixed a bug causing `RegExp` to crash if contract code is longer that 32767 characters (#675) - * Fixed a bug caused by Geth debug trace depth being 1indexed (#675) - * Fixed a bug when the tool crashed on empty traces (#675) - * Use `BlockchainLifecycle` to support reverts on Geth (#675) - * Add `ProfilerSubprovider` as a hacky way to profile code using coverage tools (#675) - * Collect traces from `estimate_gas` calls (#675) - * Fix a race condition caused by not awaiting the transaction before getting a trace (#675) - * Add `start`/`stop` functionality to `CoverageSubprovider` and `ProfilerSubprovider` (#675) - * Skip interface artifacts with a warning instead of failing (#675) - * Fix `solcVersion` regex in parameter validation (#690) - * Fix a bug when in `TruffleArtifactsAdapter` causing it to throw if `compiler.json` is not there (#690) - * HUGE perf improvements (#690) - * Create `RevertTraceSubprovider` which prints a stack trace when a `REVERT` is detected (#705) - * Add source code snippets to stack traces printed by `RevertTraceSubprovider` (#725) - -## v0.1.3 - _July 18, 2018_ - - * Dependencies updated - -## v0.1.2 - _July 9, 2018_ - - * Dependencies updated - -## v0.1.1 - _June 19, 2018_ - - * Dependencies updated - -## v0.1.0 - _May 31, 2018_ - - * Incorrect publish that was unpublished - -## v0.0.11 - _May 22, 2018_ - - * Dependencies updated - -## v0.0.10 - _May 4, 2018_ - - * Dependencies updated - -## v0.0.9 - _May 4, 2018_ - - * Dependencies updated - -## v0.0.8 - _April 18, 2018_ - - * Dependencies updated - -## v0.0.7 - _April 11, 2018_ - - * Dependencies updated - -## v0.0.6 - _April 2, 2018_ - - * Dependencies updated - -## v0.0.5 - _April 2, 2018_ - - * Dependencies updated diff --git a/packages/sol-tracing-utils/README.md b/packages/sol-tracing-utils/README.md deleted file mode 100644 index b768a06f97..0000000000 --- a/packages/sol-tracing-utils/README.md +++ /dev/null @@ -1,61 +0,0 @@ -## @0x/sol-tracing-utils - -Common code for all solidity trace-based tools (sol-coverage, sol-profiler, sol-trace). - -## Installation - -```bash -yarn add @0x/sol-tracing-utils -``` - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install dependencies - -If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: - -```bash -yarn config set workspaces-experimental true -``` - -Then install dependencies - -```bash -yarn install -``` - -### Build - -To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory: - -```bash -PKG=@0x/sol-tracing-utils yarn build -``` - -Or continuously rebuild on change: - -```bash -PKG=@0x/sol-tracing-utils yarn watch -``` - -### Clean - -```bash -yarn clean -``` - -### Lint - -```bash -yarn lint -``` - -### Run Tests - -```bash -yarn test -``` diff --git a/packages/sol-tracing-utils/compiler.json b/packages/sol-tracing-utils/compiler.json deleted file mode 100644 index 4697de2beb..0000000000 --- a/packages/sol-tracing-utils/compiler.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "contracts": ["SimpleStorage"], - "contractsDir": "test/fixtures/contracts", - "artifactsDir": "test/fixtures/artifacts", - "compilerSettings": { - "outputSelection": { - "*": { - "*": [ - "abi", - "devdoc", - "evm.bytecode.object", - "evm.bytecode.sourceMap", - "evm.deployedBytecode.object", - "evm.deployedBytecode.sourceMap" - ] - } - } - } -} diff --git a/packages/sol-tracing-utils/coverage/.gitkeep b/packages/sol-tracing-utils/coverage/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/sol-tracing-utils/package.json b/packages/sol-tracing-utils/package.json deleted file mode 100644 index e927fa82ec..0000000000 --- a/packages/sol-tracing-utils/package.json +++ /dev/null @@ -1,87 +0,0 @@ -{ - "name": "@0x/sol-tracing-utils", - "version": "7.1.0", - "engines": { - "node": ">=6.12" - }, - "description": "Common part of trace based solidity tools (sol-coverage, sol-trace, sol-profiler)", - "main": "lib/src/index.js", - "types": "lib/src/index.d.ts", - "scripts": { - "build": "yarn pre_build && tsc -b", - "build:ci": "yarn build", - "pre_build": "run-s copy_test_fixtures", - "lint": "tslint --format stylish --project .", - "fix": "tslint --fix --format stylish --project .", - "test": "run-s compile_test 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", - "run_mocha": "mocha --require source-map-support/register --require make-promises-safe lib/test/**/*_test.js --exit", - "clean": "shx rm -rf lib test/fixtures/artifacts src/artifacts generated_docs", - "copy_test_fixtures": "copyfiles 'test/fixtures/**/*' ./lib", - "compile_test": "sol-compiler compile" - }, - "config": { - "postpublish": { - "assets": [] - } - }, - "repository": { - "type": "git", - "url": "https://github.com/0xProject/0x-monorepo.git" - }, - "license": "Apache-2.0", - "bugs": { - "url": "https://github.com/0xProject/0x-monorepo/issues" - }, - "homepage": "https://github.com/0xProject/0x-monorepo/packages/sol-tracing-utils/README.md", - "dependencies": { - "@0x/dev-utils": "^3.3.0", - "@0x/sol-compiler": "^4.1.1", - "@0x/sol-resolver": "^3.1.0", - "@0x/subproviders": "^6.1.1", - "@0x/typescript-typings": "^5.1.1", - "@0x/utils": "^5.5.1", - "@0x/web3-wrapper": "^7.2.0", - "@types/solidity-parser-antlr": "^0.2.3", - "chalk": "^2.3.0", - "ethereum-types": "^3.2.0", - "ethereumjs-util": "^5.1.1", - "ethers": "~4.0.4", - "glob": "^7.1.2", - "istanbul": "^0.4.5", - "lodash": "^4.17.11", - "loglevel": "^1.6.1", - "mkdirp": "^0.5.1", - "rimraf": "^2.6.2", - "semaphore-async-await": "^1.5.1", - "solc": "^0.5.5", - "solidity-parser-antlr": "^0.4.2" - }, - "devDependencies": { - "@0x/tslint-config": "^4.1.0", - "@types/istanbul": "^0.4.30", - "@types/loglevel": "^1.5.3", - "@types/mkdirp": "^0.5.2", - "@types/mocha": "^5.2.7", - "@types/node": "12.12.54", - "@types/rimraf": "^2.0.2", - "chai": "^4.0.1", - "copyfiles": "^2.0.0", - "dirty-chai": "^2.0.1", - "make-promises-safe": "^1.1.0", - "mocha": "^6.2.0", - "npm-run-all": "^4.1.2", - "nyc": "^11.0.1", - "shx": "^0.2.2", - "sinon": "^4.0.0", - "tslint": "5.11.0", - "typescript": "3.0.1" - }, - "publishConfig": { - "access": "public" - }, - "gitHead": "4f91bfd907996b2f4dd383778b50c479c2602b56" -} diff --git a/packages/sol-tracing-utils/src/artifact_adapters/abstract_artifact_adapter.ts b/packages/sol-tracing-utils/src/artifact_adapters/abstract_artifact_adapter.ts deleted file mode 100644 index fcc6562ad1..0000000000 --- a/packages/sol-tracing-utils/src/artifact_adapters/abstract_artifact_adapter.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { ContractData } from '../types'; - -export abstract class AbstractArtifactAdapter { - public abstract async collectContractsDataAsync(): Promise; -} diff --git a/packages/sol-tracing-utils/src/artifact_adapters/sol_compiler_artifact_adapter.ts b/packages/sol-tracing-utils/src/artifact_adapters/sol_compiler_artifact_adapter.ts deleted file mode 100644 index d668b58903..0000000000 --- a/packages/sol-tracing-utils/src/artifact_adapters/sol_compiler_artifact_adapter.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { - FallthroughResolver, - FSResolver, - NameResolver, - NPMResolver, - RelativeFSResolver, - URLResolver, -} from '@0x/sol-resolver'; -import { logUtils } from '@0x/utils'; -import { CompilerOptions, ContractArtifact } from 'ethereum-types'; -import * as fs from 'fs'; -import * as glob from 'glob'; -import * as _ from 'lodash'; -import * as path from 'path'; - -import { ContractData, SourceCodes, Sources } from '../types'; - -import { AbstractArtifactAdapter } from './abstract_artifact_adapter'; - -const CONFIG_FILE = 'compiler.json'; - -export class SolCompilerArtifactAdapter extends AbstractArtifactAdapter { - private readonly _artifactsPath: string; - private readonly _sourcesPath: string; - private readonly _resolver: FallthroughResolver; - /** - * Instantiates a SolCompilerArtifactAdapter - * @param artifactsPath Path to your artifacts directory - * @param sourcesPath Path to your contract sources directory - */ - constructor(artifactsPath?: string, sourcesPath?: string) { - super(); - const config: CompilerOptions = fs.existsSync(CONFIG_FILE) - ? JSON.parse(fs.readFileSync(CONFIG_FILE).toString()) - : {}; - if (artifactsPath === undefined && config.artifactsDir === undefined) { - throw new Error(`artifactsDir not found in ${CONFIG_FILE}`); - } - this._artifactsPath = (artifactsPath || config.artifactsDir) as string; - if (sourcesPath === undefined && config.contractsDir === undefined) { - throw new Error(`contractsDir not found in ${CONFIG_FILE}`); - } - this._sourcesPath = (sourcesPath || config.contractsDir) as string; - this._resolver = new FallthroughResolver(); - this._resolver.appendResolver(new URLResolver()); - const packagePath = path.resolve(''); - this._resolver.appendResolver(new NPMResolver(packagePath)); - this._resolver.appendResolver(new RelativeFSResolver(this._sourcesPath)); - this._resolver.appendResolver(new FSResolver()); - this._resolver.appendResolver(new NameResolver(this._sourcesPath)); - } - public async collectContractsDataAsync(): Promise { - const artifactsGlob = `${this._artifactsPath}/**/*.json`; - const artifactFileNames = glob.sync(artifactsGlob, { absolute: true }); - const contractsData: ContractData[] = []; - for (const artifactFileName of artifactFileNames) { - const artifact: ContractArtifact = JSON.parse(fs.readFileSync(artifactFileName).toString()); - if (artifact.compilerOutput === undefined || artifact.compilerOutput.evm === undefined) { - logUtils.warn(`${artifactFileName} doesn't contain bytecode. Skipping...`); - continue; - } - const sources: Sources = {}; - const sourceCodes: SourceCodes = {}; - _.map(artifact.sources, (value: { id: number }, relativeFilePath: string) => { - const source = this._resolver.resolve(relativeFilePath); - sources[value.id] = source.absolutePath; - sourceCodes[value.id] = source.source; - }); - const contractData = { - name: artifact.contractName, - sourceCodes, - sources, - bytecode: artifact.compilerOutput.evm.bytecode.object, - sourceMap: artifact.compilerOutput.evm.bytecode.sourceMap, - runtimeBytecode: artifact.compilerOutput.evm.deployedBytecode.object, - sourceMapRuntime: artifact.compilerOutput.evm.deployedBytecode.sourceMap, - }; - const isInterfaceContract = contractData.bytecode === '0x' && contractData.runtimeBytecode === '0x'; - if (isInterfaceContract) { - continue; - } - contractsData.push(contractData); - } - return contractsData; - } -} diff --git a/packages/sol-tracing-utils/src/artifact_adapters/truffle_artifact_adapter.ts b/packages/sol-tracing-utils/src/artifact_adapters/truffle_artifact_adapter.ts deleted file mode 100644 index 4c6505699f..0000000000 --- a/packages/sol-tracing-utils/src/artifact_adapters/truffle_artifact_adapter.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { Compiler, CompilerOptions } from '@0x/sol-compiler'; -import * as fs from 'fs'; -import * as glob from 'glob'; -import * as _ from 'lodash'; -import * as path from 'path'; -import * as solc from 'solc'; - -import { ContractData } from '../types'; - -import { AbstractArtifactAdapter } from './abstract_artifact_adapter'; -import { SolCompilerArtifactAdapter } from './sol_compiler_artifact_adapter'; - -const DEFAULT_TRUFFLE_ARTIFACTS_DIR = './build/contracts'; - -interface TruffleSolcConfig { - version?: string; - settings?: solc.CompilerSettings; -} -interface TruffleConfig { - solc?: TruffleSolcConfig; - compilers?: { - solc?: TruffleSolcConfig; - }; - contracts_build_directory?: string; -} - -export class TruffleArtifactAdapter extends AbstractArtifactAdapter { - private readonly _solcVersion: string; - private readonly _projectRoot: string; - /** - * Instantiates a TruffleArtifactAdapter - * @param projectRoot Path to the truffle project's root directory - * @param solcVersion Solidity version with which to compile all the contracts - */ - constructor(projectRoot: string, solcVersion: string) { - super(); - this._solcVersion = solcVersion; - this._projectRoot = projectRoot; - } - public async collectContractsDataAsync(): Promise { - const artifactsDir = '.0x-artifacts'; - const contractsDir = path.join(this._projectRoot, 'contracts'); - const truffleConfig = this._getTruffleConfig(); - const solcConfig = this._getTruffleSolcSettings(); - const truffleArtifactsDirectory = truffleConfig.contracts_build_directory || DEFAULT_TRUFFLE_ARTIFACTS_DIR; - this._assertSolidityVersionIsCorrect(truffleArtifactsDirectory); - const compilerOptions: CompilerOptions = { - contractsDir, - artifactsDir, - compilerSettings: { - ...solcConfig, - outputSelection: { - ['*']: { - ['*']: ['abi', 'evm.bytecode.object', 'evm.deployedBytecode.object'], - }, - }, - }, - contracts: '*', - solcVersion: this._solcVersion, - }; - const compiler = new Compiler(compilerOptions); - await compiler.compileAsync(); - const solCompilerArtifactAdapter = new SolCompilerArtifactAdapter(artifactsDir, contractsDir); - const contractsDataFrom0xArtifacts = await solCompilerArtifactAdapter.collectContractsDataAsync(); - return contractsDataFrom0xArtifacts; - } - private _getTruffleConfig(): TruffleConfig { - const truffleConfigFileShort = path.resolve(path.join(this._projectRoot, 'truffle.js')); - const truffleConfigFileLong = path.resolve(path.join(this._projectRoot, 'truffle-config.js')); - if (fs.existsSync(truffleConfigFileShort)) { - const truffleConfig = require(truffleConfigFileShort); - return truffleConfig; - } else if (fs.existsSync(truffleConfigFileLong)) { - const truffleConfig = require(truffleConfigFileLong); - return truffleConfig; - } else { - throw new Error( - `Neither ${truffleConfigFileShort} nor ${truffleConfigFileLong} exists. Make sure the project root is correct`, - ); - } - } - private _getTruffleSolcSettings(): Partial { - const truffleConfig = this._getTruffleConfig(); - if (truffleConfig.solc !== undefined) { - // Truffle < 5.0 - return (truffleConfig as any).solc; - } else if ((truffleConfig as any).compilers.solc !== undefined) { - // Truffle >= 5.0 - return (truffleConfig as any).compilers.solc.settings; - } else { - return {}; - } - } - private _assertSolidityVersionIsCorrect(truffleArtifactsDirectory: string): void { - const artifactsGlob = `${truffleArtifactsDirectory}/**/*.json`; - const artifactFileNames = glob.sync(artifactsGlob, { absolute: true }); - for (const artifactFileName of artifactFileNames) { - const artifact = JSON.parse(fs.readFileSync(artifactFileName).toString()); - const compilerVersion = artifact.compiler.version; - if (!compilerVersion.startsWith(this._solcVersion)) { - throw new Error( - `${artifact.contractName} was compiled with solidity ${compilerVersion} but specified version is ${ - this._solcVersion - } making it impossible to process traces`, - ); - } - } - } -} diff --git a/packages/sol-tracing-utils/src/ast_visitor.ts b/packages/sol-tracing-utils/src/ast_visitor.ts deleted file mode 100644 index 637ef528d9..0000000000 --- a/packages/sol-tracing-utils/src/ast_visitor.ts +++ /dev/null @@ -1,194 +0,0 @@ -import * as _ from 'lodash'; -import * as Parser from 'solidity-parser-antlr'; - -import { BranchMap, FnMap, OffsetToLocation, SingleFileSourceRange, StatementMap } from './types'; - -export interface CoverageEntriesDescription { - fnMap: FnMap; - branchMap: BranchMap; - statementMap: StatementMap; - modifiersStatementIds: number[]; -} - -enum BranchType { - If = 'if', - ConditionalExpression = 'cond-expr', - BinaryExpression = 'binary-expr', -} - -export class ASTVisitor { - private _entryId = 0; - private readonly _fnMap: FnMap = {}; - private readonly _branchMap: BranchMap = {}; - private readonly _modifiersStatementIds: number[] = []; - private readonly _statementMap: StatementMap = {}; - private readonly _offsetToLocation: OffsetToLocation; - private readonly _ignoreRangesBeginningAt: number[]; - // keep track of contract/function ranges that are to be ignored - // so we can also ignore any children nodes within the contract/function - private readonly _ignoreRangesWithin: Array<[number, number]> = []; - constructor(offsetToLocation: OffsetToLocation, ignoreRangesBeginningAt: number[] = []) { - this._offsetToLocation = offsetToLocation; - this._ignoreRangesBeginningAt = ignoreRangesBeginningAt; - } - public getCollectedCoverageEntries(): CoverageEntriesDescription { - const coverageEntriesDescription = { - fnMap: this._fnMap, - branchMap: this._branchMap, - statementMap: this._statementMap, - modifiersStatementIds: this._modifiersStatementIds, - }; - return coverageEntriesDescription; - } - public IfStatement(ast: Parser.IfStatement): void { - this._visitStatement(ast); - this._visitBinaryBranch(ast, ast.trueBody, ast.falseBody || ast, BranchType.If); - } - public FunctionDefinition(ast: Parser.FunctionDefinition): void { - this._visitFunctionLikeDefinition(ast); - } - public ContractDefinition(ast: Parser.ContractDefinition): void { - if (this._shouldIgnoreExpression(ast)) { - this._ignoreRangesWithin.push(ast.range as [number, number]); - } - } - public ModifierDefinition(ast: Parser.ModifierDefinition): void { - this._visitFunctionLikeDefinition(ast); - } - public ForStatement(ast: Parser.ForStatement): void { - this._visitStatement(ast); - } - public ReturnStatement(ast: Parser.ReturnStatement): void { - this._visitStatement(ast); - } - public BreakStatement(ast: Parser.BreakStatement): void { - this._visitStatement(ast); - } - public ContinueStatement(ast: Parser.ContinueStatement): void { - this._visitStatement(ast); - } - public EmitStatement(ast: any /* TODO: Parser.EmitStatement */): void { - this._visitStatement(ast); - } - public VariableDeclarationStatement(ast: Parser.VariableDeclarationStatement): void { - this._visitStatement(ast); - } - public WhileStatement(ast: Parser.WhileStatement): void { - this._visitStatement(ast); - } - public ThrowStatement(ast: Parser.ThrowStatement): void { - this._visitStatement(ast); - } - public DoWhileStatement(ast: Parser.DoWhileStatement): void { - this._visitStatement(ast); - } - public ExpressionStatement(ast: Parser.ExpressionStatement): void { - if (ast.expression !== null) { - this._visitStatement(ast.expression); - } - } - public InlineAssemblyStatement(ast: Parser.InlineAssemblyStatement): void { - this._visitStatement(ast); - } - public AssemblyLocalDefinition(ast: Parser.AssemblyLocalDefinition): void { - this._visitStatement(ast); - } - public AssemblyCall(ast: Parser.AssemblyCall): void { - this._visitStatement(ast); - } - public AssemblyIf(ast: Parser.AssemblyIf): void { - this._visitStatement(ast); - } - public AssemblyBlock(ast: Parser.AssemblyBlock): void { - this._visitStatement(ast); - } - public AssemblyAssignment(ast: Parser.AssemblyAssignment): void { - this._visitStatement(ast); - } - public LabelDefinition(ast: Parser.LabelDefinition): void { - this._visitStatement(ast); - } - public AssemblySwitch(ast: Parser.AssemblySwitch): void { - this._visitStatement(ast); - } - public AssemblyFunctionDefinition(ast: Parser.AssemblyFunctionDefinition): void { - this._visitStatement(ast); - } - public AssemblyFor(ast: Parser.AssemblyFor): void { - this._visitStatement(ast); - } - public SubAssembly(ast: Parser.SubAssembly): void { - this._visitStatement(ast); - } - public BinaryOperation(ast: Parser.BinaryOperation): void { - const BRANCHING_BIN_OPS = ['&&', '||']; - if (_.includes(BRANCHING_BIN_OPS, ast.operator)) { - this._visitBinaryBranch(ast, ast.left, ast.right, BranchType.BinaryExpression); - } - } - public Conditional(ast: Parser.Conditional): void { - this._visitBinaryBranch(ast, ast.trueExpression, ast.falseExpression, BranchType.ConditionalExpression); - } - public ModifierInvocation(ast: Parser.ModifierInvocation): void { - const BUILTIN_MODIFIERS = ['public', 'view', 'payable', 'external', 'internal', 'pure', 'constant']; - if (!_.includes(BUILTIN_MODIFIERS, ast.name)) { - if (this._shouldIgnoreExpression(ast)) { - return; - } - this._modifiersStatementIds.push(this._entryId); - this._visitStatement(ast); - } - } - private _visitBinaryBranch( - ast: Parser.ASTNode, - left: Parser.ASTNode, - right: Parser.ASTNode, - type: BranchType, - ): void { - if (this._shouldIgnoreExpression(ast)) { - return; - } - this._branchMap[this._entryId++] = { - line: this._getExpressionRange(ast).start.line, - type, - locations: [this._getExpressionRange(left), this._getExpressionRange(right)], - }; - } - private _visitStatement(ast: Parser.ASTNode): void { - if (this._shouldIgnoreExpression(ast)) { - return; - } - this._statementMap[this._entryId++] = this._getExpressionRange(ast); - } - private _getExpressionRange(ast: Parser.ASTNode): SingleFileSourceRange { - const astRange = ast.range as [number, number]; - const start = this._offsetToLocation[astRange[0]]; - const end = this._offsetToLocation[astRange[1] + 1]; - const range = { - start, - end, - }; - return range; - } - private _shouldIgnoreExpression(ast: Parser.ASTNode): boolean { - const [astStart, astEnd] = ast.range as [number, number]; - const isRangeIgnored = _.some( - this._ignoreRangesWithin, - ([rangeStart, rangeEnd]: [number, number]) => astStart >= rangeStart && astEnd <= rangeEnd, - ); - return this._ignoreRangesBeginningAt.includes(astStart) || isRangeIgnored; - } - private _visitFunctionLikeDefinition(ast: Parser.ModifierDefinition | Parser.FunctionDefinition): void { - if (this._shouldIgnoreExpression(ast)) { - this._ignoreRangesWithin.push(ast.range as [number, number]); - return; - } - const loc = this._getExpressionRange(ast); - this._fnMap[this._entryId++] = { - name: ast.name, - line: loc.start.line, - loc, - }; - this._visitStatement(ast); - } -} diff --git a/packages/sol-tracing-utils/src/collect_coverage_entries.ts b/packages/sol-tracing-utils/src/collect_coverage_entries.ts deleted file mode 100644 index b7413613eb..0000000000 --- a/packages/sol-tracing-utils/src/collect_coverage_entries.ts +++ /dev/null @@ -1,40 +0,0 @@ -import * as ethUtil from 'ethereumjs-util'; -import * as _ from 'lodash'; -import * as parser from 'solidity-parser-antlr'; - -import { ASTVisitor, CoverageEntriesDescription } from './ast_visitor'; -import { getOffsetToLocation } from './source_maps'; - -// Parsing source code for each transaction/code is slow and therefore we cache it -const sourceHashToCoverageEntries: { [sourceHash: string]: CoverageEntriesDescription } = {}; - -export const collectCoverageEntries = (contractSource: string, ignoreRegexp?: RegExp) => { - const sourceHash = ethUtil.sha3(contractSource).toString('hex'); - if (sourceHashToCoverageEntries[sourceHash] === undefined && contractSource !== undefined) { - const ast = parser.parse(contractSource, { range: true }); - const offsetToLocation = getOffsetToLocation(contractSource); - const ignoreRangesBeginningAt = - ignoreRegexp === undefined ? [] : gatherRangesToIgnore(contractSource, ignoreRegexp); - const visitor = new ASTVisitor(offsetToLocation, ignoreRangesBeginningAt); - parser.visit(ast, visitor); - sourceHashToCoverageEntries[sourceHash] = visitor.getCollectedCoverageEntries(); - } - const coverageEntriesDescription = sourceHashToCoverageEntries[sourceHash]; - return coverageEntriesDescription; -}; - -// Gather the start index of all code blocks preceeded by "/* solcov ignore next */" -function gatherRangesToIgnore(contractSource: string, ignoreRegexp: RegExp): number[] { - const ignoreRangesStart = []; - - let match; - do { - match = ignoreRegexp.exec(contractSource); - if (match) { - const matchLen = match[0].length; - ignoreRangesStart.push(match.index + matchLen); - } - } while (match); - - return ignoreRangesStart; -} diff --git a/packages/sol-tracing-utils/src/constants.ts b/packages/sol-tracing-utils/src/constants.ts deleted file mode 100644 index 9135187879..0000000000 --- a/packages/sol-tracing-utils/src/constants.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { OpCode } from 'ethereum-types'; - -import { OpCodeToGasCost, OpCodeToParamToStackOffset } from './types'; - -const opCodeToParamToStackOffset: OpCodeToParamToStackOffset = { - [OpCode.Call]: { - gas: 0, - to: 1, - value: 1, - }, - [OpCode.MLoad]: { offset: 0 }, - [OpCode.MStore]: { offset: 0 }, - [OpCode.MStore8]: { offset: 0 }, - [OpCode.CallDataCopy]: { memoryOffset: 0, callDataOffset: 1, length: 2 }, -}; - -const opCodeToGasCost: OpCodeToGasCost = { - [OpCode.Call]: 700, - [OpCode.StaticCall]: 40, -}; - -// tslint:disable:number-literal-format -export const constants = { - NEW_CONTRACT: 'NEW_CONTRACT' as 'NEW_CONTRACT', - HEX_BASE: 16, - PUSH1: 0x60, - PUSH2: 0x61, - PUSH32: 0x7f, - TIMESTAMP: 0x42, - opCodeToGasCost, - opCodeToParamToStackOffset, -}; diff --git a/packages/sol-tracing-utils/src/get_source_range_snippet.ts b/packages/sol-tracing-utils/src/get_source_range_snippet.ts deleted file mode 100644 index c1f6e3a4e9..0000000000 --- a/packages/sol-tracing-utils/src/get_source_range_snippet.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { SourceRange, SourceSnippet } from './types'; -import { utils } from './utils'; - -/** - * Gets the source range snippet by source range to be used by revert trace. - * @param sourceRange source range - * @param sourceCode source code - */ -export function getSourceRangeSnippet(sourceRange: SourceRange, sourceCode: string): SourceSnippet { - const sourceCodeInRange = utils.getRange(sourceCode, sourceRange.location); - return { - range: sourceRange.location, - source: sourceCodeInRange, - fileName: sourceRange.fileName, - }; -} diff --git a/packages/sol-tracing-utils/src/globals.d.ts b/packages/sol-tracing-utils/src/globals.d.ts deleted file mode 100644 index e799b35298..0000000000 --- a/packages/sol-tracing-utils/src/globals.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// tslint:disable:completed-docs -declare module '*.json' { - const json: any; - /* tslint:disable */ - export default json; - /* tslint:enable */ -} diff --git a/packages/sol-tracing-utils/src/index.ts b/packages/sol-tracing-utils/src/index.ts deleted file mode 100644 index 86fc299fee..0000000000 --- a/packages/sol-tracing-utils/src/index.ts +++ /dev/null @@ -1,42 +0,0 @@ -export { SolCompilerArtifactAdapter } from './artifact_adapters/sol_compiler_artifact_adapter'; -export { TruffleArtifactAdapter } from './artifact_adapters/truffle_artifact_adapter'; -export { AbstractArtifactAdapter } from './artifact_adapters/abstract_artifact_adapter'; - -export { - ContractData, - EvmCallStack, - SourceRange, - SourceSnippet, - StatementCoverage, - StatementDescription, - BranchCoverage, - BranchDescription, - Subtrace, - SubTraceInfo, - Coverage, - LineColumn, - LineCoverage, - FunctionCoverage, - FunctionDescription, - SingleFileSourceRange, - BranchMap, - EvmCallStackEntry, - FnMap, - OffsetToLocation, - StatementMap, - TraceInfo, - SubTraceInfoBase, - SubTraceInfoExistingContract, - SubTraceInfoNewContract, - Sources, - SourceCodes, -} from './types'; -export { collectCoverageEntries } from './collect_coverage_entries'; -export { TraceCollector, SingleFileSubtraceHandler } from './trace_collector'; -export { TraceInfoSubprovider } from './trace_info_subprovider'; -export { utils } from './utils'; -export { constants } from './constants'; -export { parseSourceMap } from './source_maps'; -export { getSourceRangeSnippet } from './get_source_range_snippet'; -export { getRevertTrace } from './revert_trace'; -export { TraceCollectionSubprovider } from './trace_collection_subprovider'; diff --git a/packages/sol-tracing-utils/src/instructions.ts b/packages/sol-tracing-utils/src/instructions.ts deleted file mode 100644 index 40987dbe52..0000000000 --- a/packages/sol-tracing-utils/src/instructions.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { constants } from './constants'; - -const isPush = (inst: number) => inst >= constants.PUSH1 && inst <= constants.PUSH32; - -const pushDataLength = (inst: number) => inst - constants.PUSH1 + 1; - -const instructionLength = (inst: number) => (isPush(inst) ? pushDataLength(inst) + 1 : 1); - -export const getPcToInstructionIndexMapping = (bytecode: Uint8Array) => { - const result: { - [programCounter: number]: number; - } = {}; - let byteIndex = 0; - let instructionIndex = 0; - while (byteIndex < bytecode.length) { - const instruction = bytecode[byteIndex]; - const length = instructionLength(instruction); - result[byteIndex] = instructionIndex; - byteIndex += length; - instructionIndex += 1; - } - return result; -}; diff --git a/packages/sol-tracing-utils/src/revert_trace.ts b/packages/sol-tracing-utils/src/revert_trace.ts deleted file mode 100644 index a7c3b96223..0000000000 --- a/packages/sol-tracing-utils/src/revert_trace.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { logUtils } from '@0x/utils'; -import { OpCode, StructLog } from 'ethereum-types'; - -import * as _ from 'lodash'; - -import { constants } from './constants'; -import { EvmCallStack } from './types'; -import { utils } from './utils'; - -/** - * Converts linear trace to a call stack by following calls and returns - * @param structLogs Linear trace - * @param startAddress The address of initial context - */ -export function getRevertTrace(structLogs: StructLog[], startAddress: string): EvmCallStack { - const evmCallStack: EvmCallStack = []; - const addressStack = [startAddress]; - if (_.isEmpty(structLogs)) { - return []; - } - // tslint:disable-next-line:prefer-for-of - for (let i = 0; i < structLogs.length; i++) { - const structLog = structLogs[i]; - if (structLog.depth !== addressStack.length - 1) { - throw new Error("Malformed trace. Trace depth doesn't match call stack depth"); - } - // After that check we have a guarantee that call stack is never empty - // If it would: callStack.length - 1 === structLog.depth === -1 - // That means that we can always safely pop from it - - if (utils.isCallLike(structLog.op)) { - const currentAddress = _.last(addressStack) as string; - const newAddress = utils.getAddressFromStackEntry( - structLog.stack[structLog.stack.length - constants.opCodeToParamToStackOffset[OpCode.Call].to - 1], - ); - - // Sometimes calls don't change the execution context (current address). When we do a transfer to an - // externally owned account - it does the call and immediately returns because there is no fallback - // function. We manually check if the call depth had changed to handle that case. - const nextStructLog = structLogs[i + 1]; - if (nextStructLog.depth !== structLog.depth) { - addressStack.push(newAddress); - evmCallStack.push({ - address: currentAddress, - structLog, - }); - } - } else if (utils.isEndOpcode(structLog.op) && structLog.op !== OpCode.Revert) { - // Just like with calls, sometimes returns/stops don't change the execution context (current address). - const nextStructLog = structLogs[i + 1]; - if (nextStructLog === undefined || nextStructLog.depth !== structLog.depth) { - evmCallStack.pop(); - addressStack.pop(); - } - if (structLog.op === OpCode.SelfDestruct) { - // After contract execution, we look at all sub-calls to external contracts, and for each one, fetch - // the bytecode and compute the coverage for the call. If the contract is destroyed with a call - // to `selfdestruct`, we are unable to fetch it's bytecode and compute coverage. - // TODO: Refactor this logic to fetch the sub-called contract bytecode before the selfdestruct is called - // in order to handle this edge-case. - logUtils.warn( - "Detected a selfdestruct. We currently do not support that scenario. We'll just skip the trace part for a destructed contract", - ); - } - } else if (structLog.op === OpCode.Revert) { - evmCallStack.push({ - address: _.last(addressStack) as string, - structLog, - }); - return evmCallStack; - } else if (structLog.op === OpCode.Create) { - // TODO: Extract the new contract address from the stack and handle that scenario - logUtils.warn( - "Detected a contract created from within another contract. We currently do not support that scenario. We'll just skip that trace", - ); - return []; - } else { - if (structLog !== _.last(structLogs)) { - const nextStructLog = structLogs[i + 1]; - if (nextStructLog.depth === structLog.depth) { - continue; - } else if (nextStructLog.depth === structLog.depth - 1) { - addressStack.pop(); - } else { - throw new Error('Malformed trace. Unexpected call depth change'); - } - } - } - } - if (evmCallStack.length !== 0) { - logUtils.warn('Malformed trace. Call stack non empty at the end. (probably out of gas)'); - } - return []; -} diff --git a/packages/sol-tracing-utils/src/source_maps.ts b/packages/sol-tracing-utils/src/source_maps.ts deleted file mode 100644 index 7f80fc589a..0000000000 --- a/packages/sol-tracing-utils/src/source_maps.ts +++ /dev/null @@ -1,98 +0,0 @@ -import * as _ from 'lodash'; - -import { getPcToInstructionIndexMapping } from './instructions'; -import { OffsetToLocation, SourceCodes, SourceRange, Sources } from './types'; - -const RADIX = 10; - -export interface SourceLocation { - offset: number; - length: number; - fileIndex: number; -} - -/** - * Receives a string with newlines and returns a map of byte offset to LineColumn - * @param str A string to process - */ -export function getOffsetToLocation(str: string): OffsetToLocation { - const offsetToLocation: OffsetToLocation = { 0: { line: 1, column: 0 } }; - let currentOffset = 0; - for (const char of str.split('')) { - const location = offsetToLocation[currentOffset]; - const isNewline = char === '\n'; - offsetToLocation[currentOffset + 1] = { - line: location.line + (isNewline ? 1 : 0), - column: isNewline ? 0 : location.column + 1, - }; - currentOffset++; - } - return offsetToLocation; -} - -/** - * Parses a sourcemap string. - * The solidity sourcemap format is documented here: https://github.com/ethereum/solidity/blob/develop/docs/miscellaneous.rst#source-mappings - * @param indexToSourceCode index to source code - * @param srcMap source map string - * @param bytecodeHex contract bytecode - * @param indexToSource index to source file path - */ -export function parseSourceMap( - sourceCodes: SourceCodes, - srcMap: string, - bytecodeHex: string, - sources: Sources, -): { [programCounter: number]: SourceRange } { - const bytecode = Uint8Array.from(Buffer.from(bytecodeHex, 'hex')); - const pcToInstructionIndex: { [programCounter: number]: number } = getPcToInstructionIndexMapping(bytecode); - const fileIndexToOffsetToLocation: { [fileIndex: number]: OffsetToLocation } = {}; - _.map(sourceCodes, (sourceCode: string, fileIndex: number) => { - fileIndexToOffsetToLocation[fileIndex] = sourceCode === undefined ? {} : getOffsetToLocation(sourceCode); - }); - const entries = srcMap.split(';'); - let lastParsedEntry: SourceLocation = {} as any; - const instructionIndexToSourceRange: { [instructionIndex: number]: SourceRange } = {}; - _.each(entries, (entry: string, i: number) => { - // tslint:disable-next-line:no-unused-variable - const [instructionIndexStrIfExists, lengthStrIfExists, fileIndexStrIfExists, jumpTypeStrIfExists] = entry.split( - ':', - ); - const instructionIndexIfExists = parseInt(instructionIndexStrIfExists, RADIX); - const lengthIfExists = parseInt(lengthStrIfExists, RADIX); - const fileIndexIfExists = parseInt(fileIndexStrIfExists, RADIX); - const offset = _.isNaN(instructionIndexIfExists) ? lastParsedEntry.offset : instructionIndexIfExists; - const length = _.isNaN(lengthIfExists) ? lastParsedEntry.length : lengthIfExists; - const fileIndex = _.isNaN(fileIndexIfExists) ? lastParsedEntry.fileIndex : fileIndexIfExists; - const parsedEntry = { - offset, - length, - fileIndex, - }; - if (parsedEntry.fileIndex !== -1 && fileIndexToOffsetToLocation[parsedEntry.fileIndex] !== undefined) { - const offsetToLocation = fileIndexToOffsetToLocation[parsedEntry.fileIndex]; - const sourceRange = { - location: { - start: offsetToLocation[parsedEntry.offset], - end: offsetToLocation[parsedEntry.offset + parsedEntry.length], - }, - fileName: sources[parsedEntry.fileIndex], - }; - if (sourceRange.location.start === undefined || sourceRange.location.end === undefined) { - throw new Error(`Error while processing sourcemap: location out of range in ${sourceRange.fileName}`); - } - instructionIndexToSourceRange[i] = sourceRange; - } else { - // Some assembly code generated by Solidity can't be mapped back to a line of source code. - // Source: https://github.com/ethereum/solidity/issues/3629 - } - lastParsedEntry = parsedEntry; - }); - const pcsToSourceRange: { [programCounter: number]: SourceRange } = {}; - for (const programCounterKey of _.keys(pcToInstructionIndex)) { - const pc = parseInt(programCounterKey, RADIX); - const instructionIndex: number = pcToInstructionIndex[pc]; - pcsToSourceRange[pc] = instructionIndexToSourceRange[instructionIndex]; - } - return pcsToSourceRange; -} diff --git a/packages/sol-tracing-utils/src/trace.ts b/packages/sol-tracing-utils/src/trace.ts deleted file mode 100644 index 5de63bdbd5..0000000000 --- a/packages/sol-tracing-utils/src/trace.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { logUtils } from '@0x/utils'; -import { OpCode, StructLog } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { constants } from './constants'; -import { utils } from './utils'; - -export interface ContractAddressToTraces { - [contractAddress: string]: StructLog[]; -} - -/** - * Converts linear stack trace to `ContractAddressToTraces`. - * @param structLogs stack trace - * @param startAddress initial context address - */ -export function getContractAddressToTraces(structLogs: StructLog[], startAddress: string): ContractAddressToTraces { - const contractAddressToTraces: ContractAddressToTraces = {}; - let currentTraceSegment = []; - const addressStack = [startAddress]; - if (_.isEmpty(structLogs)) { - return contractAddressToTraces; - } - // tslint:disable-next-line:prefer-for-of - for (let i = 0; i < structLogs.length; i++) { - const structLog = structLogs[i]; - if (structLog.depth !== addressStack.length - 1) { - throw new Error("Malformed trace. Trace depth doesn't match call stack depth"); - } - // After that check we have a guarantee that call stack is never empty - // If it would: callStack.length - 1 === structLog.depth === -1 - // That means that we can always safely pop from it - currentTraceSegment.push(structLog); - - if (utils.isCallLike(structLog.op)) { - const currentAddress = _.last(addressStack) as string; - const newAddress = utils.getAddressFromStackEntry( - structLog.stack[structLog.stack.length - constants.opCodeToParamToStackOffset[OpCode.Call].to - 1], - ); - - // Sometimes calls don't change the execution context (current address). When we do a transfer to an - // externally owned account - it does the call and immediately returns because there is no fallback - // function. We manually check if the call depth had changed to handle that case. - const nextStructLog = structLogs[i + 1]; - if (nextStructLog.depth !== structLog.depth) { - addressStack.push(newAddress); - contractAddressToTraces[currentAddress] = (contractAddressToTraces[currentAddress] || []).concat( - currentTraceSegment, - ); - currentTraceSegment = []; - } - } else if (utils.isEndOpcode(structLog.op)) { - const currentAddress = addressStack.pop() as string; - contractAddressToTraces[currentAddress] = (contractAddressToTraces[currentAddress] || []).concat( - currentTraceSegment, - ); - currentTraceSegment = []; - if (structLog.op === OpCode.SelfDestruct) { - // After contract execution, we look at all sub-calls to external contracts, and for each one, fetch - // the bytecode and compute the coverage for the call. If the contract is destroyed with a call - // to `selfdestruct`, we are unable to fetch it's bytecode and compute coverage. - // TODO: Refactor this logic to fetch the sub-called contract bytecode before the selfdestruct is called - // in order to handle this edge-case. - logUtils.warn( - "Detected a selfdestruct. We currently do not support that scenario. We'll just skip the trace part for a destructed contract", - ); - } - } else if (structLog.op === OpCode.Create) { - // TODO: Extract the new contract address from the stack and handle that scenario - logUtils.warn( - "Detected a contract created from within another contract. We currently do not support that scenario. We'll just skip that trace", - ); - return contractAddressToTraces; - } else { - if (structLog !== _.last(structLogs)) { - const nextStructLog = structLogs[i + 1]; - if (nextStructLog.depth === structLog.depth) { - continue; - } else if (nextStructLog.depth === structLog.depth - 1) { - const currentAddress = addressStack.pop() as string; - contractAddressToTraces[currentAddress] = (contractAddressToTraces[currentAddress] || []).concat( - currentTraceSegment, - ); - currentTraceSegment = []; - } else { - throw new Error('Malformed trace. Unexpected call depth change'); - } - } - } - } - if (addressStack.length !== 0) { - logUtils.warn('Malformed trace. Call stack non empty at the end'); - } - if (currentTraceSegment.length !== 0) { - const currentAddress = addressStack.pop() as string; - contractAddressToTraces[currentAddress] = (contractAddressToTraces[currentAddress] || []).concat( - currentTraceSegment, - ); - currentTraceSegment = []; - logUtils.warn('Malformed trace. Current trace segment non empty at the end'); - } - return contractAddressToTraces; -} diff --git a/packages/sol-tracing-utils/src/trace_collection_subprovider.ts b/packages/sol-tracing-utils/src/trace_collection_subprovider.ts deleted file mode 100644 index 0665fc2e3b..0000000000 --- a/packages/sol-tracing-utils/src/trace_collection_subprovider.ts +++ /dev/null @@ -1,219 +0,0 @@ -import { BlockchainLifecycle } from '@0x/dev-utils'; -import { Callback, ErrorCallback, NextCallback, Subprovider, Web3ProviderEngine } from '@0x/subproviders'; -import { logUtils } from '@0x/utils'; -import { CallDataRPC, marshaller, Web3Wrapper } from '@0x/web3-wrapper'; -import { JSONRPCRequestPayload, TxData } from 'ethereum-types'; -import { utils } from 'ethers'; -import * as _ from 'lodash'; -import { Lock } from 'semaphore-async-await'; - -import { constants } from './constants'; -import { BlockParamLiteral } from './types'; - -interface MaybeFakeTxData extends TxData { - isFakeTransaction?: boolean; -} - -const BLOCK_GAS_LIMIT = 6000000; - -export interface TraceCollectionSubproviderConfig { - shouldCollectTransactionTraces: boolean; - shouldCollectCallTraces: boolean; - shouldCollectGasEstimateTraces: boolean; -} - -type AsyncFunc = (...args: any[]) => Promise; - -// HACK: This wrapper outputs errors to console even if the promise gets ignored -// we need this because web3-provider-engine does not handle promises in -// the after function of next(after). -function logAsyncErrors(fn: AsyncFunc): AsyncFunc { - async function wrappedAsync(...args: any[]): Promise { - try { - await fn(...args); - } catch (err) { - logUtils.log(err); - throw err; - } - } - return wrappedAsync; -} - -// Because there is no notion of a call trace in the Ethereum rpc - we collect them in a rather non-obvious/hacky way. -// On each call - we create a snapshot, execute the call as a transaction, get the trace, revert the snapshot. -// That allows us to avoid influencing test behaviour. - -/** - * This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface. - * It collects traces of all transactions that were sent and all calls that were executed through JSON RPC. It must - * be extended by implementing the _recordTxTraceAsync method which is called for every transaction. - */ -export abstract class TraceCollectionSubprovider extends Subprovider { - protected _web3Wrapper!: Web3Wrapper; - // Lock is used to not accept normal transactions while doing call/snapshot magic because they'll be reverted later otherwise - private readonly _lock = new Lock(); - private readonly _defaultFromAddress: string; - private _isEnabled = true; - private readonly _config: TraceCollectionSubproviderConfig; - /** - * Instantiates a TraceCollectionSubprovider instance - * @param defaultFromAddress default from address to use when sending transactions - */ - constructor(defaultFromAddress: string, config: TraceCollectionSubproviderConfig) { - super(); - this._defaultFromAddress = defaultFromAddress; - this._config = config; - } - /** - * Starts trace collection - */ - public start(): void { - this._isEnabled = true; - } - /** - * Stops trace collection - */ - public stop(): void { - this._isEnabled = false; - } - /** - * This method conforms to the web3-provider-engine interface. - * It is called internally by the ProviderEngine when it is this subproviders - * turn to handle a JSON RPC request. - * @param payload JSON RPC payload - * @param next Callback to call if this subprovider decides not to handle the request - * @param _end Callback to call if subprovider handled the request and wants to pass back the request. - */ - // tslint:disable-next-line:prefer-function-over-method async-suffix - public async handleRequest(payload: JSONRPCRequestPayload, next: NextCallback, _end: ErrorCallback): Promise { - if (this._isEnabled) { - switch (payload.method) { - case 'eth_sendTransaction': - if (!this._config.shouldCollectTransactionTraces) { - next(); - } else { - const txData = payload.params[0]; - next(logAsyncErrors(this._onTransactionSentAsync.bind(this, txData))); - } - return; - - case 'eth_sendRawTransaction': - if (!this._config.shouldCollectTransactionTraces) { - next(); - } else { - const txData = utils.parseTransaction(payload.params[0]); - if (txData.to === null) { - txData.to = constants.NEW_CONTRACT; - } - next(logAsyncErrors(this._onTransactionSentAsync.bind(this, txData))); - } - return; - - case 'eth_call': - if (!this._config.shouldCollectCallTraces) { - next(); - } else { - const callData = payload.params[0]; - next(logAsyncErrors(this._onCallOrGasEstimateExecutedAsync.bind(this, callData))); - } - return; - - case 'eth_estimateGas': - if (!this._config.shouldCollectGasEstimateTraces) { - next(); - } else { - const estimateGasData = payload.params[0]; - next(logAsyncErrors(this._onCallOrGasEstimateExecutedAsync.bind(this, estimateGasData))); - } - return; - - default: - next(); - return; - } - } else { - next(); - return; - } - } - /** - * Set's the subprovider's engine to the ProviderEngine it is added to. - * This is only called within the ProviderEngine source code, do not call - * directly. - * @param engine The ProviderEngine this subprovider is added to - */ - public setEngine(engine: Web3ProviderEngine): void { - super.setEngine(engine); - this._web3Wrapper = new Web3Wrapper(engine); - } - protected abstract async _recordTxTraceAsync( - address: string, - data: string | undefined, - txHash: string, - ): Promise; - private async _onTransactionSentAsync( - txData: MaybeFakeTxData, - err: Error | null, - txHash: string | undefined, - cb: Callback, - ): Promise { - if (!(txData.isFakeTransaction || txData.from === txData.to)) { - // This transaction is a usual transaction. Not a call executed as one. - // And we don't want it to be executed within a snapshotting period - await this._lock.acquire(); - } - const NULL_ADDRESS = '0x0'; - if (err === null) { - const toAddress = - txData.to === undefined || txData.to === NULL_ADDRESS ? constants.NEW_CONTRACT : txData.to; - await this._recordTxTraceAsync(toAddress, txData.data, txHash as string); - } else { - const latestBlock = await this._web3Wrapper.getBlockWithTransactionDataAsync(BlockParamLiteral.Latest); - const transactions = latestBlock.transactions; - for (const transaction of transactions) { - const toAddress = - txData.to === undefined || txData.to === NULL_ADDRESS ? constants.NEW_CONTRACT : txData.to; - await this._recordTxTraceAsync(toAddress, transaction.input, transaction.hash); - } - } - if (!txData.isFakeTransaction) { - // This transaction is a usual transaction. Not a call executed as one. - // And we don't want it to be executed within a snapshotting period - this._lock.release(); - } - cb(); - } - private async _onCallOrGasEstimateExecutedAsync( - callData: Partial, - _err: Error | null, - _callResult: string, - cb: Callback, - ): Promise { - await this._recordCallOrGasEstimateTraceAsync(callData); - cb(); - } - private async _recordCallOrGasEstimateTraceAsync(callData: Partial): Promise { - // We don't want other transactions to be executed during snashotting period, that's why we lock the - // transaction execution for all transactions except our fake ones. - await this._lock.acquire(); - const blockchainLifecycle = new BlockchainLifecycle(this._web3Wrapper); - await blockchainLifecycle.startAsync(); - const fakeTxData = { - gas: `0x${BLOCK_GAS_LIMIT.toString(16)}`, // tslint:disable-line:custom-no-magic-numbers - isFakeTransaction: true, // This transaction (and only it) is allowed to come through when the lock is locked - ...callData, - from: callData.from || this._defaultFromAddress, - }; - try { - const txData = marshaller.unmarshalTxData(fakeTxData); - const txHash = await this._web3Wrapper.sendTransactionAsync(txData); - await this._web3Wrapper.awaitTransactionMinedAsync(txHash, 0); - } catch (err) { - // TODO(logvinov) Check that transaction failed and not some other exception - // Even if this transaction failed - we've already recorded it's trace. - _.noop(); - } - await blockchainLifecycle.revertAsync(); - this._lock.release(); - } -} diff --git a/packages/sol-tracing-utils/src/trace_collector.ts b/packages/sol-tracing-utils/src/trace_collector.ts deleted file mode 100644 index 68261de847..0000000000 --- a/packages/sol-tracing-utils/src/trace_collector.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { promisify } from '@0x/utils'; -import chalk from 'chalk'; -import { stripHexPrefix } from 'ethereumjs-util'; -import * as fs from 'fs'; -import { Collector } from 'istanbul'; -import * as _ from 'lodash'; -import { getLogger, levels, Logger } from 'loglevel'; -import * as mkdirp from 'mkdirp'; - -import { AbstractArtifactAdapter } from './artifact_adapters/abstract_artifact_adapter'; -import { constants } from './constants'; -import { parseSourceMap } from './source_maps'; -import { - ContractData, - Coverage, - SourceRange, - Subtrace, - SubTraceInfo, - SubTraceInfoExistingContract, - SubTraceInfoNewContract, -} from './types'; -import { utils } from './utils'; - -const mkdirpAsync = promisify(mkdirp); - -export type SingleFileSubtraceHandler = ( - contractData: ContractData, - subtrace: Subtrace, - pcToSourceRange: { [programCounter: number]: SourceRange }, - fileIndex: number, -) => Coverage; - -/** - * TraceCollector is used by CoverageSubprovider to compute code coverage based on collected trace data. - */ -export class TraceCollector { - private readonly _artifactAdapter: AbstractArtifactAdapter; - private readonly _logger: Logger; - private _contractsData!: ContractData[]; - private readonly _collector = new Collector(); - private readonly _singleFileSubtraceHandler: SingleFileSubtraceHandler; - - /** - * Instantiates a TraceCollector instance - * @param artifactAdapter Adapter for used artifacts format (0x, truffle, giveth, etc.) - * @param isVerbose If true, we will log any unknown transactions. Otherwise we will ignore them - * @param singleFileSubtraceHandler A handler function for computing partial coverage for a single file & subtrace - */ - constructor( - artifactAdapter: AbstractArtifactAdapter, - isVerbose: boolean, - singleFileSubtraceHandler: SingleFileSubtraceHandler, - ) { - this._artifactAdapter = artifactAdapter; - this._logger = getLogger('sol-tracing-utils'); - this._logger.setLevel(isVerbose ? levels.TRACE : levels.ERROR); - this._singleFileSubtraceHandler = singleFileSubtraceHandler; - } - public async writeOutputAsync(): Promise { - const finalCoverage: Coverage = this._collector.getFinalCoverage(); - const stringifiedCoverage = JSON.stringify(finalCoverage, null, '\t'); - await mkdirpAsync('coverage'); - fs.writeFileSync('coverage/coverage.json', stringifiedCoverage); - } - public async getContractDataByTraceInfoIfExistsAsync( - address: string, - bytecode: string, - isContractCreation: boolean, - ): Promise { - if (this._contractsData === undefined) { - this._contractsData = await this._artifactAdapter.collectContractsDataAsync(); - } - const contractData = utils.getContractDataIfExists(this._contractsData, bytecode); - if (contractData === undefined) { - /** - * Length chooses so that both error messages are of the same length - * and it's enough data to figure out which artifact has a problem. - */ - const HEX_LENGTH = 16; - const errMsg = isContractCreation - ? `Unable to find matching bytecode for contract creation ${chalk.bold( - utils.shortenHex(bytecode, HEX_LENGTH), - )}, please check your artifacts. Ignoring...` - : `Unable to find matching bytecode for contract address ${chalk.bold( - address, - )}, please check your artifacts. Ignoring...`; - this._logger.warn(errMsg); - } - return contractData; - } - public async computeSingleTraceCoverageAsync(subTraceInfo: SubTraceInfo): Promise { - const isContractCreation = subTraceInfo.address === constants.NEW_CONTRACT; - const bytecode = isContractCreation - ? (subTraceInfo as SubTraceInfoNewContract).bytecode - : (subTraceInfo as SubTraceInfoExistingContract).runtimeBytecode; - const contractData = await this.getContractDataByTraceInfoIfExistsAsync( - subTraceInfo.address, - bytecode, - isContractCreation, - ); - if (contractData === undefined) { - return; - } - const bytecodeHex = stripHexPrefix(bytecode); - const sourceMap = isContractCreation ? contractData.sourceMap : contractData.sourceMapRuntime; - const pcToSourceRange = parseSourceMap(contractData.sourceCodes, sourceMap, bytecodeHex, contractData.sources); - _.map(contractData.sources, (_sourcePath: string, fileIndex: string) => { - const singleFileCoverageForTrace = this._singleFileSubtraceHandler( - contractData, - subTraceInfo.subtrace, - pcToSourceRange, - _.parseInt(fileIndex), - ); - this._collector.add(singleFileCoverageForTrace); - }); - } -} diff --git a/packages/sol-tracing-utils/src/trace_info_subprovider.ts b/packages/sol-tracing-utils/src/trace_info_subprovider.ts deleted file mode 100644 index 18e73aaf19..0000000000 --- a/packages/sol-tracing-utils/src/trace_info_subprovider.ts +++ /dev/null @@ -1,129 +0,0 @@ -import { NodeType } from '@0x/web3-wrapper'; -import * as _ from 'lodash'; - -import { constants } from './constants'; -import { getContractAddressToTraces } from './trace'; -import { TraceCollectionSubprovider } from './trace_collection_subprovider'; -import { SubTraceInfo, SubTraceInfoExistingContract, SubTraceInfoNewContract, TraceInfo } from './types'; -import { utils } from './utils'; - -// TraceInfoSubprovider is extended by subproviders which need to work with one -// TraceInfo at a time. It has one abstract method: _handleTraceInfoAsync, which -// is called for each TraceInfo. -export abstract class TraceInfoSubprovider extends TraceCollectionSubprovider { - protected abstract _handleSubTraceInfoAsync(subTraceInfo: SubTraceInfo): Promise; - // tslint:disable prefer-function-over-method - protected async _handleTraceInfoAsync(_traceInfo: TraceInfo): Promise { - return Promise.resolve(undefined); - } - protected async _recordTxTraceAsync( - address: string, - dataIfExists: string | undefined, - txHash: string, - ): Promise { - await this._web3Wrapper.awaitTransactionMinedAsync(txHash, 0); - const nodeType = await this._web3Wrapper.getNodeTypeAsync(); - let trace; - if (nodeType === NodeType.Geth) { - // For very large traces we use a custom tracer that outputs a format compatible with a - // regular trace. We only need the 2nd item on the stack when the instruction is a call. - // By not including other stack values, we drastically limit the amount of data to be collected. - // There are no good docs about how to write those tracers, but you can find some example ones here: - // https://github.com/ethereum/go-ethereum/tree/master/eth/tracers/internal/tracers - const tracer = ` - { - data: [], - extractStack: function (stack) { - var extract = []; - for (var i = 0; i < stack.length(); i++) { - extract.push('0x' + stack.peek(i).toString(16)); - } - return extract; - }, - step: function(log) { - const op = log.op.toString(); - const opn = 0 | log.op.toNumber(); - const pc = 0 | log.getPC(); - const depth = 0 | log.getDepth(); - const gasCost = 0 | log.getCost(); - const gas = 0 | log.getGas(); - const isCall = opn == 0xf1 || opn == 0xf2 || opn == 0xf4 || opn == 0xf5 || opn == 0xfa; - const isMemoryAccess = opn == 0x51 || opn == 0x52 || opn == 0x53; - const isCallDataAccess = opn == 0x37; - var stack; - if (isCall) { - stack = ['0x'+log.stack.peek(1).toString(16), null]; - } else if (isMemoryAccess) { - stack = ['0x'+log.stack.peek(0).toString(16)]; - } else if (isCallDataAccess) { - stack = ['0x'+log.stack.peek(2).toString(16), '0x'+log.stack.peek(1).toString(16), '0x'+log.stack.peek(0).toString(16)]; - } - this.data.push({ pc, gasCost, depth, op, stack, gas }); - }, - fault: function() { }, - result: function() { return {structLogs: this.data}; } - } - `; - trace = await this._web3Wrapper.getTransactionTraceAsync(txHash, { tracer, timeout: '600s' }); - } else { - /** - * Ganache doesn't support custom tracers yet. - */ - trace = await this._web3Wrapper.getTransactionTraceAsync(txHash, { - disableMemory: true, - disableStack: false, - disableStorage: true, - }); - } - trace.structLogs = utils.normalizeStructLogs(trace.structLogs); - const traceInfo = { - trace, - address, - dataIfExists, - txHash, - }; - await this._handleTraceInfoAsync(traceInfo); - const contractAddressToTraces = getContractAddressToTraces(trace.structLogs, address); - const subcallAddresses = _.keys(contractAddressToTraces); - if (address === constants.NEW_CONTRACT) { - for (const subcallAddress of subcallAddresses) { - let subTraceInfo: SubTraceInfoNewContract | SubTraceInfoExistingContract; - const traceForThatSubcall = contractAddressToTraces[subcallAddress]; - const subcallDepth = traceForThatSubcall[0].depth; - if (subcallAddress === 'NEW_CONTRACT') { - subTraceInfo = { - subcallDepth, - subtrace: traceForThatSubcall, - txHash, - address: subcallAddress, - bytecode: dataIfExists as string, - }; - } else { - const runtimeBytecode = await this._web3Wrapper.getContractCodeAsync(subcallAddress); - subTraceInfo = { - subcallDepth, - subtrace: traceForThatSubcall, - txHash, - address: subcallAddress, - runtimeBytecode, - }; - } - await this._handleSubTraceInfoAsync(subTraceInfo); - } - } else { - for (const subcallAddress of subcallAddresses) { - const runtimeBytecode = await this._web3Wrapper.getContractCodeAsync(subcallAddress); - const traceForThatSubcall = contractAddressToTraces[subcallAddress]; - const subcallDepth = traceForThatSubcall[0].depth; - const subTraceInfo: SubTraceInfoExistingContract = { - subcallDepth, - subtrace: traceForThatSubcall, - txHash, - address: subcallAddress, - runtimeBytecode, - }; - await this._handleSubTraceInfoAsync(subTraceInfo); - } - } - } -} diff --git a/packages/sol-tracing-utils/src/types.ts b/packages/sol-tracing-utils/src/types.ts deleted file mode 100644 index 6dac77a27a..0000000000 --- a/packages/sol-tracing-utils/src/types.ts +++ /dev/null @@ -1,148 +0,0 @@ -import { StructLog, TransactionTrace } from 'ethereum-types'; - -export interface LineColumn { - line: number; - column: number; -} - -export interface SourceRange { - location: SingleFileSourceRange; - fileName: string; -} - -export interface SingleFileSourceRange { - start: LineColumn; - end: LineColumn; -} - -export interface OffsetToLocation { - [offset: number]: LineColumn; -} - -export interface FunctionDescription { - name: string; - line: number; - loc: SingleFileSourceRange; - skip?: boolean; -} - -export type StatementDescription = SingleFileSourceRange; - -export interface BranchDescription { - line: number; - type: 'if' | 'switch' | 'cond-expr' | 'binary-expr'; - locations: SingleFileSourceRange[]; -} - -export interface FnMap { - [functionId: string]: FunctionDescription; -} - -export interface BranchMap { - [branchId: string]: BranchDescription; -} - -export interface StatementMap { - [statementId: string]: StatementDescription; -} - -export interface LineCoverage { - [lineNo: number]: number; -} - -export interface FunctionCoverage { - [functionId: string]: number; -} - -export interface StatementCoverage { - [statementId: string]: number; -} - -export interface BranchCoverage { - [branchId: string]: number[]; -} - -export interface Coverage { - [fineName: string]: { - l?: LineCoverage; - f: FunctionCoverage; - s: StatementCoverage; - b: BranchCoverage; - fnMap: FnMap; - branchMap: BranchMap; - statementMap: StatementMap; - path: string; - }; -} - -export interface SourceCodes { - [sourceId: number]: string; -} -export interface Sources { - [sourceId: number]: string; -} - -export interface ContractData { - name: string; - bytecode: string; - sourceMap: string; - runtimeBytecode: string; - sourceMapRuntime: string; - sourceCodes: SourceCodes; - sources: Sources; -} - -// Part of the trace executed within the same context -export type Subtrace = StructLog[]; - -export interface SubTraceInfoBase { - subtrace: Subtrace; - txHash: string; - subcallDepth: number; -} - -export interface SubTraceInfoNewContract extends SubTraceInfoBase { - address: 'NEW_CONTRACT'; - bytecode: string; -} - -export interface SubTraceInfoExistingContract extends SubTraceInfoBase { - address: string; - runtimeBytecode: string; -} - -export type SubTraceInfo = SubTraceInfoNewContract | SubTraceInfoExistingContract; - -export interface TraceInfo { - trace: TransactionTrace; - txHash: string; - address: string; - dataIfExists: string | undefined; -} - -export enum BlockParamLiteral { - Latest = 'latest', -} - -export interface EvmCallStackEntry { - structLog: StructLog; - address: string; -} - -export type EvmCallStack = EvmCallStackEntry[]; - -export interface SourceSnippet { - source: string; - fileName: string; - range: SingleFileSourceRange; -} - -export interface OpCodeToParamToStackOffset { - [opCode: string]: { - [param: string]: number; - }; -} - -export interface OpCodeToGasCost { - [opCode: string]: number; -} diff --git a/packages/sol-tracing-utils/src/utils.ts b/packages/sol-tracing-utils/src/utils.ts deleted file mode 100644 index b1c793a01e..0000000000 --- a/packages/sol-tracing-utils/src/utils.ts +++ /dev/null @@ -1,159 +0,0 @@ -import { addressUtils, BigNumber, logUtils } from '@0x/utils'; -import { OpCode, StructLog } from 'ethereum-types'; -import { addHexPrefix } from 'ethereumjs-util'; -import * as _ from 'lodash'; - -import { constants } from './constants'; -import { ContractData, LineColumn, SingleFileSourceRange } from './types'; - -const bytecodeToContractDataIfExists: { [bytecode: string]: ContractData | undefined } = {}; - -export const utils = { - compareLineColumn(lhs: LineColumn, rhs: LineColumn): number { - return lhs.line !== rhs.line ? lhs.line - rhs.line : lhs.column - rhs.column; - }, - removeHexPrefix(hex: string): string { - const hexPrefix = '0x'; - return hex.startsWith(hexPrefix) ? hex.slice(hexPrefix.length) : hex; - }, - isRangeInside(childRange: SingleFileSourceRange, parentRange: SingleFileSourceRange): boolean { - return ( - utils.compareLineColumn(parentRange.start, childRange.start) <= 0 && - utils.compareLineColumn(childRange.end, parentRange.end) <= 0 - ); - }, - isRangeEqual(childRange: SingleFileSourceRange, parentRange: SingleFileSourceRange): boolean { - return ( - utils.compareLineColumn(parentRange.start, childRange.start) === 0 && - utils.compareLineColumn(childRange.end, parentRange.end) === 0 - ); - }, - bytecodeToBytecodeRegex(bytecode: string): string { - const bytecodeRegex = bytecode - // Library linking placeholder: __ConvertLib____________________________ - .replace(/_.*_/, '.*') - // Last 86 characters is solidity compiler metadata that's different between compilations - .replace(/.{86}$/, '') - // Libraries contain their own address at the beginning of the code and it's impossible to know it in advance - .replace(/^0x730000000000000000000000000000000000000000/, '0x73........................................'); - // HACK: Node regexes can't be longer that 32767 characters. Contracts bytecode can. We just truncate the regexes. It's safe in practice. - const MAX_REGEX_LENGTH = 32767; - const truncatedBytecodeRegex = bytecodeRegex.slice(0, MAX_REGEX_LENGTH); - return truncatedBytecodeRegex; - }, - getContractDataIfExists(contractsData: ContractData[], bytecode: string): ContractData | undefined { - if (!bytecode.startsWith('0x')) { - throw new Error(`0x hex prefix missing: ${bytecode}`); - } - // HACK(leo): We want to cache the values that are possibly undefined. - // That's why we can't check for undefined as we usually do, but need to use `hasOwnProperty`. - if (bytecodeToContractDataIfExists.hasOwnProperty(bytecode)) { - return bytecodeToContractDataIfExists[bytecode]; - } - const contractDataCandidates = _.filter(contractsData, contractDataCandidate => { - const bytecodeRegex = utils.bytecodeToBytecodeRegex(contractDataCandidate.bytecode); - const runtimeBytecodeRegex = utils.bytecodeToBytecodeRegex(contractDataCandidate.runtimeBytecode); - // We use that function to find by bytecode or runtimeBytecode. Those are quasi-random strings so - // collisions are practically impossible and it allows us to reuse that code - return bytecode.match(bytecodeRegex) !== null || bytecode.match(runtimeBytecodeRegex) !== null; - }); - if (contractDataCandidates.length > 1) { - const candidates = contractDataCandidates.map( - contractDataCandidate => _.values(contractDataCandidate.sources)[0], - ); - const errMsg = - "We've found more than one artifact that contains the exact same bytecode and therefore are unable to detect which contract was executed. " + - "We'll be assigning all traces to the first one."; - logUtils.warn(errMsg); - logUtils.warn(candidates); - } - return (bytecodeToContractDataIfExists[bytecode] = contractDataCandidates[0]); - }, - isCallLike(op: OpCode): boolean { - return _.includes([OpCode.CallCode, OpCode.StaticCall, OpCode.Call, OpCode.DelegateCall], op); - }, - isEndOpcode(op: OpCode): boolean { - return _.includes([OpCode.Return, OpCode.Stop, OpCode.Revert, OpCode.Invalid, OpCode.SelfDestruct], op); - }, - getAddressFromStackEntry(stackEntry: string): string { - const hexBase = 16; - return addressUtils.padZeros(new BigNumber(addHexPrefix(stackEntry)).toString(hexBase)); - }, - normalizeStructLogs(structLogs: StructLog[]): StructLog[] { - if (_.isEmpty(structLogs)) { - return structLogs; - } - const reduceDepthBy1 = (structLog: StructLog) => ({ - ...structLog, - depth: structLog.depth - 1, - }); - let normalizedStructLogs = structLogs; - // HACK(leo): Geth traces sometimes returns those gas costs incorrectly as very big numbers so we manually fix them. - const normalizeStaticCallCost = (structLog: StructLog) => - structLog.op === OpCode.StaticCall - ? { - ...structLog, - gasCost: constants.opCodeToGasCost[structLog.op], - } - : structLog; - // HACK(leo): Geth traces sometimes returns those gas costs incorrectly as very big numbers so we manually fix them. - const normalizeCallCost = (structLog: StructLog, index: number) => { - if (structLog.op === OpCode.Call) { - const callAddress = parseInt( - structLog.stack[structLog.stack.length - constants.opCodeToParamToStackOffset[OpCode.Call].to - 1], - constants.HEX_BASE, - ); - const MAX_REASONABLE_PRECOMPILE_ADDRESS = 100; - if (callAddress < MAX_REASONABLE_PRECOMPILE_ADDRESS) { - const nextStructLog = normalizedStructLogs[index + 1]; - const gasCost = structLog.gas - nextStructLog.gas; - return { - ...structLog, - gasCost, - }; - } else { - return { - ...structLog, - gasCost: constants.opCodeToGasCost[structLog.op], - }; - } - } else { - return structLog; - } - }; - const shiftGasCosts1Left = (structLog: StructLog, idx: number) => { - if (idx === structLogs.length - 1) { - return { - ...structLog, - gasCost: 0, - }; - } else { - const nextStructLog = structLogs[idx + 1]; - const gasCost = nextStructLog.gasCost; - return { - ...structLog, - gasCost, - }; - } - }; - if (structLogs[0].depth === 1) { - // Geth uses 1-indexed depth counter whilst ganache starts from 0 - normalizedStructLogs = _.map(normalizedStructLogs, reduceDepthBy1); - normalizedStructLogs = _.map(normalizedStructLogs, normalizeCallCost); - normalizedStructLogs = _.map(normalizedStructLogs, normalizeStaticCallCost); - } else { - // Ganache shifts opcodes gas costs so we need to unshift them - normalizedStructLogs = _.map(normalizedStructLogs, shiftGasCosts1Left); - } - return normalizedStructLogs; - }, - getRange(sourceCode: string, range: SingleFileSourceRange): string { - const lines = sourceCode.split('\n').slice(range.start.line - 1, range.end.line); - lines[lines.length - 1] = lines[lines.length - 1].slice(0, range.end.column); - lines[0] = lines[0].slice(range.start.column); - return lines.join('\n'); - }, - shortenHex(hex: string, length: number): string { - return `${hex.substr(0, length + 2)}...${hex.substr(hex.length - length, length)}`; - }, -}; diff --git a/packages/sol-tracing-utils/test/collect_coverage_entries_test.ts b/packages/sol-tracing-utils/test/collect_coverage_entries_test.ts deleted file mode 100644 index d3ca8930c6..0000000000 --- a/packages/sol-tracing-utils/test/collect_coverage_entries_test.ts +++ /dev/null @@ -1,156 +0,0 @@ -import * as chai from 'chai'; -import * as fs from 'fs'; -import * as _ from 'lodash'; -import 'mocha'; -import * as path from 'path'; - -import { collectCoverageEntries } from '../src/collect_coverage_entries'; -import { utils } from '../src/utils'; - -const expect = chai.expect; - -describe('Collect coverage entries', () => { - describe('#collectCoverageEntries', () => { - it('correctly collects coverage entries for Simplest contract', () => { - const simplestContractBaseName = 'Simplest.sol'; - const simplestContractFileName = path.resolve(__dirname, 'fixtures/contracts', simplestContractBaseName); - const simplestContract = fs.readFileSync(simplestContractFileName).toString(); - const coverageEntries = collectCoverageEntries(simplestContract); - expect(coverageEntries.fnMap).to.be.deep.equal({}); - expect(coverageEntries.branchMap).to.be.deep.equal({}); - expect(coverageEntries.statementMap).to.be.deep.equal({}); - expect(coverageEntries.modifiersStatementIds).to.be.deep.equal([]); - }); - it('correctly collects coverage entries for SimpleStorage contract', () => { - const simpleStorageContractBaseName = 'SimpleStorage.sol'; - const simpleStorageContractFileName = path.resolve( - __dirname, - 'fixtures/contracts', - simpleStorageContractBaseName, - ); - const simpleStorageContract = fs.readFileSync(simpleStorageContractFileName).toString(); - const coverageEntries = collectCoverageEntries(simpleStorageContract); - const fnIds = _.keys(coverageEntries.fnMap); - expect(coverageEntries.fnMap[fnIds[0]].name).to.be.equal('set'); - // tslint:disable-next-line:custom-no-magic-numbers - expect(coverageEntries.fnMap[fnIds[0]].line).to.be.equal(5); - const setFunction = `function set(uint x) { - storedData = x; - }`; - expect(utils.getRange(simpleStorageContract, coverageEntries.fnMap[fnIds[0]].loc)).to.be.equal(setFunction); - expect(coverageEntries.fnMap[fnIds[1]].name).to.be.equal('get'); - // tslint:disable-next-line:custom-no-magic-numbers - expect(coverageEntries.fnMap[fnIds[1]].line).to.be.equal(8); - const getFunction = `function get() constant returns (uint retVal) { - return storedData; - }`; - expect(utils.getRange(simpleStorageContract, coverageEntries.fnMap[fnIds[1]].loc)).to.be.equal(getFunction); - expect(coverageEntries.branchMap).to.be.deep.equal({}); - const statementIds = _.keys(coverageEntries.statementMap); - expect(utils.getRange(simpleStorageContract, coverageEntries.statementMap[statementIds[1]])).to.be.equal( - 'storedData = x', - ); - expect(utils.getRange(simpleStorageContract, coverageEntries.statementMap[statementIds[3]])).to.be.equal( - 'return storedData;', - ); - expect(coverageEntries.modifiersStatementIds).to.be.deep.equal([]); - }); - it('correctly collects coverage entries for AllSolidityFeatures contract', () => { - const simpleStorageContractBaseName = 'AllSolidityFeatures.sol'; - const simpleStorageContractFileName = path.resolve( - __dirname, - 'fixtures/contracts', - simpleStorageContractBaseName, - ); - const simpleStorageContract = fs.readFileSync(simpleStorageContractFileName).toString(); - const coverageEntries = collectCoverageEntries(simpleStorageContract); - const fnDescriptions = _.values(coverageEntries.fnMap); - const fnNames = _.map(fnDescriptions, fnDescription => fnDescription.name); - const expectedFnNames = [ - 'f', - 'c', - 'test', - 'getChoice', - 'Base', - 'Derived', - 'f', - 'f', - '', - 'g', - 'setData', - 'getData', - 'sendHalf', - 'insert', - 'remove', - 'contains', - 'iterate_start', - 'iterate_valid', - 'iterate_advance', - 'iterate_get', - 'insert', - 'sum', - 'restricted', - 'DualIndex', - 'set', - 'transfer_ownership', - 'lookup', - '', - '', - 'sum', - 'someFunction', - 'fun', - 'at', - 'test', - 'get', - 'returnNumber', - 'alloc', - 'ham', - 'getMyTuple', - 'ham', - 'abstain', - 'foobar', - 'foobar', - 'a', - ]; - expect(fnNames).to.be.deep.equal(expectedFnNames); - - const branchDescriptions = _.values(coverageEntries.branchMap); - const branchLines = _.map(branchDescriptions, branchDescription => branchDescription.line); - // tslint:disable-next-line:custom-no-magic-numbers - expect(branchLines).to.be.deep.equal([94, 115, 119, 130, 151, 187]); - const branchTypes = _.map(branchDescriptions, branchDescription => branchDescription.type); - expect(branchTypes).to.be.deep.equal(['if', 'if', 'if', 'if', 'binary-expr', 'if']); - }); - - it('correctly ignores all coverage entries for Ignore contract', () => { - const solcovIgnoreContractBaseName = 'SolcovIgnore.sol'; - const solcovIgnoreContractFileName = path.resolve( - __dirname, - 'fixtures/contracts', - solcovIgnoreContractBaseName, - ); - const solcovIgnoreContract = fs.readFileSync(solcovIgnoreContractFileName).toString(); - const IGNORE_REGEXP = /\/\*\s*solcov\s+ignore\s+next\s*\*\/\s*/gm; - const coverageEntries = collectCoverageEntries(solcovIgnoreContract, IGNORE_REGEXP); - const fnIds = _.keys(coverageEntries.fnMap); - - expect(fnIds.length).to.be.equal(1); - expect(coverageEntries.fnMap[fnIds[0]].name).to.be.equal('set'); - // tslint:disable-next-line:custom-no-magic-numbers - expect(coverageEntries.fnMap[fnIds[0]].line).to.be.equal(6); - const setFunction = `function set(uint x) public { - /* solcov ignore next */ - storedData = x; - }`; - expect(utils.getRange(solcovIgnoreContract, coverageEntries.fnMap[fnIds[0]].loc)).to.be.equal(setFunction); - - expect(coverageEntries.branchMap).to.be.deep.equal({}); - const statementIds = _.keys(coverageEntries.statementMap); - expect(utils.getRange(solcovIgnoreContract, coverageEntries.statementMap[statementIds[0]])).to.be.equal( - setFunction, - ); - expect(statementIds.length).to.be.equal(1); - expect(coverageEntries.modifiersStatementIds.length).to.be.equal(0); - }); - }); -}); diff --git a/packages/sol-tracing-utils/test/fixtures/contracts/AllSolidityFeatures.sol b/packages/sol-tracing-utils/test/fixtures/contracts/AllSolidityFeatures.sol deleted file mode 100644 index 21137347ea..0000000000 --- a/packages/sol-tracing-utils/test/fixtures/contracts/AllSolidityFeatures.sol +++ /dev/null @@ -1,413 +0,0 @@ -// Examples taken from the Solidity documentation online. - -// for pragma version numbers, see https://docs.npmjs.com/misc/semver#versions -pragma solidity 0.4.0; -pragma solidity ^0.4.0; - -import "SomeFile.sol"; -import "SomeFile.sol" as SomeOtherFile; -import * as SomeSymbol from "AnotherFile.sol"; -import {symbol1 as alias, symbol2} from "File.sol"; - -interface i { - function f(); -} - -contract c { - function c() - { - val1 = 1 wei; // 1 - val2 = 1 szabo; // 1 * 10 ** 12 - val3 = 1 finney; // 1 * 10 ** 15 - val4 = 1 ether; // 1 * 10 ** 18 - } - uint256 val1; - uint256 val2; - uint256 val3; - uint256 val4; -} - -contract test { - enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } - - function test() - { - choices = ActionChoices.GoStraight; - } - function getChoice() returns (uint d) - { - d = uint256(choices); - } - ActionChoices choices; -} - -contract Base { - function Base(uint i) - { - m_i = i; - } - uint public m_i; -} -contract Derived is Base(0) { - function Derived(uint i) Base(i) {} -} - -contract C { - uint248 x; // 31 bytes: slot 0, offset 0 - uint16 y; // 2 bytes: slot 1, offset 0 (does not fit in slot 0) - uint240 z; // 30 bytes: slot 1, offset 2 bytes - uint8 a; // 1 byte: slot 2, offset 0 bytes - struct S { - uint8 a; // 1 byte, slot +0, offset 0 bytes - uint256 b; // 32 bytes, slot +1, offset 0 bytes (does not fit) - } - S structData; // 2 slots, slot 3, offset 0 bytes (does not really apply) - uint8 alpha; // 1 byte, slot 4 (start new slot after struct) - uint16[3] beta; // 3*16 bytes, slots 5+6 (start new slot for array) - uint8 gamma; // 1 byte, slot 7 (start new slot after array) -} - -contract test { - function f(uint x, uint y) returns (uint z) { - var c = x + 3; - var b = 7 + (c * (8 - 7)) - x; - return -(-b | 0); - } -} - -contract test { - function f(uint x, uint y) returns (uint z) { - return 10; - } -} - -contract c { - function () returns (uint) { return g(8); } - function g(uint pos) internal returns (uint) { setData(pos, 8); return getData(pos); } - function setData(uint pos, uint value) internal { data[pos] = value; } - function getData(uint pos) internal { return data[pos]; } - mapping(uint => uint) data; -} - -contract Sharer { - function sendHalf(address addr) returns (uint balance) { - if (!addr.send(msg.value/2)) - throw; // also reverts the transfer to Sharer - return address(this).balance; - } -} - -/// @dev Models a modifiable and iterable set of uint values. -library IntegerSet -{ - struct data - { - /// Mapping item => index (or zero if not present) - mapping(uint => uint) index; - /// Items by index (index 0 is invalid), items with index[item] == 0 are invalid. - uint[] items; - /// Number of stored items. - uint size; - } - function insert(data storage self, uint value) returns (bool alreadyPresent) - { - uint index = self.index[value]; - if (index > 0) - return true; - else - { - if (self.items.length == 0) self.items.length = 1; - index = self.items.length++; - self.items[index] = value; - self.index[value] = index; - self.size++; - return false; - } - } - function remove(data storage self, uint value) returns (bool success) - { - uint index = self.index[value]; - if (index == 0) - return false; - delete self.index[value]; - delete self.items[index]; - self.size --; - } - function contains(data storage self, uint value) returns (bool) - { - return self.index[value] > 0; - } - function iterate_start(data storage self) returns (uint index) - { - return iterate_advance(self, 0); - } - function iterate_valid(data storage self, uint index) returns (bool) - { - return index < self.items.length; - } - function iterate_advance(data storage self, uint index) returns (uint r_index) - { - index++; - while (iterate_valid(self, index) && self.index[self.items[index]] == index) - index++; - return index; - } - function iterate_get(data storage self, uint index) returns (uint value) - { - return self.items[index]; - } -} - -/// How to use it: -contract User -{ - /// Just a struct holding our data. - IntegerSet.data data; - /// Insert something - function insert(uint v) returns (uint size) - { - /// Sends `data` via reference, so IntegerSet can modify it. - IntegerSet.insert(data, v); - /// We can access members of the struct - but we should take care not to mess with them. - return data.size; - } - /// Computes the sum of all stored data. - function sum() returns (uint s) - { - for (var i = IntegerSet.iterate_start(data); IntegerSet.iterate_valid(data, i); i = IntegerSet.iterate_advance(data, i)) - s += IntegerSet.iterate_get(data, i); - } -} - -// This broke it at one point (namely the modifiers). -contract DualIndex { - mapping(uint => mapping(uint => uint)) data; - address public admin; - - modifier restricted { if (msg.sender == admin) _; } - - function DualIndex() { - admin = msg.sender; - } - - function set(uint key1, uint key2, uint value) restricted { - uint[2][4] memory defaults; // "memory" broke things at one time. - data[key1][key2] = value; - } - - function transfer_ownership(address _admin) restricted { - admin = _admin; - } - - function lookup(uint key1, uint key2) returns(uint) { - return data[key1][key2]; - } -} - -contract A { - -} - -contract B { - -} - -contract C is A, B { - -} - -contract TestPrivate -{ - uint private value; -} - -contract TestInternal -{ - uint internal value; -} - -contract FromSolparse is A, B, TestPrivate, TestInternal { - function() { - uint a = 6 ** 9; - var (x) = 100; - uint y = 2 days; - } -} - -contract CommentedOutFunction { - // FYI: This empty function, as well as the commented - // out function below (bad code) is important to this test. - function() { - - } - - // function something() - // uint x = 10; - // } -} - -library VarHasBrackets { - string constant specialRight = "}"; - //string storage specialLeft = "{"; -} - -library UsingExampleLibrary { - function sum(uint[] storage self) returns (uint s) { - for (uint i = 0; i < self.length; i++) - s += self[i]; - } -} - -contract UsingExampleContract { - using UsingExampleLibrary for uint[]; -} - -contract NewStuff { - uint[] b; - - function someFunction() payable { - string storage a = hex"ab1248fe"; - b[2+2]; - } -} - -// modifier with expression -contract MyContract { - function fun() mymodifier(foo.bar()) {} -} - -library GetCode { - function at(address _addr) returns (bytes o_code) { - assembly { - // retrieve the size of the code, this needs assembly - let size := extcodesize(_addr) - // allocate output byte array - this could also be done without assembly - // by using o_code = new bytes(size) - o_code := mload(0x40) - // new "memory end" including padding - mstore(0x40, add(o_code, and(add(add(size, 0x20), 0x1f), not(0x1f)))) - // store length in memory - mstore(o_code, size) - // actually retrieve the code, this needs assembly - extcodecopy(_addr, add(o_code, 0x20), 0, size) - } - } -} - -contract assemblyLocalBinding { - function test(){ - assembly { - let v := 1 - let x := 0x00 - let y := x - let z := "hello" - } - } -} - -contract assemblyReturn { - uint a = 10; - - function get() constant returns(uint) { - assembly { - mstore(0x40, sload(0)) - byte(0) - address(0) - return(0x40,32) - } - } -} - -contract usesConst { - uint const = 0; -} - -contract memoryArrays { - uint seven = 7; - - function returnNumber(uint number) returns (uint){ - return number; - } - - function alloc() { - uint[] memory a = new uint[](7); - uint[] memory b = new uint[](returnNumber(seven)); - } -} - -contract DeclarativeExpressions { - uint a; - uint b = 7; - uint b2=0; - uint public c; - uint constant public d; - uint public constant e; - uint private constant f = 7; - struct S { uint q;} - - function ham(S storage s1, uint[] storage arr) internal { - uint x; - uint y = 7; - S storage s2 = s1; - uint[] memory stor; - uint[] storage stor2 = arr; - } -} - -contract VariableDeclarationTuple { - function getMyTuple() returns (bool, bool){ - return (true, false); - } - - function ham (){ - var (x, y) = (10, 20); - var (a, b) = getMyTuple(); - var (,c) = (10, 20); - var (d,,) = (10, 20, 30); - var (,e,,f,) = (10, 20, 30, 40, 50); - - var ( - num1, num2, - num3, ,num5 - ) = (10, 20, 30, 40, 50); - } -} - -contract TypeIndexSpacing { - uint [ 7 ] x; - uint [] y; -} - -contract Ballot { - - struct Voter { - uint weight; - bool voted; - } - - function abstain() returns (bool) { - return false; - } - - function foobar() payable owner (myPrice) returns (uint[], address myAdd, string[] names) {} - function foobar() payable owner (myPrice) returns (uint[], address myAdd, string[] names); - - Voter you = Voter(1, true); - - Voter me = Voter({ - weight: 2, - voted: abstain() - }); - - Voter airbnb = Voter({ - weight: 2, - voted: true, - }); -} - -contract multilineReturn { - function a() returns (uint x) { - return - 5; - } -} diff --git a/packages/sol-tracing-utils/test/fixtures/contracts/SimpleStorage.sol b/packages/sol-tracing-utils/test/fixtures/contracts/SimpleStorage.sol deleted file mode 100644 index e4b4ac2462..0000000000 --- a/packages/sol-tracing-utils/test/fixtures/contracts/SimpleStorage.sol +++ /dev/null @@ -1,11 +0,0 @@ -pragma solidity ^0.4.21; - -contract SimpleStorage { - uint public storedData; - function set(uint x) { - storedData = x; - } - function get() constant returns (uint retVal) { - return storedData; - } -} diff --git a/packages/sol-tracing-utils/test/fixtures/contracts/Simplest.sol b/packages/sol-tracing-utils/test/fixtures/contracts/Simplest.sol deleted file mode 100644 index d71016e072..0000000000 --- a/packages/sol-tracing-utils/test/fixtures/contracts/Simplest.sol +++ /dev/null @@ -1,2 +0,0 @@ -contract Simplest { -} diff --git a/packages/sol-tracing-utils/test/fixtures/contracts/SolcovIgnore.sol b/packages/sol-tracing-utils/test/fixtures/contracts/SolcovIgnore.sol deleted file mode 100644 index a7977ffb4d..0000000000 --- a/packages/sol-tracing-utils/test/fixtures/contracts/SolcovIgnore.sol +++ /dev/null @@ -1,22 +0,0 @@ -pragma solidity ^0.4.21; - -contract SolcovIgnore { - uint public storedData; - - function set(uint x) public { - /* solcov ignore next */ - storedData = x; - } - - /* solcov ignore next */ - function get() constant public returns (uint retVal) { - return storedData; - } -} - -/* solcov ignore next */ -contract Ignore { - function ignored() public returns (bool) { - return false; - } -} diff --git a/packages/sol-tracing-utils/test/instructions_test.ts b/packages/sol-tracing-utils/test/instructions_test.ts deleted file mode 100644 index 058053cf91..0000000000 --- a/packages/sol-tracing-utils/test/instructions_test.ts +++ /dev/null @@ -1,19 +0,0 @@ -import * as chai from 'chai'; -import 'mocha'; - -import { constants } from '../src/constants'; -import { getPcToInstructionIndexMapping } from '../src/instructions'; - -const expect = chai.expect; - -describe('instructions', () => { - describe('#getPcToInstructionIndexMapping', () => { - it('correctly maps pcs to instruction indexed', () => { - // tslint:disable-next-line:custom-no-magic-numbers - const bytecode = new Uint8Array([constants.PUSH1, 42, constants.PUSH2, 1, 2, constants.TIMESTAMP]); - const pcToInstruction = getPcToInstructionIndexMapping(bytecode); - const expectedPcToInstruction = { '0': 0, '2': 1, '5': 2 }; - expect(pcToInstruction).to.be.deep.equal(expectedPcToInstruction); - }); - }); -}); diff --git a/packages/sol-tracing-utils/test/sol_compiler_artifact_adapter_test.ts b/packages/sol-tracing-utils/test/sol_compiler_artifact_adapter_test.ts deleted file mode 100644 index 07d3bf84b6..0000000000 --- a/packages/sol-tracing-utils/test/sol_compiler_artifact_adapter_test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import * as chai from 'chai'; -import * as _ from 'lodash'; -import 'mocha'; -import * as path from 'path'; - -import { SolCompilerArtifactAdapter } from '../src/artifact_adapters/sol_compiler_artifact_adapter'; - -const expect = chai.expect; - -describe('SolCompilerArtifactAdapter', () => { - describe('#collectContractsData', () => { - it('correctly collects contracts data', async () => { - const artifactsPath = path.resolve(__dirname, 'fixtures/artifacts'); - const sourcesPath = path.resolve(__dirname, 'fixtures/contracts'); - const zeroExArtifactsAdapter = new SolCompilerArtifactAdapter(artifactsPath, sourcesPath); - const contractsData = await zeroExArtifactsAdapter.collectContractsDataAsync(); - _.forEach(contractsData, contractData => { - expect(contractData).to.have.keys([ - 'name', - 'sourceCodes', - 'sources', - 'sourceMap', - 'sourceMapRuntime', - 'bytecode', - 'runtimeBytecode', - ]); - }); - }); - }); -}); diff --git a/packages/sol-tracing-utils/test/source_maps_test.ts b/packages/sol-tracing-utils/test/source_maps_test.ts deleted file mode 100644 index b874ea4374..0000000000 --- a/packages/sol-tracing-utils/test/source_maps_test.ts +++ /dev/null @@ -1,71 +0,0 @@ -import * as chai from 'chai'; -import * as fs from 'fs'; -import * as _ from 'lodash'; -import 'mocha'; -import * as path from 'path'; - -import { getOffsetToLocation, parseSourceMap } from '../src/source_maps'; - -const expect = chai.expect; - -const simplestContractBaseName = 'Simplest.sol'; -const simplestContractFileName = path.resolve(__dirname, 'fixtures/contracts', simplestContractBaseName); -const simplestContract = fs.readFileSync(simplestContractFileName).toString(); - -describe('source maps', () => { - describe('#getLocationByOffset', () => { - it('correctly computes location by offset', () => { - const offsetToLocation = getOffsetToLocation(simplestContract); - const expectedLocationByOffset = { - '0': { line: 1, column: 0 }, - '1': { line: 1, column: 1 }, - '2': { line: 1, column: 2 }, - '3': { line: 1, column: 3 }, - '4': { line: 1, column: 4 }, - '5': { line: 1, column: 5 }, - '6': { line: 1, column: 6 }, - '7': { line: 1, column: 7 }, - '8': { line: 1, column: 8 }, - '9': { line: 1, column: 9 }, - '10': { line: 1, column: 10 }, - '11': { line: 1, column: 11 }, - '12': { line: 1, column: 12 }, - '13': { line: 1, column: 13 }, - '14': { line: 1, column: 14 }, - '15': { line: 1, column: 15 }, - '16': { line: 1, column: 16 }, - '17': { line: 1, column: 17 }, - '18': { line: 1, column: 18 }, - '19': { line: 1, column: 19 }, - '20': { line: 2, column: 0 }, - '21': { line: 2, column: 1 }, - '22': { line: 3, column: 0 }, - }; - expect(offsetToLocation).to.be.deep.equal(expectedLocationByOffset); - }); - }); - describe('#parseSourceMap', () => { - it('correctly parses the source map', () => { - // This is the source map and bytecode for an empty contract like Example.sol - const srcMap = '0:21:0:-;;;;;;;;;;;;;;;;;'; - const bytecodeHex = - '60606040523415600e57600080fd5b603580601b6000396000f3006060604052600080fd00a165627a7a72305820377cdef690e46589f40efeef14d8ef73504af059fb3fd46f1da3cd2fc52ef7890029'; - const sources = [simplestContractBaseName]; - const pcToSourceRange = parseSourceMap([simplestContract], srcMap, bytecodeHex, sources); - const expectedSourceRange = { - location: { - start: { line: 1, column: 0 }, - end: { line: 2, column: 1 }, - }, - fileName: simplestContractBaseName, - }; - _.forEach(pcToSourceRange, sourceRange => { - // Solidity source maps are too short and we map some instructions to undefined - // Source: https://github.com/ethereum/solidity/issues/3741 - if (sourceRange !== undefined) { - expect(sourceRange).to.be.deep.equal(expectedSourceRange); - } - }); - }); - }); -}); diff --git a/packages/sol-tracing-utils/test/trace_test.ts b/packages/sol-tracing-utils/test/trace_test.ts deleted file mode 100644 index c9ed93e630..0000000000 --- a/packages/sol-tracing-utils/test/trace_test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import * as chai from 'chai'; -import { OpCode, StructLog } from 'ethereum-types'; -import * as _ from 'lodash'; -import 'mocha'; - -import { getContractAddressToTraces } from '../src/trace'; - -const expect = chai.expect; - -const DEFAULT_STRUCT_LOG: StructLog = { - depth: 0, - error: '', - gas: 0, - gasCost: 0, - memory: [], - op: OpCode.Invalid, - pc: 0, - stack: [], - storage: {}, -}; - -function addDefaultStructLogFields(compactStructLog: Partial & { op: OpCode; depth: number }): StructLog { - return { ...DEFAULT_STRUCT_LOG, ...compactStructLog }; -} - -describe('Trace', () => { - describe('#getTracesByContractAddress', () => { - it('correctly splits trace by contract address', () => { - const delegateCallAddress = '0x0000000000000000000000000000000000000002'; - const trace = [ - { - op: OpCode.DelegateCall, - stack: [delegateCallAddress, '0x'], - depth: 0, - }, - { - op: OpCode.Return, - depth: 1, - }, - { - op: OpCode.Return, - depth: 0, - }, - ]; - const fullTrace = _.map(trace, compactStructLog => addDefaultStructLogFields(compactStructLog)); - const startAddress = '0x0000000000000000000000000000000000000001'; - const traceByContractAddress = getContractAddressToTraces(fullTrace, startAddress); - const expectedTraceByContractAddress = { - [startAddress]: [fullTrace[0], fullTrace[2]], - [delegateCallAddress]: [fullTrace[1]], - }; - expect(traceByContractAddress).to.be.deep.equal(expectedTraceByContractAddress); - }); - }); -}); diff --git a/packages/sol-tracing-utils/test/utils_test.ts b/packages/sol-tracing-utils/test/utils_test.ts deleted file mode 100644 index 6fc8fcfe1d..0000000000 --- a/packages/sol-tracing-utils/test/utils_test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import * as chai from 'chai'; -import * as dirtyChai from 'dirty-chai'; -import 'mocha'; - -import { utils } from '../src/utils'; - -chai.use(dirtyChai); -const expect = chai.expect; - -describe('utils', () => { - describe('#compareLineColumn', () => { - it('correctly compares LineColumns', () => { - expect(utils.compareLineColumn({ line: 1, column: 3 }, { line: 1, column: 4 })).to.be.lessThan(0); - expect(utils.compareLineColumn({ line: 1, column: 4 }, { line: 1, column: 3 })).to.be.greaterThan(0); - expect(utils.compareLineColumn({ line: 1, column: 3 }, { line: 1, column: 3 })).to.be.equal(0); - expect(utils.compareLineColumn({ line: 0, column: 2 }, { line: 1, column: 0 })).to.be.lessThan(0); - expect(utils.compareLineColumn({ line: 1, column: 0 }, { line: 0, column: 2 })).to.be.greaterThan(0); - }); - }); - - describe('#isRangeInside', () => { - it('returns true if inside', () => { - expect( - utils.isRangeInside( - { start: { line: 1, column: 3 }, end: { line: 1, column: 4 } }, - { start: { line: 1, column: 2 }, end: { line: 1, column: 5 } }, - ), - ).to.be.true(); - }); - it('returns true if the same', () => { - expect( - utils.isRangeInside( - { start: { line: 1, column: 3 }, end: { line: 1, column: 4 } }, - { start: { line: 1, column: 3 }, end: { line: 1, column: 4 } }, - ), - ).to.be.true(); - }); - it('returns false if not inside', () => { - expect( - utils.isRangeInside( - { start: { line: 1, column: 3 }, end: { line: 1, column: 4 } }, - { start: { line: 1, column: 4 }, end: { line: 1, column: 4 } }, - ), - ).to.be.false(); - expect( - utils.isRangeInside( - { start: { line: 1, column: 3 }, end: { line: 1, column: 4 } }, - { start: { line: 1, column: 4 }, end: { line: 1, column: 5 } }, - ), - ).to.be.false(); - }); - }); -}); diff --git a/packages/sol-tracing-utils/tsconfig.json b/packages/sol-tracing-utils/tsconfig.json deleted file mode 100644 index 2ee711adcc..0000000000 --- a/packages/sol-tracing-utils/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../tsconfig", - "compilerOptions": { - "outDir": "lib", - "rootDir": "." - }, - "include": ["./src/**/*", "./test/**/*"] -} diff --git a/packages/sol-tracing-utils/tslint.json b/packages/sol-tracing-utils/tslint.json deleted file mode 100644 index dd9053357e..0000000000 --- a/packages/sol-tracing-utils/tslint.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": ["@0x/tslint-config"] -} diff --git a/packages/sra-spec/.discharge.json b/packages/sra-spec/.discharge.json deleted file mode 100644 index 8985f07e87..0000000000 --- a/packages/sra-spec/.discharge.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "domain": "sra3-spec", - "build_command": "yarn build", - "upload_directory": "public", - "index_key": "index.html", - "error_key": "index.html", - "trailing_slashes": true, - "cache": 3600, - "aws_profile": "default", - "aws_region": "us-east-1", - "cdn": false, - "dns_configured": true -} diff --git a/packages/sra-spec/.gitignore b/packages/sra-spec/.gitignore deleted file mode 100644 index f029c576c1..0000000000 --- a/packages/sra-spec/.gitignore +++ /dev/null @@ -1 +0,0 @@ -public/api.json diff --git a/packages/sra-spec/.npmignore b/packages/sra-spec/.npmignore deleted file mode 100644 index e610180ad8..0000000000 --- a/packages/sra-spec/.npmignore +++ /dev/null @@ -1,8 +0,0 @@ -.* -yarn-error.log -/src/ -/schemas/ -test/ -tsconfig.json -/lib/src/monorepo_scripts/ -/public/ \ No newline at end of file diff --git a/packages/sra-spec/CHANGELOG.json b/packages/sra-spec/CHANGELOG.json deleted file mode 100644 index 97d32e77ff..0000000000 --- a/packages/sra-spec/CHANGELOG.json +++ /dev/null @@ -1,470 +0,0 @@ -[ - { - "timestamp": 1594788383, - "version": "3.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1592969527, - "version": "3.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1582623685, - "version": "3.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1581204851, - "version": "3.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1580988106, - "version": "3.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1579682890, - "version": "3.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1578272714, - "version": "3.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1576540892, - "version": "3.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1575931811, - "version": "3.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.0.0", - "changes": [ - { - "note": "All references to network ID have been removed, and references to chain ID have been introduced instead", - "pr": 2313 - } - ], - "timestamp": 1575296764 - }, - { - "version": "2.1.0-beta.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1575290197 - }, - { - "version": "2.1.0-beta.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1574030254 - }, - { - "version": "2.1.0-beta.1", - "changes": [ - { - "note": "All references to network ID have been removed, and references to chain ID have been introduced instead", - "pr": 2313 - } - ], - "timestamp": 1573159180 - }, - { - "version": "2.1.0-beta.0", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1570135330 - }, - { - "timestamp": 1568744790, - "version": "2.0.17", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1567521715, - "version": "2.0.16", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1566446343, - "version": "2.0.15", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1565296576, - "version": "2.0.14", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1564604963, - "version": "2.0.13", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563957393, - "version": "2.0.12", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563006338, - "version": "2.0.11", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1557507213, - "version": "2.0.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1554997931 - }, - { - "timestamp": 1553183790, - "version": "2.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1553091633, - "version": "2.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551479279, - "version": "2.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551220833, - "version": "2.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551130135, - "version": "2.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1549733923, - "version": "2.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1549547375 - }, - { - "timestamp": 1549452781, - "version": "2.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.0", - "changes": [ - { - "note": "Upgrade the bignumber.js to v8.0.2", - "pr": 1517 - } - ], - "timestamp": 1549373905 - }, - { - "timestamp": 1547561734, - "version": "1.0.16", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547225310, - "version": "1.0.15", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547040760, - "version": "1.0.14", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.13", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544739608 - }, - { - "version": "1.0.12", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544570656 - }, - { - "timestamp": 1542821676, - "version": "1.0.11", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542208198, - "version": "1.0.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542028948, - "version": "1.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1541740904 - }, - { - "version": "1.0.7", - "changes": [ - { - "note": "Make @loopback/openapi-v3-types a 'dependency' so it's available to users of the library", - "pr": 1105 - } - ], - "timestamp": 1539871071 - }, - { - "version": "1.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1538693146 - }, - { - "timestamp": 1538157789, - "version": "1.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537907159, - "version": "1.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537875740, - "version": "1.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537541580, - "version": "1.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1536142250, - "version": "1.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.1-rc.6", - "changes": [ - { - "note": "Fix `main` and `types` package.json entries so that they point to the new location of index.d.ts and index.js" - }, - { - "note": "Fix relative path to introduction MD file" - } - ], - "timestamp": 1535377027 - }, - { - "version": "1.0.1-rc.5", - "changes": [ - { - "note": "Add takerAddress to /orders parameters", - "pr": 974 - } - ], - "timestamp": 1535133899 - }, - { - "version": "1.0.1-rc.4", - "changes": [ - { - "note": "Add inital spec for SRA v2", - "pr": 916 - } - ], - "timestamp": 1534210131 - } -] diff --git a/packages/sra-spec/CHANGELOG.md b/packages/sra-spec/CHANGELOG.md deleted file mode 100644 index 4f202421e4..0000000000 --- a/packages/sra-spec/CHANGELOG.md +++ /dev/null @@ -1,211 +0,0 @@ - - -CHANGELOG - -## v3.0.9 - _July 15, 2020_ - - * Dependencies updated - -## v3.0.8 - _June 24, 2020_ - - * Dependencies updated - -## v3.0.7 - _February 25, 2020_ - - * Dependencies updated - -## v3.0.6 - _February 8, 2020_ - - * Dependencies updated - -## v3.0.5 - _February 6, 2020_ - - * Dependencies updated - -## v3.0.4 - _January 22, 2020_ - - * Dependencies updated - -## v3.0.3 - _January 6, 2020_ - - * Dependencies updated - -## v3.0.2 - _December 17, 2019_ - - * Dependencies updated - -## v3.0.1 - _December 9, 2019_ - - * Dependencies updated - -## v3.0.0 - _December 2, 2019_ - - * All references to network ID have been removed, and references to chain ID have been introduced instead (#2313) - -## v2.1.0-beta.3 - _December 2, 2019_ - - * Dependencies updated - -## v2.1.0-beta.2 - _November 17, 2019_ - - * Dependencies updated - -## v2.1.0-beta.1 - _November 7, 2019_ - - * All references to network ID have been removed, and references to chain ID have been introduced instead (#2313) - -## v2.1.0-beta.0 - _October 3, 2019_ - - * Dependencies updated - -## v2.0.17 - _September 17, 2019_ - - * Dependencies updated - -## v2.0.16 - _September 3, 2019_ - - * Dependencies updated - -## v2.0.15 - _August 22, 2019_ - - * Dependencies updated - -## v2.0.14 - _August 8, 2019_ - - * Dependencies updated - -## v2.0.13 - _July 31, 2019_ - - * Dependencies updated - -## v2.0.12 - _July 24, 2019_ - - * Dependencies updated - -## v2.0.11 - _July 13, 2019_ - - * Dependencies updated - -## v2.0.10 - _May 10, 2019_ - - * Dependencies updated - -## v2.0.9 - _April 11, 2019_ - - * Dependencies updated - -## v2.0.8 - _March 21, 2019_ - - * Dependencies updated - -## v2.0.7 - _March 20, 2019_ - - * Dependencies updated - -## v2.0.6 - _March 1, 2019_ - - * Dependencies updated - -## v2.0.5 - _February 26, 2019_ - - * Dependencies updated - -## v2.0.4 - _February 25, 2019_ - - * Dependencies updated - -## v2.0.3 - _February 9, 2019_ - - * Dependencies updated - -## v2.0.2 - _February 7, 2019_ - - * Dependencies updated - -## v2.0.1 - _February 6, 2019_ - - * Dependencies updated - -## v2.0.0 - _February 5, 2019_ - - * Upgrade the bignumber.js to v8.0.2 (#1517) - -## v1.0.16 - _January 15, 2019_ - - * Dependencies updated - -## v1.0.15 - _January 11, 2019_ - - * Dependencies updated - -## v1.0.14 - _January 9, 2019_ - - * Dependencies updated - -## v1.0.13 - _December 13, 2018_ - - * Dependencies updated - -## v1.0.12 - _December 11, 2018_ - - * Dependencies updated - -## v1.0.11 - _November 21, 2018_ - - * Dependencies updated - -## v1.0.10 - _November 14, 2018_ - - * Dependencies updated - -## v1.0.9 - _November 12, 2018_ - - * Dependencies updated - -## v1.0.8 - _November 9, 2018_ - - * Dependencies updated - -## v1.0.7 - _October 18, 2018_ - - * Make @loopback/openapi-v3-types a 'dependency' so it's available to users of the library (#1105) - -## v1.0.6 - _October 4, 2018_ - - * Dependencies updated - -## v1.0.5 - _September 28, 2018_ - - * Dependencies updated - -## v1.0.4 - _September 25, 2018_ - - * Dependencies updated - -## v1.0.3 - _September 25, 2018_ - - * Dependencies updated - -## v1.0.2 - _September 21, 2018_ - - * Dependencies updated - -## v1.0.1 - _September 5, 2018_ - - * Dependencies updated - -## v1.0.1-rc.6 - _August 27, 2018_ - - * Fix `main` and `types` package.json entries so that they point to the new location of index.d.ts and index.js - * Fix relative path to introduction MD file - -## v1.0.1-rc.5 - _August 24, 2018_ - - * Add takerAddress to /orders parameters (#974) - -## v1.0.1-rc.4 - _August 14, 2018_ - - * Add inital spec for SRA v2 (#916) diff --git a/packages/sra-spec/README.md b/packages/sra-spec/README.md deleted file mode 100644 index 4575aaf66f..0000000000 --- a/packages/sra-spec/README.md +++ /dev/null @@ -1,93 +0,0 @@ -## @0x/sra-spec - -Contains the Standard Relayer API [OpenAPI Spec](https://github.com/OAI/OpenAPI-Specification). - -The package distributes both a javascript object version and a json version. - -A deployed [ReDoc](https://github.com/Rebilly/ReDoc) static site with the API can be found here http://sra-spec.s3-website-us-east-1.amazonaws.com/. - -## Usage - -``` -import { api } from '@0x/sra-spec'; -``` - -## Installation - -``` -yarn install -``` - -## Development - -You can start a development server that will serve a [ReDoc](https://github.com/Rebilly/ReDoc) documentation instance. It uses the `api.json` file from `lib/` (you must have built at least once with `yarn build` or `yarn build-json`) that is based on the `api` object exported from `src`. - -``` -yarn watch_without_deps -``` - -The process will watch for changes, but will not hot-reload so you must refresh the page to see the changes. - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install dependencies - -If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: - -```bash -yarn config set workspaces-experimental true -``` - -Then install dependencies - -```bash -yarn install -``` - -### Build - -To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory: - -```bash -PKG=@0x/sra-spec yarn build -``` - -Or continuously rebuild on change: - -```bash -PKG=@0x/sra-spec yarn watch -``` - -### Static Site - -We also [host a static HTML version of the docs on S3](http://sra-spec.s3-website-us-east-1.amazonaws.com/) for easy sharing. - -To build and deploy the site run - -``` -yarn deploy-site -``` - -**NOTE: On deploying the site, it will say the site is available at a non-existent URL. Please ignore and use the (now updated) URL above.** - -### Clean - -```bash -yarn clean -``` - -### Lint - -```bash -yarn lint -``` - -### Run Tests - -```bash -yarn test -``` diff --git a/packages/sra-spec/build_scripts/buildJson.ts b/packages/sra-spec/build_scripts/buildJson.ts deleted file mode 100644 index b92b5172bd..0000000000 --- a/packages/sra-spec/build_scripts/buildJson.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { writeFileSync } from 'fs'; - -import { api } from '../src'; - -const apiJson = JSON.stringify(api); -writeFileSync('lib/api.json', apiJson); -writeFileSync('public/api.json', apiJson); diff --git a/packages/sra-spec/package.json b/packages/sra-spec/package.json deleted file mode 100644 index 0548ae38d9..0000000000 --- a/packages/sra-spec/package.json +++ /dev/null @@ -1,63 +0,0 @@ -{ - "name": "@0x/sra-spec", - "version": "3.0.9", - "engines": { - "node": ">=6.12" - }, - "description": "Standard Relayer API Open API Spec", - "main": "lib/src/index.js", - "types": "lib/src/index.d.ts", - "scripts": { - "watch_without_deps": "run-p build:watch serve", - "lint": "tslint --format stylish --project .", - "fix": "tslint --fix --format stylish --project .", - "test": "swagger-cli validate lib/api.json", - "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", - "clean": "shx rm -rf lib", - "build": "tsc -b && yarn copy_md_files && yarn build-json", - "build:ci": "yarn build", - "build-json": "node ./lib/build_scripts/buildJson", - "build:watch": "chokidar 'src/**/*' -c 'yarn build' ", - "copy_md_files": "copyfiles -u 2 './src/md/**/*.md' ./lib/src/md", - "deploy-site": "discharge deploy" - }, - "repository": { - "type": "git", - "url": "https://github.com/0xProject/0x-monorepo.git" - }, - "author": "Francesco Agosti", - "license": "Apache-2.0", - "bugs": { - "url": "https://github.com/0xProject/0x-monorepo/issues" - }, - "homepage": "https://github.com/0xProject/0x-monorepo/packages/sra-spec/README.md", - "dependencies": { - "@0x/json-schemas": "^5.1.0", - "@loopback/openapi-v3-types": "^0.8.2" - }, - "devDependencies": { - "@0x/tslint-config": "^4.1.0", - "@types/mocha": "^5.2.7", - "@types/node": "12.12.54", - "chai": "^4.0.1", - "chokidar-cli": "^1.2.0", - "copyfiles": "^2.0.0", - "dirty-chai": "^2.0.1", - "discharge": "^0.7.1", - "mocha": "^6.2.0", - "npm-run-all": "^4.1.2", - "nyc": "^11.0.1", - "shx": "^0.2.2", - "swagger-cli": "^2.1.1", - "ts-node": "^7.0.0", - "tslint": "5.11.0", - "typescript": "3.0.1" - }, - "publishConfig": { - "access": "public" - }, - "gitHead": "4f91bfd907996b2f4dd383778b50c479c2602b56" -} diff --git a/packages/sra-spec/public/index.html b/packages/sra-spec/public/index.html deleted file mode 100644 index e334c6749c..0000000000 --- a/packages/sra-spec/public/index.html +++ /dev/null @@ -1,27 +0,0 @@ - - - - - 0x Standard Relayer API - - - - - - - - - - - - - - - diff --git a/packages/sra-spec/src/api.ts b/packages/sra-spec/src/api.ts deleted file mode 100644 index fdfb9548b5..0000000000 --- a/packages/sra-spec/src/api.ts +++ /dev/null @@ -1,328 +0,0 @@ -import { OpenApiSpec } from '@loopback/openapi-v3-types'; - -import { examples } from './examples'; -import { schemas } from './json-schemas'; -import { md } from './md'; -import { generateParameters } from './parameters'; -import { generateResponses } from './responses'; - -export const api: OpenApiSpec = { - openapi: '3.0.0', - info: { - version: '3.0.0', - title: 'Standard Relayer REST API', - description: md.introduction, - license: { - name: 'Apache 2.0', - url: 'https://www.apache.org/licenses/LICENSE-2.0.html', - }, - }, - paths: { - '/v3/asset_pairs': { - get: { - description: - 'Retrieves a list of available asset pairs and the information required to trade them (in any order). Setting only `assetDataA` or `assetDataB` returns pairs filtered by that asset only.', - operationId: 'getAssetPairs', - parameters: generateParameters( - [ - { - name: 'assetDataA', - in: 'query', - description: 'The assetData value for the first asset in the pair.', - example: '0xf47261b04c32345ced77393b3530b1eed0f346429d', - schema: { - $ref: '#/components/schemas/hexSchema', - }, - }, - { - name: 'assetDataB', - in: 'query', - description: 'The assetData value for the second asset in the pair.', - example: '0x0257179264389b814a946f3e92105513705ca6b990', - schema: { - $ref: '#/components/schemas/hexSchema', - }, - }, - ], - true, - ), - responses: generateResponses( - 'relayerApiAssetDataPairsResponseSchema', - examples.relayerApiAssetDataPairsResponse, - `Returns a collection of available asset pairs with some meta info`, - ), - }, - }, - '/v3/orders': { - get: { - description: - 'Retrieves a list of orders given query parameters. This endpoint should be [paginated](#section/Pagination). For querying an entire orderbook snapshot, the [orderbook endpoint](#operation/getOrderbook) is recommended. If both makerAssetData and takerAssetData are specified, returned orders will be sorted by price determined by (takerTokenAmount/makerTokenAmount) in ascending order. By default, orders returned by this endpoint are unsorted.', - operationId: 'getOrders', - parameters: generateParameters( - [ - { - name: 'makerAssetProxyId', - in: 'query', - description: `The maker asset proxy id (example: "0xf47261b0" for ERC20, "0x02571792" for ERC721).`, - example: '0xf47261b0', - schema: { - $ref: '#/components/schemas/hexSchema', - }, - }, - { - name: 'takerAssetProxyId', - in: 'query', - description: `The taker asset asset proxy id (example: "0xf47261b0" for ERC20, "0x02571792" for ERC721).`, - example: '0x02571792', - schema: { - $ref: '#/components/schemas/hexSchema', - }, - }, - { - name: 'makerAssetAddress', - in: 'query', - description: `The contract address for the maker asset.`, - example: '0xe41d2489571d322189246dafa5ebde1f4699f498', - schema: { - $ref: '#/components/schemas/addressSchema', - }, - }, - { - name: 'takerAssetAddress', - in: 'query', - description: `The contract address for the taker asset.`, - example: '0xe41d2489571d322189246dafa5ebde1f4699f498', - schema: { - $ref: '#/components/schemas/addressSchema', - }, - }, - { - name: 'exchangeAddress', - in: 'query', - description: `Same as exchangeAddress in the [0x Protocol v3 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v3/v3-specification.md#order-message-format)`, - example: '0xe41d2489571d322189246dafa5ebde1f4699f498', - schema: { - $ref: '#/components/schemas/addressSchema', - }, - }, - { - name: 'senderAddress', - in: 'query', - description: `Same as senderAddress in the [0x Protocol v3 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v3/v3-specification.md#order-message-format)`, - example: '0xe41d2489571d322189246dafa5ebde1f4699f498', - schema: { - $ref: '#/components/schemas/addressSchema', - }, - }, - { - name: 'makerAssetData', - in: 'query', - description: `Same as makerAssetData in the [0x Protocol v3 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v3/v3-specification.md#order-message-format)`, - example: '0xe41d2489571d322189246dafa5ebde1f4699f498', - schema: { - $ref: '#/components/schemas/hexSchema', - }, - }, - { - name: 'takerAssetData', - in: 'query', - description: `Same as takerAssetData in the [0x Protocol v3 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v3/v3-specification.md#order-message-format)`, - example: '0xe41d2489571d322189246dafa5ebde1f4699f498', - schema: { - $ref: '#/components/schemas/hexSchema', - }, - }, - { - name: 'traderAssetData', - in: 'query', - description: `Same as traderAssetData in the [0x Protocol v3 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v3/v3-specification.md#order-message-format)`, - example: '0xe41d2489571d322189246dafa5ebde1f4699f498', - schema: { - $ref: '#/components/schemas/hexSchema', - }, - }, - { - name: 'makerAddress', - in: 'query', - description: `Same as makerAddress in the [0x Protocol v3 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v3/v3-specification.md#order-message-format)`, - example: '0xe41d2489571d322189246dafa5ebde1f4699f498', - schema: { - $ref: '#/components/schemas/addressSchema', - }, - }, - { - name: 'takerAddress', - in: 'query', - description: `Same as takerAddress in the [0x Protocol v3 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v3/v3-specification.md#order-message-format)`, - example: '0xe41d2489571d322189246dafa5ebde1f4699f498', - schema: { - $ref: '#/components/schemas/addressSchema', - }, - }, - { - name: 'traderAddress', - in: 'query', - description: `Same as traderAddress in the [0x Protocol v3 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v3/v3-specification.md#order-message-format)`, - example: '0xe41d2489571d322189246dafa5ebde1f4699f498', - schema: { - $ref: '#/components/schemas/addressSchema', - }, - }, - { - name: 'feeRecipientAddress', - in: 'query', - description: `Same as feeRecipientAddress in the [0x Protocol v3 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v3/v3-specification.md#order-message-format)`, - example: '0xe41d2489571d322189246dafa5ebde1f4699f498', - schema: { - $ref: '#/components/schemas/addressSchema', - }, - }, - { - name: 'makerFeeAssetData', - in: 'query', - description: `Same as makerFeeAssetData in the [0x Protocol v3 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v3/v3-specification.md#order-message-format)`, - example: '0xe41d2489571d322189246dafa5ebde1f4699f498', - schema: { - $ref: '#/components/schemas/hexSchema', - }, - }, - { - name: 'takerFeeAssetData', - in: 'query', - description: `Same as takerFeeAssetData in the [0x Protocol v3 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v3/v3-specification.md#order-message-format)`, - example: '0xe41d2489571d322189246dafa5ebde1f4699f498', - schema: { - $ref: '#/components/schemas/hexSchema', - }, - }, - ], - true, - ), - responses: generateResponses( - 'relayerApiOrdersResponseSchema', - examples.relayerApiOrdersResponse, - `A collection of 0x orders with meta-data as specified by query params`, - ), - }, - }, - '/v3/order/{orderHash}': { - get: { - description: 'Retrieves the 0x order with meta info that is associated with the hash.', - operationId: 'getOrder', - parameters: generateParameters( - [ - { - name: 'orderHash', - in: 'path', - description: 'The hash of the desired 0x order.', - example: '0xd4b103c42d2512eef3fee775e097f044291615d25f5d71e0ac70dbd49d223591', - schema: { - $ref: '#/components/schemas/orderHashSchema', - }, - }, - ], - false, - ), - responses: generateResponses( - 'relayerApiOrderSchema', - examples.relayerApiOrder, - `The order and meta info associated with the orderHash`, - ), - }, - }, - '/v3/orderbook': { - get: { - description: `Retrieves the orderbook for a given asset pair. This endpoint should be [paginated](#section/Pagination). Bids will be sorted in descending order by price, and asks will be sorted in ascending order by price. Within the price sorted orders, the orders are further sorted by _taker fee price_ which is defined as the **takerFee** divided by **takerTokenAmount**. After _taker fee price_, orders are to be sorted by expiration in ascending order. The way pagination works for this endpoint is that the **page** and **perPage** query params apply to both \`bids\` and \`asks\` collections, and if \`page\` * \`perPage\` > \`total\` for a certain collection, the \`records\` for that collection should just be empty. `, - operationId: 'getOrderbook', - parameters: generateParameters( - [ - { - name: 'baseAssetData', - in: 'query', - description: `assetData (makerAssetData or takerAssetData) designated as the base currency in the [currency pair calculation](https://en.wikipedia.org/wiki/Currency_pair) of price.`, - required: true, - example: '0xf47261b04c32345ced77393b3530b1eed0f346429d', - schema: { - $ref: '#/components/schemas/hexSchema', - }, - }, - { - name: 'quoteAssetData', - in: 'query', - description: `assetData (makerAssetData or takerAssetData) designated as the quote currency in the currency pair calculation of price (required).`, - required: true, - example: '0xf47261b04c32345ced77393b3530b1eed0f346429d', - schema: { - $ref: '#/components/schemas/hexSchema', - }, - }, - ], - true, - ), - responses: generateResponses( - 'relayerApiOrderbookResponseSchema', - examples.relayerApiOrderbookResponse, - `The sorted order book for the specified asset pair.`, - ), - }, - }, - '/v3/order_config': { - post: { - description: `Relayers have full discretion over the orders that they are willing to host on their orderbooks (e.g what fees they charge, etc...). In order for traders to discover their requirements programmatically, they can send an incomplete order to this endpoint and receive the missing fields, specifc to that order. This gives relayers a large amount of flexibility to tailor fees to unique traders, trading pairs and volume amounts. Submit a partial order and receive information required to complete the order: \`senderAddress\`, \`feeRecipientAddress\`, \`makerFee\`, \`takerFee\`, \`makerFeeAssetData\`, \`takerFeeAssetData\`. `, - operationId: 'getOrderConfig', - parameters: generateParameters([], false), - requestBody: { - description: - 'The fields of a 0x order the relayer may want to decide what configuration to send back.', - content: { - 'application/json': { - schema: { - $ref: '#/components/schemas/relayerApiOrderConfigPayloadSchema', - }, - example: examples.relayerApiOrderConfigPayload, - }, - }, - }, - responses: generateResponses( - 'relayerApiOrderConfigResponseSchema', - examples.relayerApiOrderConfigResponse, - `The additional fields necessary in order to submit an order to the relayer.`, - ), - }, - }, - '/v3/fee_recipients': { - get: { - description: `Retrieves a collection of all fee recipient addresses for a relayer. This endpoint should be [paginated](#section/Pagination).`, - operationId: 'getFeeRecipients', - parameters: generateParameters([], true), - responses: generateResponses( - 'relayerApiFeeRecipientsResponseSchema', - examples.relayerApiFeeRecipientsResponse, - `A collection of all used fee recipient addresses.`, - ), - }, - }, - '/v3/order': { - post: { - description: `Submit a signed order to the relayer.`, - operationId: 'postOrder', - parameters: generateParameters([], false), - requestBody: { - description: 'A valid signed 0x order based on the schema.', - content: { - 'application/json': { - schema: { - $ref: '#/components/schemas/signedOrderSchema', - }, - example: examples.signedOrder, - }, - }, - }, - responses: generateResponses(), - }, - }, - }, - components: { - schemas, - }, -}; diff --git a/packages/sra-spec/src/errors.ts b/packages/sra-spec/src/errors.ts deleted file mode 100644 index 20c35514f5..0000000000 --- a/packages/sra-spec/src/errors.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { examples } from './examples'; -export const errorResponses = { - '400': { - description: 'Validation error', - content: { - 'application/json': { - schema: { $ref: '#/components/schemas/relayerApiErrorResponseSchema' }, - example: examples.validationError, - }, - }, - }, - '404': { - description: 'Not found', - }, - '429': { - description: 'Too many requests - Rate limit exceeded', - }, - '500': { - description: 'Internal Server Error', - }, - '501': { - description: 'Not implemented.', - }, -}; diff --git a/packages/sra-spec/src/examples/errors.ts b/packages/sra-spec/src/examples/errors.ts deleted file mode 100644 index 1c834c55cd..0000000000 --- a/packages/sra-spec/src/examples/errors.ts +++ /dev/null @@ -1,11 +0,0 @@ -export const validationError = { - code: 101, - reason: 'Validation failed', - validationErrors: [ - { - field: 'maker', - code: 1002, - reason: 'Invalid address', - }, - ], -}; diff --git a/packages/sra-spec/src/examples/index.ts b/packages/sra-spec/src/examples/index.ts deleted file mode 100644 index dcf9b13ebe..0000000000 --- a/packages/sra-spec/src/examples/index.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { validationError } from './errors'; -import { relayerApiAssetDataPairsResponse } from './relayerApiAssetDataPairsResponse'; -import { relayerApiFeeRecipientsResponse } from './relayerApiFeeRecipientsResponse'; -import { relayerApiOrder } from './relayerApiOrder'; -import { relayerApiOrderbookResponse } from './relayerApiOrderbookResponse'; -import { relayerApiOrderConfigPayload } from './relayerApiOrderConfigPayload'; -import { relayerApiOrderConfigResponse } from './relayerApiOrderConfigResponse'; -import { relayerApiOrdersResponse } from './relayerApiOrdersResponse'; -import { signedOrder } from './signedOrder'; - -export const examples = { - validationError, - relayerApiAssetDataPairsResponse, - relayerApiFeeRecipientsResponse, - relayerApiOrder, - relayerApiOrderbookResponse, - relayerApiOrderConfigPayload, - relayerApiOrderConfigResponse, - relayerApiOrdersResponse, - signedOrder, -}; diff --git a/packages/sra-spec/src/examples/relayerApiAssetDataPairsResponse.ts b/packages/sra-spec/src/examples/relayerApiAssetDataPairsResponse.ts deleted file mode 100644 index 3ab7b29c07..0000000000 --- a/packages/sra-spec/src/examples/relayerApiAssetDataPairsResponse.ts +++ /dev/null @@ -1,22 +0,0 @@ -export const relayerApiAssetDataPairsResponse = { - total: 43, - page: 1, - perPage: 100, - records: [ - { - assetDataA: { - minAmount: '0', - maxAmount: '10000000000000000000', - precision: 5, - assetData: '0xf47261b0000000000000000000000000e41d2489571d322189246dafa5ebde1f4699f498', - }, - assetDataB: { - minAmount: '0', - maxAmount: '1', - precision: 5, - assetData: - '0x02571792000000000000000000000000371b13d97f4bf77d724e78c16b7dc74099f40e840000000000000000000000000000000000000000000000000000000000000063', - }, - }, - ], -}; diff --git a/packages/sra-spec/src/examples/relayerApiFeeRecipientsResponse.ts b/packages/sra-spec/src/examples/relayerApiFeeRecipientsResponse.ts deleted file mode 100644 index 0182af629f..0000000000 --- a/packages/sra-spec/src/examples/relayerApiFeeRecipientsResponse.ts +++ /dev/null @@ -1,10 +0,0 @@ -export const relayerApiFeeRecipientsResponse = { - total: 3, - page: 1, - perPage: 10, - records: [ - '0x6eC92694ea172ebC430C30fa31De87620967A082', - '0x9e56625509c2f60af937f23b7b532600390e8c8b', - '0xa2b31dacf30a9c50ca473337c01d8a201ae33e32', - ], -}; diff --git a/packages/sra-spec/src/examples/relayerApiOrder.ts b/packages/sra-spec/src/examples/relayerApiOrder.ts deleted file mode 100644 index a2851943b2..0000000000 --- a/packages/sra-spec/src/examples/relayerApiOrder.ts +++ /dev/null @@ -1,23 +0,0 @@ -export const relayerApiOrder = { - order: { - makerAddress: '0x9e56625509c2f60af937f23b7b532600390e8c8b', - takerAddress: '0xa2b31dacf30a9c50ca473337c01d8a201ae33e32', - feeRecipientAddress: '0xb046140686d052fff581f63f8136cce132e857da', - senderAddress: '0xa2b31dacf30a9c50ca473337c01d8a201ae33e32', - makerAssetAmount: '10000000000000000', - takerAssetAmount: '1', - makerFee: '100000000000000', - takerFee: '200000000000000', - expirationTimeSeconds: '1532560590', - salt: '1532559225', - makerAssetData: '0xf47261b0000000000000000000000000e41d2489571d322189246dafa5ebde1f4699f498', - takerAssetData: - '0x02571792000000000000000000000000371b13d97f4bf77d724e78c16b7dc74099f40e840000000000000000000000000000000000000000000000000000000000000063', - makerFeeAssetData: '0xf47261b04c32345ced77393b3530b1eed0f346429d', - takerFeeAssetData: '0xf47261b04c32345ced77393b3530b1eed0f346429d', - exchangeAddress: '0x12459c951127e0c374ff9105dda097662a027093', - signature: '0x012761a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351bc33', - chainId: 1, - }, - metaData: {}, -}; diff --git a/packages/sra-spec/src/examples/relayerApiOrderConfigPayload.ts b/packages/sra-spec/src/examples/relayerApiOrderConfigPayload.ts deleted file mode 100644 index cca68b84d2..0000000000 --- a/packages/sra-spec/src/examples/relayerApiOrderConfigPayload.ts +++ /dev/null @@ -1,11 +0,0 @@ -export const relayerApiOrderConfigPayload = { - makerAddress: '0x9e56625509c2f60af937f23b7b532600390e8c8b', - takerAddress: '0xa2b31dacf30a9c50ca473337c01d8a201ae33e32', - makerAssetAmount: '10000000000000000', - takerAssetAmount: '1', - makerAssetData: '0xf47261b0000000000000000000000000e41d2489571d322189246dafa5ebde1f4699f498', - takerAssetData: - '0x02571792000000000000000000000000371b13d97f4bf77d724e78c16b7dc74099f40e840000000000000000000000000000000000000000000000000000000000000063', - exchangeAddress: '0x12459c951127e0c374ff9105dda097662a027093', - expirationTimeSeconds: '1532560590', -}; diff --git a/packages/sra-spec/src/examples/relayerApiOrderConfigResponse.ts b/packages/sra-spec/src/examples/relayerApiOrderConfigResponse.ts deleted file mode 100644 index ec43c9f05a..0000000000 --- a/packages/sra-spec/src/examples/relayerApiOrderConfigResponse.ts +++ /dev/null @@ -1,8 +0,0 @@ -export const relayerApiOrderConfigResponse = { - senderAddress: '0xa2b31dacf30a9c50ca473337c01d8a201ae33e32', - feeRecipientAddress: '0xb046140686d052fff581f63f8136cce132e857da', - makerFee: '100000000000000', - takerFee: '200000000000000', - makerFeeAssetData: '0xf47261b04c32345ced77393b3530b1eed0f346429d', - takerFeeAssetData: '0xf47261b04c32345ced77393b3530b1eed0f346429d', -}; diff --git a/packages/sra-spec/src/examples/relayerApiOrderbookResponse.ts b/packages/sra-spec/src/examples/relayerApiOrderbookResponse.ts deleted file mode 100644 index ab9825cdbd..0000000000 --- a/packages/sra-spec/src/examples/relayerApiOrderbookResponse.ts +++ /dev/null @@ -1,60 +0,0 @@ -export const relayerApiOrderbookResponse = { - bids: { - total: 325, - page: 2, - perPage: 100, - records: [ - { - order: { - makerAddress: '0x9e56625509c2f60af937f23b7b532600390e8c8b', - takerAddress: '0xa2b31dacf30a9c50ca473337c01d8a201ae33e32', - feeRecipientAddress: '0xb046140686d052fff581f63f8136cce132e857da', - senderAddress: '0xa2b31dacf30a9c50ca473337c01d8a201ae33e32', - makerAssetAmount: '10000000000000000', - takerAssetAmount: '1', - makerFee: '100000000000000', - takerFee: '200000000000000', - expirationTimeSeconds: '1532560590', - salt: '1532559225', - makerAssetData: '0xf47261b0000000000000000000000000e41d2489571d322189246dafa5ebde1f4699f498', - takerAssetData: - '0x02571792000000000000000000000000371b13d97f4bf77d724e78c16b7dc74099f40e840000000000000000000000000000000000000000000000000000000000000063', - makerFeeAssetData: '0xf47261b04c32345ced77393b3530b1eed0f346429d', - takerFeeAssetData: '0xf47261b04c32345ced77393b3530b1eed0f346429d', - exchangeAddress: '0x12459c951127e0c374ff9105dda097662a027093', - signature: '0x012761a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351bc33', - chainId: 1, - }, - metaData: {}, - }, - ], - }, - asks: { - total: 500, - page: 2, - perPage: 100, - records: [ - { - order: { - makerAddress: '0xa2b31dacf30a9c50ca473337c01d8a201ae33e32', - takerAddress: '0x9e56625509c2f60af937f23b7b532600390e8c8b', - feeRecipientAddress: '0xb046140686d052fff581f63f8136cce132e857da', - senderAddress: '0xa2b31dacf30a9c50ca473337c01d8a201ae33e32', - makerAssetAmount: '20000000000000000', - takerAssetAmount: '1', - makerFee: '200000000000000', - takerFee: '100000000000000', - expirationTimeSeconds: '1532560590', - salt: '1532559225', - makerAssetData: - '0x02571792000000000000000000000000371b13d97f4bf77d724e78c16b7dc74099f40e840000000000000000000000000000000000000000000000000000000000000063', - takerAssetData: '0xf47261b0000000000000000000000000e41d2489571d322189246dafa5ebde1f4699f498', - exchangeAddress: '0x12459c951127e0c374ff9105dda097662a027093', - signature: '0x013842a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b3518891', - chainId: 1, - }, - metaData: {}, - }, - ], - }, -}; diff --git a/packages/sra-spec/src/examples/relayerApiOrdersResponse.ts b/packages/sra-spec/src/examples/relayerApiOrdersResponse.ts deleted file mode 100644 index d5f64d6215..0000000000 --- a/packages/sra-spec/src/examples/relayerApiOrdersResponse.ts +++ /dev/null @@ -1,30 +0,0 @@ -export const relayerApiOrdersResponse = { - total: 984, - page: 1, - perPage: 100, - records: [ - { - order: { - makerAddress: '0x9e56625509c2f60af937f23b7b532600390e8c8b', - takerAddress: '0xa2b31dacf30a9c50ca473337c01d8a201ae33e32', - feeRecipientAddress: '0xb046140686d052fff581f63f8136cce132e857da', - senderAddress: '0xa2b31dacf30a9c50ca473337c01d8a201ae33e32', - makerAssetAmount: '10000000000000000', - takerAssetAmount: '1', - makerFee: '100000000000000', - takerFee: '200000000000000', - expirationTimeSeconds: '1532560590', - salt: '1532559225', - makerAssetData: '0xf47261b0000000000000000000000000e41d2489571d322189246dafa5ebde1f4699f498', - takerAssetData: - '0x02571792000000000000000000000000371b13d97f4bf77d724e78c16b7dc74099f40e840000000000000000000000000000000000000000000000000000000000000063', - makerFeeAssetData: '0xf47261b04c32345ced77393b3530b1eed0f346429d', - takerFeeAssetData: '0xf47261b04c32345ced77393b3530b1eed0f346429d', - exchangeAddress: '0x12459c951127e0c374ff9105dda097662a027093', - signature: '0x012761a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351bc33', - chainId: 1, - }, - metaData: {}, - }, - ], -}; diff --git a/packages/sra-spec/src/examples/signedOrder.ts b/packages/sra-spec/src/examples/signedOrder.ts deleted file mode 100644 index c901da2909..0000000000 --- a/packages/sra-spec/src/examples/signedOrder.ts +++ /dev/null @@ -1,20 +0,0 @@ -export const signedOrder = { - makerAddress: '0x9e56625509c2f60af937f23b7b532600390e8c8b', - takerAddress: '0xa2b31dacf30a9c50ca473337c01d8a201ae33e32', - feeRecipientAddress: '0xb046140686d052fff581f63f8136cce132e857da', - senderAddress: '0xa2b31dacf30a9c50ca473337c01d8a201ae33e32', - makerAssetAmount: '10000000000000000', - takerAssetAmount: '20000000000000000', - makerFee: '100000000000000', - takerFee: '200000000000000', - expirationTimeSeconds: '1532560590', - salt: '1532559225', - makerAssetData: '0xf47261b0000000000000000000000000e41d2489571d322189246dafa5ebde1f4699f498', - takerAssetData: - '0x02571792000000000000000000000000371b13d97f4bf77d724e78c16b7dc74099f40e840000000000000000000000000000000000000000000000000000000000000063', - makerFeeAssetData: '0xf47261b04c32345ced77393b3530b1eed0f346429d', - takerFeeAssetData: '0xf47261b04c32345ced77393b3530b1eed0f346429d', - exchangeAddress: '0x12459c951127e0c374ff9105dda097662a027093', - signature: '0x012761a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351bc33', - chainId: 1, -}; diff --git a/packages/sra-spec/src/headers.ts b/packages/sra-spec/src/headers.ts deleted file mode 100644 index 152254c9fb..0000000000 --- a/packages/sra-spec/src/headers.ts +++ /dev/null @@ -1,20 +0,0 @@ -export const headers = { - 'X-Rate-Limit-Limit': { - description: `The maximum number of requests you're permitted to make per hour.`, - schema: { - type: 'integer', - }, - }, - 'X-Rate-Limit-Remaining': { - description: 'The number of requests remaining in the current rate limit window.', - schema: { - type: 'integer', - }, - }, - 'X-Rate-Limit-Reset': { - description: 'The time at which the current rate limit window resets in UTC epoch seconds.', - schema: { - type: 'integer', - }, - }, -}; diff --git a/packages/sra-spec/src/index.ts b/packages/sra-spec/src/index.ts deleted file mode 100644 index 4d73f3cd3a..0000000000 --- a/packages/sra-spec/src/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { api } from './api'; diff --git a/packages/sra-spec/src/json-schemas.ts b/packages/sra-spec/src/json-schemas.ts deleted file mode 100644 index f9342ca9e8..0000000000 --- a/packages/sra-spec/src/json-schemas.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { schemas as jsonSchemas } from '@0x/json-schemas'; - -// Only include schemas we actually need -const { - wholeNumberSchema, - numberSchema, - addressSchema, - hexSchema, - orderHashSchema, - orderSchema, - signedOrderSchema, - signedOrdersSchema, - ordersSchema, - paginatedCollectionSchema, - relayerApiErrorResponseSchema, - relayerApiFeeRecipientsResponseSchema, - relayerApiOrderSchema, - relayerApiOrdersSchema, - relayerApiOrderConfigPayloadSchema, - relayerApiOrderConfigResponseSchema, - relayerApiOrderbookResponseSchema, - relayerApiAssetDataPairsResponseSchema, - relayerApiAssetDataTradeInfoSchema, - relayerApiOrdersChannelSubscribeSchema, - relayerApiOrdersChannelSubscribePayloadSchema, - relayerApiOrdersChannelUpdateSchema, - relayerApiOrdersResponseSchema, - relayerApiAssetDataPairsSchema, -} = jsonSchemas; - -const usedSchemas = { - wholeNumberSchema, - numberSchema, - addressSchema, - hexSchema, - orderHashSchema, - orderSchema, - signedOrderSchema, - signedOrdersSchema, - ordersSchema, - paginatedCollectionSchema, - relayerApiErrorResponseSchema, - relayerApiFeeRecipientsResponseSchema, - relayerApiOrderSchema, - relayerApiOrdersSchema, - relayerApiOrderConfigPayloadSchema, - relayerApiOrderConfigResponseSchema, - relayerApiOrderbookResponseSchema, - relayerApiAssetDataPairsResponseSchema, - relayerApiAssetDataTradeInfoSchema, - relayerApiOrdersChannelSubscribeSchema, - relayerApiOrdersChannelSubscribePayloadSchema, - relayerApiOrdersChannelUpdateSchema, - relayerApiOrdersResponseSchema, - relayerApiAssetDataPairsSchema, -}; - -// We need to replace the `$ref`s to be OpenAPI compliant. -const openApiSchemas = JSON.parse( - JSON.stringify(usedSchemas).replace(/(\/\w+)/g, match => `#/components/schemas${match}`), -); -// The json schema used by OpenAPI does not accept ids -Object.keys(openApiSchemas).forEach(key => delete openApiSchemas[key].id); - -export const schemas = openApiSchemas; diff --git a/packages/sra-spec/src/md/index.ts b/packages/sra-spec/src/md/index.ts deleted file mode 100644 index 4e778e0736..0000000000 --- a/packages/sra-spec/src/md/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { readFileSync } from 'fs'; - -export const md = { - introduction: readFileSync(`${__dirname}/introduction.md`).toString(), -}; diff --git a/packages/sra-spec/src/md/introduction.md b/packages/sra-spec/src/md/introduction.md deleted file mode 100644 index 79c588f242..0000000000 --- a/packages/sra-spec/src/md/introduction.md +++ /dev/null @@ -1,175 +0,0 @@ -# Schemas - -The [JSON schemas](http://json-schema.org/) for the API payloads and responses can be found in [@0xproject/json-schemas](https://github.com/0xProject/0x-monorepo/tree/development/packages/json-schemas). Examples of each payload and response can be found in the library's [test suite](https://github.com/0xProject/0x-monorepo/blob/development/packages/json-schemas/test/schema_test.ts#L1). - -```bash -npm install @0xproject/json-schemas --save -``` - -You can easily validate your API's payloads and responses using the [@0xproject/json-schemas](https://github.com/0xProject/0x-monorepo/tree/development/packages/json-schemas) package: - -```js -import {SchemaValidator, ValidatorResult, schemas} from '@0xproject/json-schemas'; - -const {relayerApiTokenPairsResponseSchema} = schemas; -const validator = new SchemaValidator(); - -const tokenPairsResponse = { - ... -}; -const validatorResult: ValidatorResult = validator.validate(tokenPairsResponse, relayerApiTokenPairsResponseSchema); -``` - -# Pagination - -Requests that return potentially large collections should respond to the **?page** and **?perPage** parameters. For example: - -```bash -$ curl https://api.example-relayer.com/v3/asset_pairs?page=3&perPage=20 -``` - -Page numbering should be 1-indexed, not 0-indexed. If a query provides an unreasonable (ie. too high) `perPage` value, the response can return a validation error as specified in the [errors section](#section/Errors). If the query specifies a `page` that does not exist (ie. there are not enough `records`), the response should just return an empty `records` array. - -All endpoints that are paginated should return a `total`, `page`, `perPage` and a `records` value in the top level of the collection. The value of `total` should be the total number of records for a given query, whereas `records` should be an array representing the response to the query for that page. `page` and `perPage`, are the same values that were specified in the request. See the note in [miscellaneous](#section/Misc.) about formatting `snake_case` vs. `lowerCamelCase`. - -These requests include the [`/v3/asset_pairs`](#operation/getAssetPairs), [`/v3/orders`](#operation/getOrders), [`/v3/fee_recipients`](#operation/getFeeRecipients) and [`/v3/orderbook`](#operation/getOrderbook) endpoints. - -# Link Header - -A [Link Header](https://tools.ietf.org/html/rfc5988) can be included in a response to provide clients with more context about paging -For example: - -```bash -Link: ; rel="next", -; rel="last" -``` - -This `Link` response header contains one or more Hypermedia link relations. - -The possible `rel` values are: - -| Name | Description | -| ----- | ------------------------------------------------------------- | -| next | The link relation for the immediate next page of results. | -| last | The link relation for the last page of results. | -| first | The link relation for the first page of results. | -| prev | The link relation for the immediate previous page of results. | - -# Rate Limits - -Rate limit guidance for clients can be optionally returned in the response headers: - -| Header Name | Description | -| --------------------- | ---------------------------------------------------------------------------- | -| X-RateLimit-Limit | The maximum number of requests you're permitted to make per hour. | -| X-RateLimit-Remaining | The number of requests remaining in the current rate limit window. | -| X-RateLimit-Reset | The time at which the current rate limit window resets in UTC epoch seconds. | - -For example: - -```bash -$ curl -i https://api.example-relayer.com/v3/asset_pairs -HTTP/1.1 200 OK -Date: Mon, 20 Oct 2017 12:30:06 GMT -Status: 200 OK -X-RateLimit-Limit: 60 -X-RateLimit-Remaining: 56 -X-RateLimit-Reset: 1372700873 -``` - -When a rate limit is exceeded, a status of **429 Too Many Requests** should be returned. - -# Errors - -Unless the spec defines otherwise, errors to bad requests should respond with HTTP 4xx or status codes. - -## Common error codes - -| Code | Reason | -| ---- | --------------------------------------- | -| 400 | Bad Request – Invalid request format | -| 404 | Not found | -| 429 | Too many requests - Rate limit exceeded | -| 500 | Internal Server Error | -| 501 | Not Implemented | - -## Error reporting format - -For all **400** responses, see the [error response schema](https://github.com/0xProject/0x-monorepo/blob/development/packages/json-schemas/schemas/relayer_api_error_response_schema.ts#L1). - -```json -{ - "code": 101, - "reason": "Validation failed", - "validationErrors": [ - { - "field": "maker", - "code": 1002, - "reason": "Invalid address" - } - ] -} -``` - -General error codes: - -```bash -100 - Validation Failed -101 - Malformed JSON -102 - Order submission disabled -103 - Throttled -``` - -Validation error codes: - -```bash -1000 - Required field -1001 - Incorrect format -1002 - Invalid address -1003 - Address not supported -1004 - Value out of range -1005 - Invalid signature or hash -1006 - Unsupported option -``` - -# Asset Data Encoding - -As we now support multiple [token transfer proxies](https://github.com/0xProject/0x-protocol-specification/blob/master/v3/v3-specification.md#assetproxy), the identifier of which proxy to use for the token transfer must be encoded, along with the token information. Each proxy in 0x v3 has a unique identifier. If you're using 0x.js there will be helper methods for this encoding and decoding. - -The identifier for the Proxy uses a similar scheme to [ABI function selectors](https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI#function-selector). - -```js -// ERC20 Proxy ID 0xf47261b0 -bytes4(keccak256('ERC20Token(address)')); -// ERC721 Proxy ID 0x02571792 -bytes4(keccak256('ERC721Token(address,uint256)')); -``` - -Asset data is encoded using [ABI encoding](https://solidity.readthedocs.io/en/develop/abi-spec.html). - -For example, encoding the ERC20 token contract (address: 0x1dc4c1cefef38a777b15aa20260a54e584b16c48) using the ERC20 Transfer Proxy (id: 0xf47261b0) would be: - -```bash -0xf47261b00000000000000000000000001dc4c1cefef38a777b15aa20260a54e584b16c48 -``` - -Encoding the ERC721 token contract (address: `0x371b13d97f4bf77d724e78c16b7dc74099f40e84`), token id (id: `99`, which hex encoded is `0x63`) and the ERC721 Transfer Proxy (id: 0x02571792) would be: - -```bash -0x02571792000000000000000000000000371b13d97f4bf77d724e78c16b7dc74099f40e840000000000000000000000000000000000000000000000000000000000000063 -``` - -For more information see [the Asset Proxy](https://github.com/0xProject/0x-protocol-specification/blob/master/v3/v3-specification.md#erc20proxy) section of the v3 spec and the [Ethereum ABI Spec](https://solidity.readthedocs.io/en/develop/abi-spec.html). - -# Meta Data in Order Responses - -In v3 of the standard relayer API we added the `metaData` field. It is meant to provide a standard place for relayers to put optional, custom or non-standard fields that may of interest to the consumer of the API. - -A good example of such a field is `remainingTakerAssetAmount`, which is a convenience field that communicates how much of a 0x order is potentially left to be filled. Unlike the other fields in a 0x order, it is not guaranteed to be correct as it is derived from whatever mechanism the implementer (ie. the relayer) is using. While convenient for prototyping and low stakes situations, we recommend validating the value of the field by checking the state of the blockchain yourself. - -# Misc. - -- All requests and responses should be of **application/json** content type -- All token amounts are sent in amounts of the smallest level of precision (base units). (e.g if a token has 18 decimal places, selling 1 token would show up as selling `'1000000000000000000'` units by this API). -- All addresses are sent as lower-case (non-checksummed) Ethereum addresses with the `0x` prefix. -- All parameters are to be written in `lowerCamelCase`. diff --git a/packages/sra-spec/src/parameters.ts b/packages/sra-spec/src/parameters.ts deleted file mode 100644 index 7915598c53..0000000000 --- a/packages/sra-spec/src/parameters.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { ParameterObject } from '@loopback/openapi-v3-types'; -export const paginationParameters: ParameterObject[] = [ - { - name: 'page', - in: 'query', - description: 'The number of the page to request in the collection.', - example: 3, - schema: { - type: 'number', - default: 1, - }, - }, - { - name: 'perPage', - in: 'query', - description: 'The number of records to return per page.', - example: 10, - schema: { - type: 'number', - default: 100, - }, - }, -]; - -export const generateParameters = (parameters: ParameterObject[], isPaginated: boolean = false): ParameterObject[] => { - const optionalParameters = isPaginated ? paginationParameters : []; - return [...parameters, ...optionalParameters]; -}; diff --git a/packages/sra-spec/src/responses.ts b/packages/sra-spec/src/responses.ts deleted file mode 100644 index cd7352058a..0000000000 --- a/packages/sra-spec/src/responses.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { ResponsesObject } from '@loopback/openapi-v3-types'; - -import { errorResponses } from './errors'; -import { headers } from './headers'; - -export const generateResponses = (schemaName?: string, example?: any, description: string = 'OK'): ResponsesObject => { - const responses = { - '200': { - headers, - description, - content: {}, - }, - ...errorResponses, - }; - if (schemaName) { - responses['200'].content = { - 'application/json': { - schema: { $ref: `#/components/schemas/${schemaName}` }, - example, - }, - }; - } - return responses; -}; diff --git a/packages/sra-spec/tsconfig.json b/packages/sra-spec/tsconfig.json deleted file mode 100644 index 785ed914dd..0000000000 --- a/packages/sra-spec/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../tsconfig", - "compilerOptions": { - "outDir": "lib", - "rootDir": "." - }, - "include": ["./src/**/*", "./test/*", "./build_scripts/*", "./md/*"] -} diff --git a/packages/sra-spec/tslint.json b/packages/sra-spec/tslint.json deleted file mode 100644 index dd9053357e..0000000000 --- a/packages/sra-spec/tslint.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": ["@0x/tslint-config"] -} diff --git a/packages/subproviders/.npmignore b/packages/subproviders/.npmignore deleted file mode 100644 index ea588d4859..0000000000 --- a/packages/subproviders/.npmignore +++ /dev/null @@ -1,9 +0,0 @@ -# Blacklist all files -.* -* -# Whitelist lib -!lib/**/* -# Blacklist tests and publish scripts -/lib/test/* -/lib/monorepo_scripts/ -# Package specific ignore diff --git a/packages/subproviders/CHANGELOG.json b/packages/subproviders/CHANGELOG.json deleted file mode 100644 index b90f83c5f6..0000000000 --- a/packages/subproviders/CHANGELOG.json +++ /dev/null @@ -1,800 +0,0 @@ -[ - { - "timestamp": 1594788383, - "version": "6.1.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "6.1.0", - "changes": [ - { - "note": "Update ganache-core", - "pr": 2545 - } - ], - "timestamp": 1592969527 - }, - { - "timestamp": 1582623685, - "version": "6.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1581204851, - "version": "6.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1580988106, - "version": "6.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1580811564, - "version": "6.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1579682890, - "version": "6.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1578272714, - "version": "6.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1576540892, - "version": "6.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1575931811, - "version": "6.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "6.0.0", - "changes": [ - { - "note": "Adds DebugSubprovider", - "pr": 2329 - } - ], - "timestamp": 1575296764 - }, - { - "version": "5.1.0-beta.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1575290197 - }, - { - "version": "5.1.0-beta.2", - "changes": [ - { - "note": "Adds DebugSubprovider", - "pr": 2329 - } - ], - "timestamp": 1574030254 - }, - { - "version": "5.1.0-beta.1", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1573159180 - }, - { - "version": "5.1.0-beta.0", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1570135330 - }, - { - "timestamp": 1568744790, - "version": "5.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1567521715, - "version": "5.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "5.0.2", - "changes": [ - { - "note": "Updated `MetamaskSubprovider` to use `personal_sign` instead of `eth_sign` to support proxied hardware wallets.", - "pr": 2054 - } - ], - "timestamp": 1566446343 - }, - { - "timestamp": 1565296576, - "version": "5.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "5.0.0", - "changes": [ - { - "note": "Remove eth-lightwallet subprovider" - } - ], - "timestamp": 1564604963 - }, - { - "version": "4.1.2", - "changes": [ - { - "note": "Fix bug in Private Key subprovider causing checksummed tx.origin addresses to be rejected.", - "pr": 1962 - } - ], - "timestamp": 1563957393 - }, - { - "version": "4.1.1", - "changes": [ - { - "note": "Fix bug in Trezor subprovider causing Trezor response to not be hex encoded", - "pr": 1867 - } - ], - "timestamp": 1563006338 - }, - { - "version": "4.1.0", - "changes": [ - { - "note": "Improve performance of Trezor subprovider via caching", - "pr": 1830 - }, - { - "note": "Add Trezor handware wallet subprovider", - "pr": 1431 - } - ], - "timestamp": 1558712885 - }, - { - "timestamp": 1557507213, - "version": "4.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "4.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1554997931 - }, - { - "timestamp": 1553183790, - "version": "4.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "4.0.3", - "changes": [ - { - "note": "Update ganache-core to 2.5.3", - "pr": 1707 - } - ], - "timestamp": 1553091633 - }, - { - "timestamp": 1551479279, - "version": "4.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551220833, - "version": "4.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "4.0.0", - "changes": [ - { - "note": "Add support for EIP1193 providers & Web3.js providers >= 1.0-beta.38", - "pr": 1627 - }, - { - "note": "Update provider params to type SupportedProvider which outlines all supported providers", - "pr": 1627 - } - ], - "timestamp": 1551130135 - }, - { - "timestamp": 1549733923, - "version": "3.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1549547375 - }, - { - "timestamp": 1549452781, - "version": "3.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.0.0", - "changes": [ - { - "note": "Upgrade the bignumber.js to v8.0.2", - "pr": 1517 - }, - { - "note": "Update ganache-core to v2.3.3", - "pr": 1518 - } - ], - "timestamp": 1549373905 - }, - { - "timestamp": 1547561734, - "version": "2.1.11", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547225310, - "version": "2.1.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547040760, - "version": "2.1.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.1.8", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544739608 - }, - { - "version": "2.1.7", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544570656 - }, - { - "timestamp": 1543401373, - "version": "2.1.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542821676, - "version": "2.1.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542208198, - "version": "2.1.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542134075, - "version": "2.1.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542028948, - "version": "2.1.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.1.1", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1541740904 - }, - { - "version": "2.1.0", - "changes": [ - { - "note": "Add `MetamaskSubprovider` to handle inconsistent JSON RPC behaviour", - "pr": 1102 - }, - { - "note": "Add support for `eth_signTypedData` in wallets Mnemonic, Private and EthLightWallet", - "pr": 1102 - }, - { - "note": "Make web3-provider-engine types a 'dependency' so it's available to users of the library", - "pr": 1105 - } - ], - "timestamp": 1539871071 - }, - { - "version": "2.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1538693146 - }, - { - "timestamp": 1538157789, - "version": "2.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537907159, - "version": "2.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537875740, - "version": "2.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537541580, - "version": "2.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1536142250, - "version": "2.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1535377027, - "version": "2.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.0", - "changes": [ - { - "note": "Export types: `PartialTxParams`, `JSONRPCRequestPayloadWithMethod`, `ECSignatureString`, `AccountFetchingConfigs`, `LedgerEthereumClientFactoryAsync`, `OnNextCompleted`, `MnemonicWalletSubproviderConfigs`, LedgerGetAddressResult, `JSONRPCRequestPayload`, `Provider`, `JSONRPCResponsePayload` and `JSONRPCErrorCallback`", - "pr": 924 - } - ], - "timestamp": 1535133899 - }, - { - "timestamp": 1534210131, - "version": "1.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532619515, - "version": "1.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532614997, - "version": "1.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532605697, - "version": "1.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532357734, - "version": "1.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532043000, - "version": "1.0.0", - "changes": [ - { - "note": "Add `RpcSubprovider` with timeout", - "pr": 874 - }, - { - "note": "Add `EthLightwalletSubprovider`", - "pr": 775 - } - ] - }, - { - "timestamp": 1531919263, - "version": "0.10.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1529397769, - "version": "0.10.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1527009133, - "version": "0.10.3", - "changes": [ - { - "note": "Define engine type as Provider in setEngine", - "pr": 675 - } - ] - }, - { - "timestamp": 1527009133, - "version": "0.10.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1525477860, - "version": "0.10.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.10.0", - "changes": [ - { - "note": "Upgrade web3-provider-engine to 14.0.4", - "pr": 555 - }, - { - "note": "Relax `to` validation in base wallet subprovider for transactions that deploy contracts", - "pr": 555 - } - ], - "timestamp": 1525428773 - }, - { - "version": "0.9.0", - "changes": [ - { - "note": "Refactor RedundantRPCSubprovider into RedundantSubprovider where it now accepts an array of subproviders rather then an array of RPC endpoints", - "pr": 500 - }, - { - "note": "Add PrivateKeySubprovider and refactor shared functionality into a base wallet subprovider", - "pr": 506 - }, - { - "note": "Add MnemonicWalletsubprovider, deprecating our truffle-hdwallet-provider fork", - "pr": 507 - }, - { - "note": "Support multiple addresses in ledger and mnemonic wallets", - "pr": 507 - }, - { - "note": "Refactors LedgerSubprovider such that explicitly setting the `pathIndex` is no longer required. Simply set the request `from` address as desired", - "pr": 507 - }, - { - "note": "Renamed derivationPath to baseDerivationPath.", - "pr": 507 - } - ], - "timestamp": 1523462196 - }, - { - "timestamp": 1522673609, - "version": "0.8.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.8.3", - "changes": [ - { - "note": "Introduce `JSONRPCRequestPayloadWithMethod` type", - "pr": 465 - }, - { - "note": "Export `ErrorCallback` type.", - "pr": 465 - } - ], - "timestamp": 1522658513 - }, - { - "version": "0.8.0", - "changes": [ - { - "note": "Export `GanacheSubprovider` and `Subprovider`", - "pr": 426 - }, - { - "note": "Make all subproviders to derive from `Subprovider`", - "pr": 426 - }, - { - "note": "Add types for `NextCallback`, `OnNextCompleted`", - "pr": 426 - }, - { - "note": "Ignore `ganache-core` dependency when using package in a browser environment." - } - ], - "timestamp": 1521298800 - }, - { - "version": "0.7.0", - "changes": [ - { - "note": "Updated legerco packages. Removed node-hid package as a dependency and make it an optional dependency. It is still used in integration tests but is causing problems for users on Linux distros.", - "pr": 437 - } - ], - "timestamp": 1520434800 - }, - { - "version": "0.6.0", - "changes": [ - { - "note": "Move web3 types from being a devDep to a dep since one cannot use this package without it", - "pr": 429 - }, - { - "note": "Add `numberOfAccounts` param to `LedgerSubprovider` method `getAccountsAsync`", - "pr": 432 - } - ], - "timestamp": 1520089200 - }, - { - "version": "0.5.0", - "changes": [ - { - "note": "Add EmptyWalletSubprovider and FakeGasEstimateSubprovider", - "pr": 392 - } - ], - "timestamp": 1518706800 - }, - { - "version": "0.4.1", - "changes": [ - { - "note": "Fix publishing issue where .npmignore was not properly excluding undesired content", - "pr": 389 - } - ], - "timestamp": 1518102000 - }, - { - "version": "0.4.0", - "changes": [ - { - "note": "Added NonceTrackerSubprovider", - "pr": 355 - }, - { - "note": "InjectedWeb3Subprovider accepts a Provider in the constructor, previously it was a Web3 object", - "pr": 363 - } - ], - "timestamp": 1517929200 - }, - { - "version": "0.3.6", - "changes": [ - { - "note": "Return a transaction hash from `_sendTransactionAsync`", - "pr": 303 - } - ], - "timestamp": 1517065200 - }, - { - "version": "0.3.0", - "changes": [ - { - "note": "Allow LedgerSubprovider to handle `eth_sign` in addition to `personal_sign` RPC requests" - } - ], - "timestamp": 1514386800 - }, - { - "version": "0.2.0", - "changes": [ - { - "note": "Improve the performance of address fetching", - "pr": 271 - } - ], - "timestamp": 1513695600 - } -] diff --git a/packages/subproviders/CHANGELOG.md b/packages/subproviders/CHANGELOG.md deleted file mode 100644 index 3af75af988..0000000000 --- a/packages/subproviders/CHANGELOG.md +++ /dev/null @@ -1,336 +0,0 @@ - - -CHANGELOG - -## v6.1.1 - _July 15, 2020_ - - * Dependencies updated - -## v6.1.0 - _June 24, 2020_ - - * Update ganache-core (#2545) - -## v6.0.8 - _February 25, 2020_ - - * Dependencies updated - -## v6.0.7 - _February 8, 2020_ - - * Dependencies updated - -## v6.0.6 - _February 6, 2020_ - - * Dependencies updated - -## v6.0.5 - _February 4, 2020_ - - * Dependencies updated - -## v6.0.4 - _January 22, 2020_ - - * Dependencies updated - -## v6.0.3 - _January 6, 2020_ - - * Dependencies updated - -## v6.0.2 - _December 17, 2019_ - - * Dependencies updated - -## v6.0.1 - _December 9, 2019_ - - * Dependencies updated - -## v6.0.0 - _December 2, 2019_ - - * Adds DebugSubprovider (#2329) - -## v5.1.0-beta.3 - _December 2, 2019_ - - * Dependencies updated - -## v5.1.0-beta.2 - _November 17, 2019_ - - * Adds DebugSubprovider (#2329) - -## v5.1.0-beta.1 - _November 7, 2019_ - - * Dependencies updated - -## v5.1.0-beta.0 - _October 3, 2019_ - - * Dependencies updated - -## v5.0.4 - _September 17, 2019_ - - * Dependencies updated - -## v5.0.3 - _September 3, 2019_ - - * Dependencies updated - -## v5.0.2 - _August 22, 2019_ - - * Updated `MetamaskSubprovider` to use `personal_sign` instead of `eth_sign` to support proxied hardware wallets. (#2054) - -## v5.0.1 - _August 8, 2019_ - - * Dependencies updated - -## v5.0.0 - _July 31, 2019_ - - * Remove eth-lightwallet subprovider - -## v4.1.2 - _July 24, 2019_ - - * Fix bug in Private Key subprovider causing checksummed tx.origin addresses to be rejected. (#1962) - -## v4.1.1 - _July 13, 2019_ - - * Fix bug in Trezor subprovider causing Trezor response to not be hex encoded (#1867) - -## v4.1.0 - _May 24, 2019_ - - * Improve performance of Trezor subprovider via caching (#1830) - * Add Trezor handware wallet subprovider (#1431) - -## v4.0.6 - _May 10, 2019_ - - * Dependencies updated - -## v4.0.5 - _April 11, 2019_ - - * Dependencies updated - -## v4.0.4 - _March 21, 2019_ - - * Dependencies updated - -## v4.0.3 - _March 20, 2019_ - - * Update ganache-core to 2.5.3 (#1707) - -## v4.0.2 - _March 1, 2019_ - - * Dependencies updated - -## v4.0.1 - _February 26, 2019_ - - * Dependencies updated - -## v4.0.0 - _February 25, 2019_ - - * Add support for EIP1193 providers & Web3.js providers >= 1.0-beta.38 (#1627) - * Update provider params to type SupportedProvider which outlines all supported providers (#1627) - -## v3.0.3 - _February 9, 2019_ - - * Dependencies updated - -## v3.0.2 - _February 7, 2019_ - - * Dependencies updated - -## v3.0.1 - _February 6, 2019_ - - * Dependencies updated - -## v3.0.0 - _February 5, 2019_ - - * Upgrade the bignumber.js to v8.0.2 (#1517) - * Update ganache-core to v2.3.3 (#1518) - -## v2.1.11 - _January 15, 2019_ - - * Dependencies updated - -## v2.1.10 - _January 11, 2019_ - - * Dependencies updated - -## v2.1.9 - _January 9, 2019_ - - * Dependencies updated - -## v2.1.8 - _December 13, 2018_ - - * Dependencies updated - -## v2.1.7 - _December 11, 2018_ - - * Dependencies updated - -## v2.1.6 - _November 28, 2018_ - - * Dependencies updated - -## v2.1.5 - _November 21, 2018_ - - * Dependencies updated - -## v2.1.4 - _November 14, 2018_ - - * Dependencies updated - -## v2.1.3 - _November 13, 2018_ - - * Dependencies updated - -## v2.1.2 - _November 12, 2018_ - - * Dependencies updated - -## v2.1.1 - _November 9, 2018_ - - * Dependencies updated - -## v2.1.0 - _October 18, 2018_ - - * Add `MetamaskSubprovider` to handle inconsistent JSON RPC behaviour (#1102) - * Add support for `eth_signTypedData` in wallets Mnemonic, Private and EthLightWallet (#1102) - * Make web3-provider-engine types a 'dependency' so it's available to users of the library (#1105) - -## v2.0.7 - _October 4, 2018_ - - * Dependencies updated - -## v2.0.6 - _September 28, 2018_ - - * Dependencies updated - -## v2.0.5 - _September 25, 2018_ - - * Dependencies updated - -## v2.0.4 - _September 25, 2018_ - - * Dependencies updated - -## v2.0.3 - _September 21, 2018_ - - * Dependencies updated - -## v2.0.2 - _September 5, 2018_ - - * Dependencies updated - -## v2.0.1 - _August 27, 2018_ - - * Dependencies updated - -## v2.0.0 - _August 24, 2018_ - - * Export types: `PartialTxParams`, `JSONRPCRequestPayloadWithMethod`, `ECSignatureString`, `AccountFetchingConfigs`, `LedgerEthereumClientFactoryAsync`, `OnNextCompleted`, `MnemonicWalletSubproviderConfigs`, LedgerGetAddressResult, `JSONRPCRequestPayload`, `Provider`, `JSONRPCResponsePayload` and `JSONRPCErrorCallback` (#924) - -## v1.0.5 - _August 14, 2018_ - - * Dependencies updated - -## v1.0.4 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.3 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.2 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.1 - _July 23, 2018_ - - * Dependencies updated - -## v1.0.0 - _July 19, 2018_ - - * Add `RpcSubprovider` with timeout (#874) - * Add `EthLightwalletSubprovider` (#775) - -## v0.10.6 - _July 18, 2018_ - - * Dependencies updated - -## v0.10.4 - _June 19, 2018_ - - * Dependencies updated - -## v0.10.3 - _May 22, 2018_ - - * Define engine type as Provider in setEngine (#675) - -## v0.10.2 - _May 22, 2018_ - - * Dependencies updated - -## v0.10.1 - _May 4, 2018_ - - * Dependencies updated - -## v0.10.0 - _May 4, 2018_ - - * Upgrade web3-provider-engine to 14.0.4 (#555) - * Relax `to` validation in base wallet subprovider for transactions that deploy contracts (#555) - -## v0.9.0 - _April 11, 2018_ - - * Refactor RedundantRPCSubprovider into RedundantSubprovider where it now accepts an array of subproviders rather then an array of RPC endpoints (#500) - * Add PrivateKeySubprovider and refactor shared functionality into a base wallet subprovider (#506) - * Add MnemonicWalletsubprovider, deprecating our truffle-hdwallet-provider fork (#507) - * Support multiple addresses in ledger and mnemonic wallets (#507) - * Refactors LedgerSubprovider such that explicitly setting the `pathIndex` is no longer required. Simply set the request `from` address as desired (#507) - * Renamed derivationPath to baseDerivationPath. (#507) - -## v0.8.4 - _April 2, 2018_ - - * Dependencies updated - -## v0.8.3 - _April 2, 2018_ - - * Introduce `JSONRPCRequestPayloadWithMethod` type (#465) - * Export `ErrorCallback` type. (#465) - -## v0.8.0 - _March 17, 2018_ - - * Export `GanacheSubprovider` and `Subprovider` (#426) - * Make all subproviders to derive from `Subprovider` (#426) - * Add types for `NextCallback`, `OnNextCompleted` (#426) - * Ignore `ganache-core` dependency when using package in a browser environment. - -## v0.7.0 - _March 7, 2018_ - - * Updated legerco packages. Removed node-hid package as a dependency and make it an optional dependency. It is still used in integration tests but is causing problems for users on Linux distros. (#437) - -## v0.6.0 - _March 3, 2018_ - - * Move web3 types from being a devDep to a dep since one cannot use this package without it (#429) - * Add `numberOfAccounts` param to `LedgerSubprovider` method `getAccountsAsync` (#432) - -## v0.5.0 - _February 15, 2018_ - - * Add EmptyWalletSubprovider and FakeGasEstimateSubprovider (#392) - -## v0.4.1 - _February 8, 2018_ - - * Fix publishing issue where .npmignore was not properly excluding undesired content (#389) - -## v0.4.0 - _February 6, 2018_ - - * Added NonceTrackerSubprovider (#355) - * InjectedWeb3Subprovider accepts a Provider in the constructor, previously it was a Web3 object (#363) - -## v0.3.6 - _January 27, 2018_ - - * Return a transaction hash from `_sendTransactionAsync` (#303) - -## v0.3.0 - _December 27, 2017_ - - * Allow LedgerSubprovider to handle `eth_sign` in addition to `personal_sign` RPC requests - -## v0.2.0 - _December 19, 2017_ - - * Improve the performance of address fetching (#271) diff --git a/packages/subproviders/README.md b/packages/subproviders/README.md deleted file mode 100644 index 5f0fd8135b..0000000000 --- a/packages/subproviders/README.md +++ /dev/null @@ -1,100 +0,0 @@ -## @0x/subproviders - -A few useful web3 subproviders including a LedgerSubprovider useful for adding Ledger Nano S support. - -We have written up a [guide](https://0x.org/docs/guides/web3-provider-explained#web3-provider-examples) article detailing some use cases of this subprovider package. - -### Read the [Documentation](https://0x.org/docs/tools/subproviders). - -## Installation - -``` -yarn add @0x/subproviders -``` - -If your project is in [TypeScript](https://www.typescriptlang.org/), add the following to your `tsconfig.json`: - -```json -"compilerOptions": { - "typeRoots": ["node_modules/@0x/typescript-typings/types", "node_modules/@types"], -} -``` - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install dependencies - -If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: - -```bash -yarn config set workspaces-experimental true -``` - -Then install dependencies - -```bash -yarn install -``` - -### Build - -To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory: - -```bash -PKG=@0x/subproviders yarn build -``` - -Or continuously rebuild on change: - -```bash -PKG=@0x/subproviders yarn watch -``` - -### Clean - -```bash -yarn clean -``` - -### Lint - -```bash -yarn lint -``` - -### Run tests - -#### Unit tests - -```bash -yarn run test:unit -``` - -#### Integration tests - -In order to run the integration tests, make sure you have a Ledger Nano S available. - -- Setup your Ledger with the development mnemonic seed: `concert load couple harbor equip island argue ramp clarify fence smart topic` -- Plug it into your computer -- Unlock the device -- Open the on-device Ethereum app -- Make sure "browser support" and "contract data" are disabled -- Start [TestRPC](https://github.com/trufflesuite/ganache-cli) locally at port `8545` - -Then run: - -``` -yarn test:integration -``` - -**Note:** We assume a derivation path of `m/44'/60'/0'/0` which is already configured in the tests. With this setup and derivation path, your first account should be `0x5409ed021d9299bf6814279a6a1411a7e866a631`, exactly like TestRPC. - -#### All tests - -```bash -yarn run test:all -``` diff --git a/packages/subproviders/coverage/.gitkeep b/packages/subproviders/coverage/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/subproviders/docs/reference.mdx b/packages/subproviders/docs/reference.mdx deleted file mode 100644 index e34aa73ced..0000000000 --- a/packages/subproviders/docs/reference.mdx +++ /dev/null @@ -1,3387 +0,0 @@ - - -# Class: EmptyWalletSubprovider - -This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface. -It intercepts the `eth_accounts` JSON RPC requests and never returns any addresses when queried. - - -## Methods - -### emitPayloadAsync - -▸ **emitPayloadAsync**(`payload`: `Partial`): *`Promise`* - -*Inherited from [Subprovider](#interface-subprovider).[emitPayloadAsync](#emitpayloadasync)* - -*Defined in [subproviders/src/subproviders/subprovider.ts:55](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L55)* - -Emits a JSON RPC payload that will then be handled by the ProviderEngine instance -this subprovider is a part of. The payload will cascade down the subprovider middleware -stack until finding the responsible entity for handling the request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `Partial` | JSON RPC payload | - -**Returns:** *`Promise`* - -JSON RPC response payload - -___ - -### handleRequest - -▸ **handleRequest**(`payload`: `JSONRPCRequestPayload`, `next`: [Callback](#callback), `end`: [ErrorCallback](#errorcallback)): *`Promise`* - -*Overrides [Subprovider](_subproviders_src_subproviders_subprovider_.subprovider.md).[handleRequest](#abstract-handlerequest)* - -*Defined in [subproviders/src/subproviders/empty_wallet_subprovider.ts:21](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/empty_wallet_subprovider.ts#L21)* - -This method conforms to the web3-provider-engine interface. -It is called internally by the ProviderEngine when it is this subproviders -turn to handle a JSON RPC request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `JSONRPCRequestPayload` | JSON RPC payload | -`next` | [Callback](#callback) | Callback to call if this subprovider decides not to handle the request | -`end` | [ErrorCallback](#errorcallback) | Callback to call if subprovider handled the request and wants to pass back the request. | - -**Returns:** *`Promise`* - -___ - -### setEngine - -▸ **setEngine**(`engine`: `Web3ProviderEngine`): *void* - -*Inherited from [Subprovider](#interface-subprovider).[setEngine](#setengine)* - -*Defined in [subproviders/src/subproviders/subprovider.ts:68](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L68)* - -Set's the subprovider's engine to the ProviderEngine it is added to. -This is only called within the ProviderEngine source code, do not call -directly. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`engine` | `Web3ProviderEngine` | The ProviderEngine this subprovider is added to | - -**Returns:** *void* - -
- -# Class: FakeGasEstimateSubprovider - -This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface. -It intercepts the `eth_estimateGas` JSON RPC call and always returns a constant gas amount when queried. - - -## Constructors - - - -\+ **new FakeGasEstimateSubprovider**(`constantGasAmount`: number): *[FakeGasEstimateSubprovider](#class-fakegasestimatesubprovider)* - -*Defined in [subproviders/src/subproviders/fake_gas_estimate_subprovider.ts:17](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/fake_gas_estimate_subprovider.ts#L17)* - -Instantiates an instance of the FakeGasEstimateSubprovider - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`constantGasAmount` | number | The constant gas amount you want returned | - -**Returns:** *[FakeGasEstimateSubprovider](#class-fakegasestimatesubprovider)* - -## Methods - -### emitPayloadAsync - -▸ **emitPayloadAsync**(`payload`: `Partial`): *`Promise`* - -*Inherited from [Subprovider](#interface-subprovider).[emitPayloadAsync](#emitpayloadasync)* - -*Defined in [subproviders/src/subproviders/subprovider.ts:55](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L55)* - -Emits a JSON RPC payload that will then be handled by the ProviderEngine instance -this subprovider is a part of. The payload will cascade down the subprovider middleware -stack until finding the responsible entity for handling the request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `Partial` | JSON RPC payload | - -**Returns:** *`Promise`* - -JSON RPC response payload - -___ - -### handleRequest - -▸ **handleRequest**(`payload`: `JSONRPCRequestPayload`, `next`: [Callback](#callback), `end`: [ErrorCallback](#errorcallback)): *`Promise`* - -*Overrides [Subprovider](_subproviders_src_subproviders_subprovider_.subprovider.md).[handleRequest](#abstract-handlerequest)* - -*Defined in [subproviders/src/subproviders/fake_gas_estimate_subprovider.ts:35](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/fake_gas_estimate_subprovider.ts#L35)* - -This method conforms to the web3-provider-engine interface. -It is called internally by the ProviderEngine when it is this subproviders -turn to handle a JSON RPC request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `JSONRPCRequestPayload` | JSON RPC payload | -`next` | [Callback](#callback) | Callback to call if this subprovider decides not to handle the request | -`end` | [ErrorCallback](#errorcallback) | Callback to call if subprovider handled the request and wants to pass back the request. | - -**Returns:** *`Promise`* - -___ - -### setEngine - -▸ **setEngine**(`engine`: `Web3ProviderEngine`): *void* - -*Inherited from [Subprovider](#interface-subprovider).[setEngine](#setengine)* - -*Defined in [subproviders/src/subproviders/subprovider.ts:68](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L68)* - -Set's the subprovider's engine to the ProviderEngine it is added to. -This is only called within the ProviderEngine source code, do not call -directly. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`engine` | `Web3ProviderEngine` | The ProviderEngine this subprovider is added to | - -**Returns:** *void* - -
- -# Class: GanacheSubprovider - -This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface. -It intercepts all JSON RPC requests and relays them to an in-process ganache instance. - - -## Constructors - - - -\+ **new GanacheSubprovider**(`opts`: `GanacheOpts`): *[GanacheSubprovider](#class-ganachesubprovider)* - -*Defined in [subproviders/src/subproviders/ganache.ts:13](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/ganache.ts#L13)* - -Instantiates a GanacheSubprovider - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`opts` | `GanacheOpts` | The desired opts with which to instantiate the Ganache provider | - -**Returns:** *[GanacheSubprovider](#class-ganachesubprovider)* - -## Methods - -### emitPayloadAsync - -▸ **emitPayloadAsync**(`payload`: `Partial`): *`Promise`* - -*Inherited from [Subprovider](#interface-subprovider).[emitPayloadAsync](#emitpayloadasync)* - -*Defined in [subproviders/src/subproviders/subprovider.ts:55](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L55)* - -Emits a JSON RPC payload that will then be handled by the ProviderEngine instance -this subprovider is a part of. The payload will cascade down the subprovider middleware -stack until finding the responsible entity for handling the request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `Partial` | JSON RPC payload | - -**Returns:** *`Promise`* - -JSON RPC response payload - -___ - -### handleRequest - -▸ **handleRequest**(`payload`: `JSONRPCRequestPayload`, `_next`: [Callback](#callback), `end`: [ErrorCallback](#errorcallback)): *`Promise`* - -*Overrides [Subprovider](_subproviders_src_subproviders_subprovider_.subprovider.md).[handleRequest](#abstract-handlerequest)* - -*Defined in [subproviders/src/subproviders/ganache.ts:31](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/ganache.ts#L31)* - -This method conforms to the web3-provider-engine interface. -It is called internally by the ProviderEngine when it is this subproviders -turn to handle a JSON RPC request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `JSONRPCRequestPayload` | JSON RPC payload | -`_next` | [Callback](#callback) | Callback to call if this subprovider decides not to handle the request | -`end` | [ErrorCallback](#errorcallback) | Callback to call if subprovider handled the request and wants to pass back the request. | - -**Returns:** *`Promise`* - -___ - -### setEngine - -▸ **setEngine**(`engine`: `Web3ProviderEngine`): *void* - -*Inherited from [Subprovider](#interface-subprovider).[setEngine](#setengine)* - -*Defined in [subproviders/src/subproviders/subprovider.ts:68](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L68)* - -Set's the subprovider's engine to the ProviderEngine it is added to. -This is only called within the ProviderEngine source code, do not call -directly. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`engine` | `Web3ProviderEngine` | The ProviderEngine this subprovider is added to | - -**Returns:** *void* - -
- -# Class: LedgerSubprovider - -Subprovider for interfacing with a user's [Ledger Nano S](https://www.ledgerwallet.com/products/ledger-nano-s). -This subprovider intercepts all account related RPC requests (e.g message/transaction signing, etc...) and -re-routes them to a Ledger device plugged into the users computer. - - -## Constructors - - - -\+ **new LedgerSubprovider**(`config`: [LedgerSubproviderConfigs](#interface-ledgersubproviderconfigs)): *[LedgerSubprovider](#class-ledgersubprovider)* - -*Defined in [subproviders/src/subproviders/ledger.ts:41](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/ledger.ts#L41)* - -Instantiates a LedgerSubprovider. Defaults to derivationPath set to `44'/60'/0'`. -TestRPC/Ganache defaults to `m/44'/60'/0'/0`, so set this in the configs if desired. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`config` | [LedgerSubproviderConfigs](#interface-ledgersubproviderconfigs) | Several available configurations | - -**Returns:** *[LedgerSubprovider](#class-ledgersubprovider)* - -LedgerSubprovider instance - -## Methods - -### emitPayloadAsync - -▸ **emitPayloadAsync**(`payload`: `Partial`): *`Promise`* - -*Inherited from [Subprovider](#interface-subprovider).[emitPayloadAsync](#emitpayloadasync)* - -*Defined in [subproviders/src/subproviders/subprovider.ts:55](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L55)* - -Emits a JSON RPC payload that will then be handled by the ProviderEngine instance -this subprovider is a part of. The payload will cascade down the subprovider middleware -stack until finding the responsible entity for handling the request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `Partial` | JSON RPC payload | - -**Returns:** *`Promise`* - -JSON RPC response payload - -___ - -### getAccountsAsync - -▸ **getAccountsAsync**(`numberOfAccounts`: number): *`Promise`* - -*Overrides void* - -*Defined in [subproviders/src/subproviders/ledger.ts:87](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/ledger.ts#L87)* - -Retrieve a users Ledger accounts. The accounts are derived from the derivationPath, -master public key and chain code. Because of this, you can request as many accounts -as you wish and it only requires a single request to the Ledger device. This method -is automatically called when issuing a `eth_accounts` JSON RPC request via your providerEngine -instance. - -**Parameters:** - -Name | Type | Default | Description | ------- | ------ | ------ | ------ | -`numberOfAccounts` | number | DEFAULT_NUM_ADDRESSES_TO_FETCH | Number of accounts to retrieve (default: 10) | - -**Returns:** *`Promise`* - -An array of accounts - -___ - -### getPath - -▸ **getPath**(): *string* - -*Defined in [subproviders/src/subproviders/ledger.ts:68](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/ledger.ts#L68)* - -Retrieve the set derivation path - -**Returns:** *string* - -derivation path - -___ - -### handleRequest - -▸ **handleRequest**(`payload`: `JSONRPCRequestPayload`, `next`: [Callback](#callback), `end`: [ErrorCallback](#errorcallback)): *`Promise`* - - - -*Overrides [Subprovider](_subproviders_src_subproviders_subprovider_.subprovider.md).[handleRequest](#abstract-handlerequest)* - -*Defined in [subproviders/src/subproviders/base_wallet_subprovider.ts:37](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/base_wallet_subprovider.ts#L37)* - -This method conforms to the web3-provider-engine interface. -It is called internally by the ProviderEngine when it is this subproviders -turn to handle a JSON RPC request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `JSONRPCRequestPayload` | JSON RPC payload | -`next` | [Callback](#callback) | Callback to call if this subprovider decides not to handle the request | -`end` | [ErrorCallback](#errorcallback) | Callback to call if subprovider handled the request and wants to pass back the request. | - -**Returns:** *`Promise`* - -___ - -### setEngine - -▸ **setEngine**(`engine`: `Web3ProviderEngine`): *void* - -*Inherited from [Subprovider](#interface-subprovider).[setEngine](#setengine)* - -*Defined in [subproviders/src/subproviders/subprovider.ts:68](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L68)* - -Set's the subprovider's engine to the ProviderEngine it is added to. -This is only called within the ProviderEngine source code, do not call -directly. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`engine` | `Web3ProviderEngine` | The ProviderEngine this subprovider is added to | - -**Returns:** *void* - -___ - -### setPath - -▸ **setPath**(`basDerivationPath`: string): *void* - -*Defined in [subproviders/src/subproviders/ledger.ts:75](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/ledger.ts#L75)* - -Set a desired derivation path when computing the available user addresses - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`basDerivationPath` | string | The desired derivation path (e.g `44'/60'/0'`) | - -**Returns:** *void* - -___ - -### signPersonalMessageAsync - -▸ **signPersonalMessageAsync**(`data`: string, `address`: string): *`Promise`* - -*Overrides void* - -*Defined in [subproviders/src/subproviders/ledger.ts:158](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/ledger.ts#L158)* - -Sign a personal Ethereum signed message. The signing account will be the account -associated with the provided address. -The Ledger adds the Ethereum signed message prefix on-device. If you've added -the LedgerSubprovider to your app's provider, you can simply send an `eth_sign` -or `personal_sign` JSON RPC request, and this method will be called auto-magically. -If you are not using this via a ProviderEngine instance, you can call it directly. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`data` | string | Hex string message to sign | -`address` | string | Address of the account to sign with | - -**Returns:** *`Promise`* - -Signature hex string (order: rsv) - -___ - -### signTransactionAsync - -▸ **signTransactionAsync**(`txParams`: [PartialTxParams](#interface-partialtxparams)): *`Promise`* - -*Overrides void* - -*Defined in [subproviders/src/subproviders/ledger.ts:101](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/ledger.ts#L101)* - -Signs a transaction on the Ledger with the account specificed by the `from` field in txParams. -If you've added the LedgerSubprovider to your app's provider, you can simply send an `eth_sendTransaction` -JSON RPC request, and this method will be called auto-magically. If you are not using this via a ProviderEngine -instance, you can call it directly. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`txParams` | [PartialTxParams](#interface-partialtxparams) | Parameters of the transaction to sign | - -**Returns:** *`Promise`* - -Signed transaction hex string - -___ - -### signTypedDataAsync - -▸ **signTypedDataAsync**(`address`: string, `typedData`: any): *`Promise`* - -*Overrides void* - -*Defined in [subproviders/src/subproviders/ledger.ts:196](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/ledger.ts#L196)* - -eth_signTypedData is currently not supported on Ledger devices. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`address` | string | Address of the account to sign with | -`typedData` | any | - | - -**Returns:** *`Promise`* - -Signature hex string (order: rsv) - -
- -# Class: MetamaskSubprovider - -This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) -subprovider interface and the provider sendAsync interface. -It handles inconsistencies with Metamask implementations of various JSON RPC methods. -It forwards JSON RPC requests involving the domain of a signer (getAccounts, -sendTransaction, signMessage etc...) to the provider instance supplied at instantiation. All other requests -are passed onwards for subsequent subproviders to handle. - - -## Constructors - - - -\+ **new MetamaskSubprovider**(`supportedProvider`: [SupportedProvider](#supportedprovider)): *[MetamaskSubprovider](#class-metamasksubprovider)* - -*Defined in [subproviders/src/subproviders/metamask_subprovider.ts:19](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/metamask_subprovider.ts#L19)* - -Instantiates a new MetamaskSubprovider - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`supportedProvider` | [SupportedProvider](#supportedprovider) | Web3 provider that should handle all user account related requests | - -**Returns:** *[MetamaskSubprovider](#class-metamasksubprovider)* - -## Methods - -### emitPayloadAsync - -▸ **emitPayloadAsync**(`payload`: `Partial`): *`Promise`* - -*Inherited from [Subprovider](#interface-subprovider).[emitPayloadAsync](#emitpayloadasync)* - -*Defined in [subproviders/src/subproviders/subprovider.ts:55](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L55)* - -Emits a JSON RPC payload that will then be handled by the ProviderEngine instance -this subprovider is a part of. The payload will cascade down the subprovider middleware -stack until finding the responsible entity for handling the request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `Partial` | JSON RPC payload | - -**Returns:** *`Promise`* - -JSON RPC response payload - -___ - -### handleRequest - -▸ **handleRequest**(`payload`: `JSONRPCRequestPayload`, `next`: [Callback](#callback), `end`: [ErrorCallback](#errorcallback)): *`Promise`* - -*Overrides [Subprovider](_subproviders_src_subproviders_subprovider_.subprovider.md).[handleRequest](#abstract-handlerequest)* - -*Defined in [subproviders/src/subproviders/metamask_subprovider.ts:39](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/metamask_subprovider.ts#L39)* - -This method conforms to the web3-provider-engine interface. -It is called internally by the ProviderEngine when it is this subproviders -turn to handle a JSON RPC request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `JSONRPCRequestPayload` | JSON RPC payload | -`next` | [Callback](#callback) | Callback to call if this subprovider decides not to handle the request | -`end` | [ErrorCallback](#errorcallback) | Callback to call if subprovider handled the request and wants to pass back the request. | - -**Returns:** *`Promise`* - -___ - -### sendAsync - -▸ **sendAsync**(`payload`: `JSONRPCRequestPayload`, `callback`: [ErrorCallback](#errorcallback)): *void* - -*Defined in [subproviders/src/subproviders/metamask_subprovider.ts:117](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/metamask_subprovider.ts#L117)* - -This method conforms to the provider sendAsync interface. -Allowing the MetamaskSubprovider to be used as a generic provider (outside of Web3ProviderEngine) with the -addition of wrapping the inconsistent Metamask behaviour - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `JSONRPCRequestPayload` | JSON RPC payload | -`callback` | [ErrorCallback](#errorcallback) | - | - -**Returns:** *void* - -The contents nested under the result key of the response body - -___ - -### setEngine - -▸ **setEngine**(`engine`: `Web3ProviderEngine`): *void* - -*Inherited from [Subprovider](#interface-subprovider).[setEngine](#setengine)* - -*Defined in [subproviders/src/subproviders/subprovider.ts:68](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L68)* - -Set's the subprovider's engine to the ProviderEngine it is added to. -This is only called within the ProviderEngine source code, do not call -directly. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`engine` | `Web3ProviderEngine` | The ProviderEngine this subprovider is added to | - -**Returns:** *void* - -
- -# Class: MnemonicWalletSubprovider - -This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface. -This subprovider intercepts all account related RPC requests (e.g message/transaction signing, etc...) and handles -all requests with accounts derived from the supplied mnemonic. - - -## Constructors - - - -\+ **new MnemonicWalletSubprovider**(`config`: [MnemonicWalletSubproviderConfigs](#interface-mnemonicwalletsubproviderconfigs)): *[MnemonicWalletSubprovider](#class-mnemonicwalletsubprovider)* - -*Defined in [subproviders/src/subproviders/mnemonic_wallet.ts:27](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/mnemonic_wallet.ts#L27)* - -Instantiates a MnemonicWalletSubprovider. Defaults to baseDerivationPath set to `44'/60'/0'/0`. -This is the default in TestRPC/Ganache, it can be overridden if desired. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`config` | [MnemonicWalletSubproviderConfigs](#interface-mnemonicwalletsubproviderconfigs) | Configuration for the mnemonic wallet, must contain the mnemonic | - -**Returns:** *[MnemonicWalletSubprovider](#class-mnemonicwalletsubprovider)* - -MnemonicWalletSubprovider instance - -## Methods - -### emitPayloadAsync - -▸ **emitPayloadAsync**(`payload`: `Partial`): *`Promise`* - -*Inherited from [Subprovider](#interface-subprovider).[emitPayloadAsync](#emitpayloadasync)* - -*Defined in [subproviders/src/subproviders/subprovider.ts:55](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L55)* - -Emits a JSON RPC payload that will then be handled by the ProviderEngine instance -this subprovider is a part of. The payload will cascade down the subprovider middleware -stack until finding the responsible entity for handling the request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `Partial` | JSON RPC payload | - -**Returns:** *`Promise`* - -JSON RPC response payload - -___ - -### getAccountsAsync - -▸ **getAccountsAsync**(`numberOfAccounts`: number): *`Promise`* - -*Overrides void* - -*Defined in [subproviders/src/subproviders/mnemonic_wallet.ts:70](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/mnemonic_wallet.ts#L70)* - -Retrieve the accounts associated with the mnemonic. -This method is implicitly called when issuing a `eth_accounts` JSON RPC request -via your providerEngine instance. - -**Parameters:** - -Name | Type | Default | Description | ------- | ------ | ------ | ------ | -`numberOfAccounts` | number | DEFAULT_NUM_ADDRESSES_TO_FETCH | Number of accounts to retrieve (default: 10) | - -**Returns:** *`Promise`* - -An array of accounts - -___ - -### getPath - -▸ **getPath**(): *string* - -*Defined in [subproviders/src/subproviders/mnemonic_wallet.ts:52](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/mnemonic_wallet.ts#L52)* - -Retrieve the set derivation path - -**Returns:** *string* - -derivation path - -___ - -### handleRequest - -▸ **handleRequest**(`payload`: `JSONRPCRequestPayload`, `next`: [Callback](#callback), `end`: [ErrorCallback](#errorcallback)): *`Promise`* - - - -*Overrides [Subprovider](_subproviders_src_subproviders_subprovider_.subprovider.md).[handleRequest](#abstract-handlerequest)* - -*Defined in [subproviders/src/subproviders/base_wallet_subprovider.ts:37](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/base_wallet_subprovider.ts#L37)* - -This method conforms to the web3-provider-engine interface. -It is called internally by the ProviderEngine when it is this subproviders -turn to handle a JSON RPC request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `JSONRPCRequestPayload` | JSON RPC payload | -`next` | [Callback](#callback) | Callback to call if this subprovider decides not to handle the request | -`end` | [ErrorCallback](#errorcallback) | Callback to call if subprovider handled the request and wants to pass back the request. | - -**Returns:** *`Promise`* - -___ - -### setEngine - -▸ **setEngine**(`engine`: `Web3ProviderEngine`): *void* - -*Inherited from [Subprovider](#interface-subprovider).[setEngine](#setengine)* - -*Defined in [subproviders/src/subproviders/subprovider.ts:68](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L68)* - -Set's the subprovider's engine to the ProviderEngine it is added to. -This is only called within the ProviderEngine source code, do not call -directly. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`engine` | `Web3ProviderEngine` | The ProviderEngine this subprovider is added to | - -**Returns:** *void* - -___ - -### setPath - -▸ **setPath**(`baseDerivationPath`: string): *void* - -*Defined in [subproviders/src/subproviders/mnemonic_wallet.ts:59](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/mnemonic_wallet.ts#L59)* - -Set a desired derivation path when computing the available user addresses - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`baseDerivationPath` | string | The desired derivation path (e.g `44'/60'/0'`) | - -**Returns:** *void* - -___ - -### signPersonalMessageAsync - -▸ **signPersonalMessageAsync**(`data`: string, `address`: string): *`Promise`* - -*Overrides void* - -*Defined in [subproviders/src/subproviders/mnemonic_wallet.ts:102](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/mnemonic_wallet.ts#L102)* - -Sign a personal Ethereum signed message. The signing account will be the account -associated with the provided address. If you've added the MnemonicWalletSubprovider to -your app's provider, you can simply send an `eth_sign` or `personal_sign` JSON RPC request, -and this method will be called auto-magically. If you are not using this via a ProviderEngine -instance, you can call it directly. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`data` | string | Hex string message to sign | -`address` | string | Address of the account to sign with | - -**Returns:** *`Promise`* - -Signature hex string (order: rsv) - -___ - -### signTransactionAsync - -▸ **signTransactionAsync**(`txParams`: [PartialTxParams](#interface-partialtxparams)): *`Promise`* - -*Overrides void* - -*Defined in [subproviders/src/subproviders/mnemonic_wallet.ts:84](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/mnemonic_wallet.ts#L84)* - -Signs a transaction with the account specificed by the `from` field in txParams. -If you've added this Subprovider to your app's provider, you can simply send -an `eth_sendTransaction` JSON RPC request, and this method will be called auto-magically. -If you are not using this via a ProviderEngine instance, you can call it directly. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`txParams` | [PartialTxParams](#interface-partialtxparams) | Parameters of the transaction to sign | - -**Returns:** *`Promise`* - -Signed transaction hex string - -___ - -### signTypedDataAsync - -▸ **signTypedDataAsync**(`address`: string, `typedData`: `EIP712TypedData`): *`Promise`* - -*Overrides void* - -*Defined in [subproviders/src/subproviders/mnemonic_wallet.ts:122](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/mnemonic_wallet.ts#L122)* - -Sign an EIP712 Typed Data message. The signing account will be the account -associated with the provided address. If you've added this MnemonicWalletSubprovider to -your app's provider, you can simply send an `eth_signTypedData` JSON RPC request, and -this method will be called auto-magically. If you are not using this via a ProviderEngine - instance, you can call it directly. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`address` | string | Address of the account to sign with | -`typedData` | `EIP712TypedData` | - | - -**Returns:** *`Promise`* - -Signature hex string (order: rsv) - -
- -# Class: NonceTrackerSubprovider - -This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface. -It is heavily inspired by the [NonceSubprovider](https://github.com/MetaMask/provider-engine/blob/master/subproviders/nonce-tracker.js). -We added the additional feature of clearing the cached nonce value when a `nonce value too low` error occurs. - - -## Methods - -### emitPayloadAsync - -▸ **emitPayloadAsync**(`payload`: `Partial`): *`Promise`* - -*Inherited from [Subprovider](#interface-subprovider).[emitPayloadAsync](#emitpayloadasync)* - -*Defined in [subproviders/src/subproviders/subprovider.ts:55](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L55)* - -Emits a JSON RPC payload that will then be handled by the ProviderEngine instance -this subprovider is a part of. The payload will cascade down the subprovider middleware -stack until finding the responsible entity for handling the request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `Partial` | JSON RPC payload | - -**Returns:** *`Promise`* - -JSON RPC response payload - -___ - -### handleRequest - -▸ **handleRequest**(`payload`: `JSONRPCRequestPayload`, `next`: [NextCallback](#nextcallback), `end`: [ErrorCallback](#errorcallback)): *`Promise`* - -*Overrides [Subprovider](_subproviders_src_subproviders_subprovider_.subprovider.md).[handleRequest](#abstract-handlerequest)* - -*Defined in [subproviders/src/subproviders/nonce_tracker.ts:57](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/nonce_tracker.ts#L57)* - -This method conforms to the web3-provider-engine interface. -It is called internally by the ProviderEngine when it is this subproviders -turn to handle a JSON RPC request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `JSONRPCRequestPayload` | JSON RPC payload | -`next` | [NextCallback](#nextcallback) | Callback to call if this subprovider decides not to handle the request | -`end` | [ErrorCallback](#errorcallback) | Callback to call if subprovider handled the request and wants to pass back the request. | - -**Returns:** *`Promise`* - -___ - -### setEngine - -▸ **setEngine**(`engine`: `Web3ProviderEngine`): *void* - -*Inherited from [Subprovider](#interface-subprovider).[setEngine](#setengine)* - -*Defined in [subproviders/src/subproviders/subprovider.ts:68](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L68)* - -Set's the subprovider's engine to the ProviderEngine it is added to. -This is only called within the ProviderEngine source code, do not call -directly. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`engine` | `Web3ProviderEngine` | The ProviderEngine this subprovider is added to | - -**Returns:** *void* - -
- -# Class: PrivateKeyWalletSubprovider - -This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface. -This subprovider intercepts all account related RPC requests (e.g message/transaction signing, etc...) and handles -all requests with the supplied Ethereum private key. - - -## Constructors - - - -\+ **new PrivateKeyWalletSubprovider**(`privateKey`: string): *[PrivateKeyWalletSubprovider](#class-privatekeywalletsubprovider)* - -*Defined in [subproviders/src/subproviders/private_key_wallet.ts:19](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/private_key_wallet.ts#L19)* - -Instantiates a PrivateKeyWalletSubprovider. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`privateKey` | string | The corresponding private key to an Ethereum address | - -**Returns:** *[PrivateKeyWalletSubprovider](#class-privatekeywalletsubprovider)* - -PrivateKeyWalletSubprovider instance - -## Methods - -### emitPayloadAsync - -▸ **emitPayloadAsync**(`payload`: `Partial`): *`Promise`* - -*Inherited from [Subprovider](#interface-subprovider).[emitPayloadAsync](#emitpayloadasync)* - -*Defined in [subproviders/src/subproviders/subprovider.ts:55](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L55)* - -Emits a JSON RPC payload that will then be handled by the ProviderEngine instance -this subprovider is a part of. The payload will cascade down the subprovider middleware -stack until finding the responsible entity for handling the request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `Partial` | JSON RPC payload | - -**Returns:** *`Promise`* - -JSON RPC response payload - -___ - -### getAccountsAsync - -▸ **getAccountsAsync**(): *`Promise`* - -*Overrides void* - -*Defined in [subproviders/src/subproviders/private_key_wallet.ts:37](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/private_key_wallet.ts#L37)* - -Retrieve the account associated with the supplied private key. -This method is implicitly called when issuing a `eth_accounts` JSON RPC request -via your providerEngine instance. - -**Returns:** *`Promise`* - -An array of accounts - -___ - -### handleRequest - -▸ **handleRequest**(`payload`: `JSONRPCRequestPayload`, `next`: [Callback](#callback), `end`: [ErrorCallback](#errorcallback)): *`Promise`* - - - -*Overrides [Subprovider](_subproviders_src_subproviders_subprovider_.subprovider.md).[handleRequest](#abstract-handlerequest)* - -*Defined in [subproviders/src/subproviders/base_wallet_subprovider.ts:37](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/base_wallet_subprovider.ts#L37)* - -This method conforms to the web3-provider-engine interface. -It is called internally by the ProviderEngine when it is this subproviders -turn to handle a JSON RPC request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `JSONRPCRequestPayload` | JSON RPC payload | -`next` | [Callback](#callback) | Callback to call if this subprovider decides not to handle the request | -`end` | [ErrorCallback](#errorcallback) | Callback to call if subprovider handled the request and wants to pass back the request. | - -**Returns:** *`Promise`* - -___ - -### setEngine - -▸ **setEngine**(`engine`: `Web3ProviderEngine`): *void* - -*Inherited from [Subprovider](#interface-subprovider).[setEngine](#setengine)* - -*Defined in [subproviders/src/subproviders/subprovider.ts:68](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L68)* - -Set's the subprovider's engine to the ProviderEngine it is added to. -This is only called within the ProviderEngine source code, do not call -directly. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`engine` | `Web3ProviderEngine` | The ProviderEngine this subprovider is added to | - -**Returns:** *void* - -___ - -### signPersonalMessageAsync - -▸ **signPersonalMessageAsync**(`data`: string, `address`: string): *`Promise`* - -*Overrides void* - -*Defined in [subproviders/src/subproviders/private_key_wallet.ts:72](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/private_key_wallet.ts#L72)* - -Sign a personal Ethereum signed message. The signing address will be calculated from the private key. -The address must be provided it must match the address calculated from the private key. -If you've added this Subprovider to your app's provider, you can simply send an `eth_sign` -or `personal_sign` JSON RPC request, and this method will be called auto-magically. -If you are not using this via a ProviderEngine instance, you can call it directly. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`data` | string | Hex string message to sign | -`address` | string | Address of the account to sign with | - -**Returns:** *`Promise`* - -Signature hex string (order: rsv) - -___ - -### signTransactionAsync - -▸ **signTransactionAsync**(`txParams`: [PartialTxParams](#interface-partialtxparams)): *`Promise`* - -*Overrides void* - -*Defined in [subproviders/src/subproviders/private_key_wallet.ts:48](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/private_key_wallet.ts#L48)* - -Sign a transaction with the private key. If you've added this Subprovider to your -app's provider, you can simply send an `eth_sendTransaction` JSON RPC request, and -this method will be called auto-magically. If you are not using this via a ProviderEngine -instance, you can call it directly. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`txParams` | [PartialTxParams](#interface-partialtxparams) | Parameters of the transaction to sign | - -**Returns:** *`Promise`* - -Signed transaction hex string - -___ - -### signTypedDataAsync - -▸ **signTypedDataAsync**(`address`: string, `typedData`: `EIP712TypedData`): *`Promise`* - -*Overrides void* - -*Defined in [subproviders/src/subproviders/private_key_wallet.ts:99](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/private_key_wallet.ts#L99)* - -Sign an EIP712 Typed Data message. The signing address will be calculated from the private key. -The address must be provided it must match the address calculated from the private key. -If you've added this Subprovider to your app's provider, you can simply send an `eth_signTypedData` -JSON RPC request, and this method will be called auto-magically. -If you are not using this via a ProviderEngine instance, you can call it directly. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`address` | string | Address of the account to sign with | -`typedData` | `EIP712TypedData` | - | - -**Returns:** *`Promise`* - -Signature hex string (order: rsv) - -
- -# Class: RedundantSubprovider - -This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface. -It attempts to handle each JSON RPC request by sequentially attempting to receive a valid response from one of a -set of JSON RPC endpoints. - - -## Constructors - - - -\+ **new RedundantSubprovider**(`subproviders`: [Subprovider](_subproviders_src_subproviders_subprovider_.subprovider.md)[]): *[RedundantSubprovider](#class-redundantsubprovider)* - -*Defined in [subproviders/src/subproviders/redundant_subprovider.ts:33](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/redundant_subprovider.ts#L33)* - -Instantiates a new RedundantSubprovider - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`subproviders` | [Subprovider](#class-subprovider)[] | Subproviders to attempt the request with | - -**Returns:** *[RedundantSubprovider](#class-redundantsubprovider)* - -## Methods - -### emitPayloadAsync - -▸ **emitPayloadAsync**(`payload`: `Partial`): *`Promise`* - -*Inherited from [Subprovider](#interface-subprovider).[emitPayloadAsync](#emitpayloadasync)* - -*Defined in [subproviders/src/subproviders/subprovider.ts:55](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L55)* - -Emits a JSON RPC payload that will then be handled by the ProviderEngine instance -this subprovider is a part of. The payload will cascade down the subprovider middleware -stack until finding the responsible entity for handling the request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `Partial` | JSON RPC payload | - -**Returns:** *`Promise`* - -JSON RPC response payload - -___ - -### handleRequest - -▸ **handleRequest**(`payload`: `JSONRPCRequestPayload`, `next`: [Callback](#callback), `end`: function): *`Promise`* - -*Overrides [Subprovider](_subproviders_src_subproviders_subprovider_.subprovider.md).[handleRequest](#abstract-handlerequest)* - -*Defined in [subproviders/src/subproviders/redundant_subprovider.ts:51](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/redundant_subprovider.ts#L51)* - -This method conforms to the web3-provider-engine interface. -It is called internally by the ProviderEngine when it is this subproviders -turn to handle a JSON RPC request. - -**Parameters:** - -▪ **payload**: *`JSONRPCRequestPayload`* - -JSON RPC payload - -▪ **next**: *[Callback](#callback)* - -Callback to call if this subprovider decides not to handle the request - -▪ **end**: *function* - -Callback to call if subprovider handled the request and wants to pass back the request. - -▸ (`err`: `Error` | null, `data?`: any): *void* - -**Parameters:** - -Name | Type | ------- | ------ | -`err` | `Error` \| null | -`data?` | any | - -**Returns:** *`Promise`* - -___ - -### setEngine - -▸ **setEngine**(`engine`: `Web3ProviderEngine`): *void* - -*Inherited from [Subprovider](#interface-subprovider).[setEngine](#setengine)* - -*Defined in [subproviders/src/subproviders/subprovider.ts:68](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L68)* - -Set's the subprovider's engine to the ProviderEngine it is added to. -This is only called within the ProviderEngine source code, do not call -directly. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`engine` | `Web3ProviderEngine` | The ProviderEngine this subprovider is added to | - -**Returns:** *void* - -
- -# Class: RPCSubprovider - -This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface. -It forwards on JSON RPC requests to the supplied `rpcUrl` endpoint - - -## Constructors - - - -\+ **new RPCSubprovider**(`rpcUrl`: string, `requestTimeoutMs`: number): *[RPCSubprovider](#class-rpcsubprovider)* - -*Defined in [subproviders/src/subproviders/rpc_subprovider.ts:17](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/rpc_subprovider.ts#L17)* - -**Parameters:** - -Name | Type | Default | Description | ------- | ------ | ------ | ------ | -`rpcUrl` | string | - | URL to the backing Ethereum node to which JSON RPC requests should be sent | -`requestTimeoutMs` | number | 20000 | Amount of miliseconds to wait before timing out the JSON RPC request | - -**Returns:** *[RPCSubprovider](#class-rpcsubprovider)* - -## Methods - -### emitPayloadAsync - -▸ **emitPayloadAsync**(`payload`: `Partial`): *`Promise`* - -*Inherited from [Subprovider](#interface-subprovider).[emitPayloadAsync](#emitpayloadasync)* - -*Defined in [subproviders/src/subproviders/subprovider.ts:55](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L55)* - -Emits a JSON RPC payload that will then be handled by the ProviderEngine instance -this subprovider is a part of. The payload will cascade down the subprovider middleware -stack until finding the responsible entity for handling the request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `Partial` | JSON RPC payload | - -**Returns:** *`Promise`* - -JSON RPC response payload - -___ - -### handleRequest - -▸ **handleRequest**(`payload`: `JSONRPCRequestPayload`, `_next`: [Callback](#callback), `end`: [ErrorCallback](#errorcallback)): *`Promise`* - -*Overrides [Subprovider](_subproviders_src_subproviders_subprovider_.subprovider.md).[handleRequest](#abstract-handlerequest)* - -*Defined in [subproviders/src/subproviders/rpc_subprovider.ts:38](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/rpc_subprovider.ts#L38)* - -This method conforms to the web3-provider-engine interface. -It is called internally by the ProviderEngine when it is this subproviders -turn to handle a JSON RPC request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `JSONRPCRequestPayload` | JSON RPC payload | -`_next` | [Callback](#callback) | Callback to call if this subprovider decides not to handle the request | -`end` | [ErrorCallback](#errorcallback) | Callback to call if subprovider handled the request and wants to pass back the request. | - -**Returns:** *`Promise`* - -___ - -### setEngine - -▸ **setEngine**(`engine`: `Web3ProviderEngine`): *void* - -*Inherited from [Subprovider](#interface-subprovider).[setEngine](#setengine)* - -*Defined in [subproviders/src/subproviders/subprovider.ts:68](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L68)* - -Set's the subprovider's engine to the ProviderEngine it is added to. -This is only called within the ProviderEngine source code, do not call -directly. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`engine` | `Web3ProviderEngine` | The ProviderEngine this subprovider is added to | - -**Returns:** *void* - -
- -# Class: SignerSubprovider - -This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) -subprovider interface. It forwards JSON RPC requests involving the domain of a signer (getAccounts, -sendTransaction, signMessage etc...) to the provider instance supplied at instantiation. All other requests -are passed onwards for subsequent subproviders to handle. - - -## Constructors - - - -\+ **new SignerSubprovider**(`supportedProvider`: [SupportedProvider](#supportedprovider)): *[SignerSubprovider](#class-signersubprovider)* - -*Defined in [subproviders/src/subproviders/signer.ts:15](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/signer.ts#L15)* - -Instantiates a new SignerSubprovider. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`supportedProvider` | [SupportedProvider](#supportedprovider) | Web3 provider that should handle all user account related requests | - -**Returns:** *[SignerSubprovider](#class-signersubprovider)* - -## Methods - -### emitPayloadAsync - -▸ **emitPayloadAsync**(`payload`: `Partial`): *`Promise`* - -*Inherited from [Subprovider](#interface-subprovider).[emitPayloadAsync](#emitpayloadasync)* - -*Defined in [subproviders/src/subproviders/subprovider.ts:55](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L55)* - -Emits a JSON RPC payload that will then be handled by the ProviderEngine instance -this subprovider is a part of. The payload will cascade down the subprovider middleware -stack until finding the responsible entity for handling the request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `Partial` | JSON RPC payload | - -**Returns:** *`Promise`* - -JSON RPC response payload - -___ - -### handleRequest - -▸ **handleRequest**(`payload`: `JSONRPCRequestPayload`, `next`: [Callback](#callback), `end`: [ErrorCallback](#errorcallback)): *`Promise`* - -*Overrides [Subprovider](_subproviders_src_subproviders_subprovider_.subprovider.md).[handleRequest](#abstract-handlerequest)* - -*Defined in [subproviders/src/subproviders/signer.ts:33](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/signer.ts#L33)* - -This method conforms to the web3-provider-engine interface. -It is called internally by the ProviderEngine when it is this subproviders -turn to handle a JSON RPC request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `JSONRPCRequestPayload` | JSON RPC payload | -`next` | [Callback](#callback) | Callback to call if this subprovider decides not to handle the request | -`end` | [ErrorCallback](#errorcallback) | Callback to call if subprovider handled the request and wants to pass back the request. | - -**Returns:** *`Promise`* - -___ - -### setEngine - -▸ **setEngine**(`engine`: `Web3ProviderEngine`): *void* - -*Inherited from [Subprovider](#interface-subprovider).[setEngine](#setengine)* - -*Defined in [subproviders/src/subproviders/subprovider.ts:68](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L68)* - -Set's the subprovider's engine to the ProviderEngine it is added to. -This is only called within the ProviderEngine source code, do not call -directly. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`engine` | `Web3ProviderEngine` | The ProviderEngine this subprovider is added to | - -**Returns:** *void* - -
- -# Class: Subprovider - -A altered version of the base class Subprovider found in [web3-provider-engine](https://github.com/MetaMask/provider-engine). -This one has an async/await `emitPayloadAsync` and also defined types. - - -## Methods - -### emitPayloadAsync - -▸ **emitPayloadAsync**(`payload`: `Partial`): *`Promise`* - -*Defined in [subproviders/src/subproviders/subprovider.ts:55](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L55)* - -Emits a JSON RPC payload that will then be handled by the ProviderEngine instance -this subprovider is a part of. The payload will cascade down the subprovider middleware -stack until finding the responsible entity for handling the request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `Partial` | JSON RPC payload | - -**Returns:** *`Promise`* - -JSON RPC response payload - -___ - -### `Abstract` handleRequest - -▸ **handleRequest**(`payload`: `JSONRPCRequestPayload`, `next`: [Callback](#callback), `end`: [ErrorCallback](#errorcallback)): *`Promise`* - -*Defined in [subproviders/src/subproviders/subprovider.ts:42](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L42)* - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `JSONRPCRequestPayload` | JSON RPC request payload | -`next` | [Callback](#callback) | A callback to pass the request to the next subprovider in the stack | -`end` | [ErrorCallback](#errorcallback) | A callback called once the subprovider is done handling the request | - -**Returns:** *`Promise`* - -___ - -### setEngine - -▸ **setEngine**(`engine`: `Web3ProviderEngine`): *void* - -*Defined in [subproviders/src/subproviders/subprovider.ts:68](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L68)* - -Set's the subprovider's engine to the ProviderEngine it is added to. -This is only called within the ProviderEngine source code, do not call -directly. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`engine` | `Web3ProviderEngine` | The ProviderEngine this subprovider is added to | - -**Returns:** *void* - -
- -# Class: TrezorSubprovider - - -## Constructors - - - -\+ **new TrezorSubprovider**(`config`: [TrezorSubproviderConfig](#interface-trezorsubproviderconfig)): *[TrezorSubprovider](#class-trezorsubprovider)* - -*Defined in [subproviders/src/subproviders/trezor.ts:32](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/trezor.ts#L32)* - -Instantiates a TrezorSubprovider. Defaults to private key path set to `44'/60'/0'/0/`. -Must be initialized with trezor-connect API module https://github.com/trezor/connect. - -**Parameters:** - -Name | Type | ------- | ------ | -`config` | [TrezorSubproviderConfig](#interface-trezorsubproviderconfig) | - -**Returns:** *[TrezorSubprovider](#class-trezorsubprovider)* - -TrezorSubprovider instance - -## Methods - -### emitPayloadAsync - -▸ **emitPayloadAsync**(`payload`: `Partial`): *`Promise`* - -*Inherited from [Subprovider](#interface-subprovider).[emitPayloadAsync](#emitpayloadasync)* - -*Defined in [subproviders/src/subproviders/subprovider.ts:55](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L55)* - -Emits a JSON RPC payload that will then be handled by the ProviderEngine instance -this subprovider is a part of. The payload will cascade down the subprovider middleware -stack until finding the responsible entity for handling the request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `Partial` | JSON RPC payload | - -**Returns:** *`Promise`* - -JSON RPC response payload - -___ - -### getAccountsAsync - -▸ **getAccountsAsync**(`numberOfAccounts`: number): *`Promise`* - -*Overrides void* - -*Defined in [subproviders/src/subproviders/trezor.ts:56](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/trezor.ts#L56)* - -Retrieve a users Trezor account. This method is automatically called -when issuing a `eth_accounts` JSON RPC request via your providerEngine -instance. - -**Parameters:** - -Name | Type | Default | ------- | ------ | ------ | -`numberOfAccounts` | number | DEFAULT_NUM_ADDRESSES_TO_FETCH | - -**Returns:** *`Promise`* - -An array of accounts - -___ - -### handleRequest - -▸ **handleRequest**(`payload`: `JSONRPCRequestPayload`, `next`: [Callback](#callback), `end`: [ErrorCallback](#errorcallback)): *`Promise`* - - - -*Overrides [Subprovider](_subproviders_src_subproviders_subprovider_.subprovider.md).[handleRequest](#abstract-handlerequest)* - -*Defined in [subproviders/src/subproviders/base_wallet_subprovider.ts:37](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/base_wallet_subprovider.ts#L37)* - -This method conforms to the web3-provider-engine interface. -It is called internally by the ProviderEngine when it is this subproviders -turn to handle a JSON RPC request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `JSONRPCRequestPayload` | JSON RPC payload | -`next` | [Callback](#callback) | Callback to call if this subprovider decides not to handle the request | -`end` | [ErrorCallback](#errorcallback) | Callback to call if subprovider handled the request and wants to pass back the request. | - -**Returns:** *`Promise`* - -___ - -### setEngine - -▸ **setEngine**(`engine`: `Web3ProviderEngine`): *void* - -*Inherited from [Subprovider](#interface-subprovider).[setEngine](#setengine)* - -*Defined in [subproviders/src/subproviders/subprovider.ts:68](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L68)* - -Set's the subprovider's engine to the ProviderEngine it is added to. -This is only called within the ProviderEngine source code, do not call -directly. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`engine` | `Web3ProviderEngine` | The ProviderEngine this subprovider is added to | - -**Returns:** *void* - -___ - -### signPersonalMessageAsync - -▸ **signPersonalMessageAsync**(`data`: string, `address`: string): *`Promise`* - -*Overrides void* - -*Defined in [subproviders/src/subproviders/trezor.ts:129](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/trezor.ts#L129)* - -Sign a personal Ethereum signed message. The signing account will be the account -associated with the provided address. If you've added the TrezorSubprovider to -your app's provider, you can simply send an `eth_sign` or `personal_sign` JSON RPC -request, and this method will be called auto-magically. -If you are not using this via a ProviderEngine instance, you can call it directly. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`data` | string | Hex string message to sign | -`address` | string | Address of the account to sign with | - -**Returns:** *`Promise`* - -Signature hex string (order: rsv) - -___ - -### signTransactionAsync - -▸ **signTransactionAsync**(`txData`: [PartialTxParams](#interface-partialtxparams)): *`Promise`* - -*Overrides void* - -*Defined in [subproviders/src/subproviders/trezor.ts:70](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/trezor.ts#L70)* - -Signs a transaction on the Trezor with the account specificed by the `from` field in txParams. -If you've added the TrezorSubprovider to your app's provider, you can simply send an `eth_sendTransaction` -JSON RPC request, and this method will be called auto-magically. If you are not using this via a ProviderEngine -instance, you can call it directly. - -**Parameters:** - -Name | Type | ------- | ------ | -`txData` | [PartialTxParams](#interface-partialtxparams) | - -**Returns:** *`Promise`* - -Signed transaction hex string - -___ - -### signTypedDataAsync - -▸ **signTypedDataAsync**(`address`: string, `typedData`: any): *`Promise`* - -*Overrides void* - -*Defined in [subproviders/src/subproviders/trezor.ts:161](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/trezor.ts#L161)* - -TODO:: eth_signTypedData is currently not supported on Trezor devices. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`address` | string | Address of the account to sign with | -`typedData` | any | - | - -**Returns:** *`Promise`* - -Signature hex string (order: rsv) - -
- - - - - - - - - - - -# Enumeration: NonceSubproviderErrors - - -## Enumeration members - -### CannotDetermineAddressFromPayload - -• **CannotDetermineAddressFromPayload**: = "CANNOT_DETERMINE_ADDRESS_FROM_PAYLOAD" - -*Defined in [subproviders/src/types.ts:121](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L121)* - -___ - -### EmptyParametersFound - -• **EmptyParametersFound**: = "EMPTY_PARAMETERS_FOUND" - -*Defined in [subproviders/src/types.ts:120](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L120)* - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -## Type aliases - - - - - - - - - -### EIP712ObjectValue - -Ƭ **EIP712ObjectValue**: *string | number | [EIP712Object](#interface-eip712object)* - -*Defined in [types/src/index.ts:740](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L740)* - -___ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# Interface: EIP1193Provider - - -## Properties - -### isEIP1193 - -• **isEIP1193**: *boolean* - -*Defined in [ethereum-types/src/index.ts:73](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L73)* - -## Methods - -### on - -▸ **on**(`event`: [EIP1193Event](#eip1193event), `listener`: function): *this* - -*Defined in [ethereum-types/src/index.ts:75](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L75)* - -**Parameters:** - -▪ **event**: *[EIP1193Event](#eip1193event)* - -▪ **listener**: *function* - -▸ (`result`: any): *void* - -**Parameters:** - -Name | Type | ------- | ------ | -`result` | any | - -**Returns:** *this* - -___ - -### send - -▸ **send**(`method`: string, `params?`: any[]): *`Promise`* - -*Defined in [ethereum-types/src/index.ts:74](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L74)* - -**Parameters:** - -Name | Type | ------- | ------ | -`method` | string | -`params?` | any[] | - -**Returns:** *`Promise`* - -
- - - - - - - - - - - - - -# Interface: GanacheProvider - - -## Methods - -### sendAsync - -▸ **sendAsync**(`payload`: [JSONRPCRequestPayload](_ethereum_types_src_index_.jsonrpcrequestpayload.md), `callback`: [JSONRPCErrorCallback](#jsonrpcerrorcallback)): *void* - -*Defined in [ethereum-types/src/index.ts:14](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L14)* - -**Parameters:** - -Name | Type | ------- | ------ | -`payload` | [JSONRPCRequestPayload](#class-jsonrpcrequestpayload) | -`callback` | [JSONRPCErrorCallback](#jsonrpcerrorcallback) | - -**Returns:** *void* - -
- - - -# Interface: JSONRPCRequestPayload - - -## Properties - -### id - -• **id**: *number* - -*Defined in [ethereum-types/src/index.ts:331](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L331)* - -___ - -### jsonrpc - -• **jsonrpc**: *string* - -*Defined in [ethereum-types/src/index.ts:332](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L332)* - -___ - -### method - -• **method**: *string* - -*Defined in [ethereum-types/src/index.ts:330](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L330)* - -___ - -### params - -• **params**: *any[]* - -*Defined in [ethereum-types/src/index.ts:329](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L329)* - -
- -# Interface: JSONRPCResponseError - - -## Properties - -### code - -• **code**: *number* - -*Defined in [ethereum-types/src/index.ts:337](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L337)* - -___ - -### message - -• **message**: *string* - -*Defined in [ethereum-types/src/index.ts:336](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L336)* - -
- -# Interface: JSONRPCResponsePayload - - -## Properties - -### `Optional` error - -• **error**? : *[JSONRPCResponseError](#class-jsonrpcresponseerror)* - -*Defined in [ethereum-types/src/index.ts:344](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L344)* - -___ - -### id - -• **id**: *number* - -*Defined in [ethereum-types/src/index.ts:342](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L342)* - -___ - -### jsonrpc - -• **jsonrpc**: *string* - -*Defined in [ethereum-types/src/index.ts:343](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L343)* - -___ - -### result - -• **result**: *any* - -*Defined in [ethereum-types/src/index.ts:341](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L341)* - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# Interface: Web3JsV1Provider - -Web3.js version 1 provider interface -This provider interface was implemented in the pre-1.0Beta releases for Web3.js. -This interface allowed sending synchonous requests, support for which was later dropped. - - -## Methods - -### send - -▸ **send**(`payload`: [JSONRPCRequestPayload](_ethereum_types_src_index_.jsonrpcrequestpayload.md)): *[JSONRPCResponsePayload](#class-jsonrpcresponsepayload)* - -*Defined in [ethereum-types/src/index.ts:45](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L45)* - -**Parameters:** - -Name | Type | ------- | ------ | -`payload` | [JSONRPCRequestPayload](#class-jsonrpcrequestpayload) | - -**Returns:** *[JSONRPCResponsePayload](#class-jsonrpcresponsepayload)* - -___ - -### sendAsync - -▸ **sendAsync**(`payload`: [JSONRPCRequestPayload](_ethereum_types_src_index_.jsonrpcrequestpayload.md), `callback`: [JSONRPCErrorCallback](#jsonrpcerrorcallback)): *void* - -*Defined in [ethereum-types/src/index.ts:44](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L44)* - -**Parameters:** - -Name | Type | ------- | ------ | -`payload` | [JSONRPCRequestPayload](#class-jsonrpcrequestpayload) | -`callback` | [JSONRPCErrorCallback](#jsonrpcerrorcallback) | - -**Returns:** *void* - -
- -# Interface: Web3JsV2Provider - -Web3.js version 2 provider interface -This provider interface was used in a couple of Web3.js 1.0 beta releases -before the first attempts to conform to EIP1193 - - -## Methods - -### send - -▸ **send**(`payload`: [JSONRPCRequestPayload](_ethereum_types_src_index_.jsonrpcrequestpayload.md), `callback`: [JSONRPCErrorCallback](#jsonrpcerrorcallback)): *void* - -*Defined in [ethereum-types/src/index.ts:54](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L54)* - -**Parameters:** - -Name | Type | ------- | ------ | -`payload` | [JSONRPCRequestPayload](#class-jsonrpcrequestpayload) | -`callback` | [JSONRPCErrorCallback](#jsonrpcerrorcallback) | - -**Returns:** *void* - -
- -# Interface: Web3JsV3Provider - -Web3.js version 3 provider interface -This provider interface was implemented with the hopes for conforming to the EIP1193 spec, -however it does not conform entirely. - - -## Methods - -### send - -▸ **send**(`method`: string, `params?`: any[]): *`Promise`* - -*Defined in [ethereum-types/src/index.ts:63](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L63)* - -**Parameters:** - -Name | Type | ------- | ------ | -`method` | string | -`params?` | any[] | - -**Returns:** *`Promise`* - -
- -# Interface: ZeroExProvider - -The interface for the provider used internally by 0x libraries -Any property we use from any SupportedProvider should we explicitly -add here - - -## Properties - -### `Optional` isMetaMask - -• **isMetaMask**? : *undefined | false | true* - -*Defined in [ethereum-types/src/index.ts:31](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L31)* - -___ - -### `Optional` isParity - -• **isParity**? : *undefined | false | true* - -*Defined in [ethereum-types/src/index.ts:32](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L32)* - -___ - -### `Optional` isZeroExProvider - -• **isZeroExProvider**? : *undefined | false | true* - -*Defined in [ethereum-types/src/index.ts:30](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L30)* - -## Methods - -### `Optional` enable - -▸ **enable**(): *`Promise`* - -*Defined in [ethereum-types/src/index.ts:34](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L34)* - -**Returns:** *`Promise`* - -___ - -### sendAsync - -▸ **sendAsync**(`payload`: [JSONRPCRequestPayload](_ethereum_types_src_index_.jsonrpcrequestpayload.md), `callback`: [JSONRPCErrorCallback](#jsonrpcerrorcallback)): *void* - -*Defined in [ethereum-types/src/index.ts:35](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L35)* - -**Parameters:** - -Name | Type | ------- | ------ | -`payload` | [JSONRPCRequestPayload](#class-jsonrpcrequestpayload) | -`callback` | [JSONRPCErrorCallback](#jsonrpcerrorcallback) | - -**Returns:** *void* - -___ - -### `Optional` stop - -▸ **stop**(): *void* - -*Defined in [ethereum-types/src/index.ts:33](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L33)* - -**Returns:** *void* - -
- -# Interface: DebugPayload - - -## Properties - -### id - -• **id**: *number* - - - -Defined in ethereum-types/lib/index.d.ts:268 - -___ - -### jsonrpc - -• **jsonrpc**: *string* - - - -Defined in ethereum-types/lib/index.d.ts:269 - -___ - -### method - -• **method**: *string* - - - -Defined in ethereum-types/lib/index.d.ts:267 - -___ - -### params - -• **params**: *any[]* - - - -Defined in ethereum-types/lib/index.d.ts:266 - -___ - -### `Optional` rawTransactionAttributes - -• **rawTransactionAttributes**? : *[DebugPayloadRawTransactionAttributes](#class-debugpayloadrawtransactionattributes)* - -*Defined in [subproviders/src/subproviders/debug_subprovider.ts:19](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/debug_subprovider.ts#L19)* - -
- -# Interface: DebugPayloadRawTransactionAttributes - - -## Properties - -### gasLimit - -• **gasLimit**: *string* - -*Defined in [subproviders/src/subproviders/debug_subprovider.ts:13](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/debug_subprovider.ts#L13)* - -___ - -### gasPrice - -• **gasPrice**: *string* - -*Defined in [subproviders/src/subproviders/debug_subprovider.ts:12](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/debug_subprovider.ts#L12)* - -___ - -### nonce - -• **nonce**: *string* - -*Defined in [subproviders/src/subproviders/debug_subprovider.ts:14](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/debug_subprovider.ts#L14)* - -___ - -### to - -• **to**: *string* - -*Defined in [subproviders/src/subproviders/debug_subprovider.ts:16](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/debug_subprovider.ts#L16)* - -___ - -### value - -• **value**: *string* - -*Defined in [subproviders/src/subproviders/debug_subprovider.ts:15](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/debug_subprovider.ts#L15)* - -
- -# Interface: AccountFetchingConfigs - -addressSearchLimit: The maximum number of addresses to search through, defaults to 1000 -numAddressesToReturn: Number of addresses to return from 'eth_accounts' call -shouldAskForOnDeviceConfirmation: Whether you wish to prompt the user on their Ledger - before fetching their addresses - - -## Properties - -### `Optional` addressSearchLimit - -• **addressSearchLimit**? : *undefined | number* - -*Defined in [subproviders/src/types.ts:55](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L55)* - -___ - -### `Optional` numAddressesToReturn - -• **numAddressesToReturn**? : *undefined | number* - -*Defined in [subproviders/src/types.ts:56](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L56)* - -___ - -### `Optional` shouldAskForOnDeviceConfirmation - -• **shouldAskForOnDeviceConfirmation**? : *undefined | false | true* - -*Defined in [subproviders/src/types.ts:57](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L57)* - -
- - - -# Interface: ECSignatureString - - -## Properties - -### r - -• **r**: *string* - -*Defined in [subproviders/src/types.ts:29](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L29)* - -___ - -### s - -• **s**: *string* - -*Defined in [subproviders/src/types.ts:30](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L30)* - -___ - -### v - -• **v**: *string* - -*Defined in [subproviders/src/types.ts:28](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L28)* - -
- -# Interface: JSONRPCRequestPayloadWithMethod - - -## Properties - -### id - -• **id**: *number* - - - -Defined in ethereum-types/lib/index.d.ts:268 - -___ - -### jsonrpc - -• **jsonrpc**: *string* - - - -Defined in ethereum-types/lib/index.d.ts:269 - -___ - -### method - -• **method**: *string* - -*Overrides void* - -*Defined in [subproviders/src/types.ts:136](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L136)* - -___ - -### params - -• **params**: *any[]* - - - -Defined in ethereum-types/lib/index.d.ts:266 - -
- - - - - -# Interface: LedgerEthereumClient - -Elliptic Curve signature -The LedgerEthereumClient sends Ethereum-specific requests to the Ledger Nano S -It uses an internal LedgerCommunicationClient to relay these requests. Currently -NodeJs and Browser communication are supported. - - -## Properties - -### getAddress - -• **getAddress**: *function* - -*Defined in [subproviders/src/types.ts:17](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L17)* - -#### Type declaration: - -▸ (`derivationPath`: string, `askForDeviceConfirmation`: boolean, `shouldGetChainCode`: true): *`Promise`* - -**Parameters:** - -Name | Type | ------- | ------ | -`derivationPath` | string | -`askForDeviceConfirmation` | boolean | -`shouldGetChainCode` | true | - -___ - -### signPersonalMessage - -• **signPersonalMessage**: *function* - -*Defined in [subproviders/src/types.ts:23](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L23)* - -#### Type declaration: - -▸ (`derivationPath`: string, `messageHex`: string): *`Promise`* - -**Parameters:** - -Name | Type | ------- | ------ | -`derivationPath` | string | -`messageHex` | string | - -___ - -### signTransaction - -• **signTransaction**: *function* - -*Defined in [subproviders/src/types.ts:22](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L22)* - -#### Type declaration: - -▸ (`derivationPath`: string, `rawTxHex`: string): *`Promise`* - -**Parameters:** - -Name | Type | ------- | ------ | -`derivationPath` | string | -`rawTxHex` | string | - -___ - -### transport - -• **transport**: *[LedgerCommunicationClient](#class-ledgercommunicationclient)* - -*Defined in [subproviders/src/types.ts:24](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L24)* - -
- -# Interface: LedgerGetAddressResult - - -## Properties - -### address - -• **address**: *string* - -*Defined in [subproviders/src/types.ts:79](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L79)* - -___ - -### chainCode - -• **chainCode**: *string* - -*Defined in [subproviders/src/types.ts:81](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L81)* - -___ - -### publicKey - -• **publicKey**: *string* - -*Defined in [subproviders/src/types.ts:80](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L80)* - -
- -# Interface: LedgerSubproviderConfigs - -networkId: The ethereum networkId to set as the chainId from EIP155 -ledgerConnectionType: Environment in which you wish to connect to Ledger (nodejs or browser) -derivationPath: Initial derivation path to use e.g 44'/60'/0' -accountFetchingConfigs: configs related to fetching accounts from a Ledger - - -## Properties - -### `Optional` accountFetchingConfigs - -• **accountFetchingConfigs**? : *[AccountFetchingConfigs](#class-accountfetchingconfigs)* - -*Defined in [subproviders/src/types.ts:45](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L45)* - -___ - -### `Optional` baseDerivationPath - -• **baseDerivationPath**? : *undefined | string* - -*Defined in [subproviders/src/types.ts:44](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L44)* - -___ - -### ledgerEthereumClientFactoryAsync - -• **ledgerEthereumClientFactoryAsync**: *[LedgerEthereumClientFactoryAsync](#ledgerethereumclientfactoryasync)* - -*Defined in [subproviders/src/types.ts:43](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L43)* - -___ - -### networkId - -• **networkId**: *number* - -*Defined in [subproviders/src/types.ts:42](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L42)* - -
- -# Interface: MnemonicWalletSubproviderConfigs - -mnemonic: The string mnemonic seed -addressSearchLimit: The maximum number of addresses to search through, defaults to 1000 -baseDerivationPath: The base derivation path (e.g 44'/60'/0'/0) - - -## Properties - -### `Optional` addressSearchLimit - -• **addressSearchLimit**? : *undefined | number* - -*Defined in [subproviders/src/types.ts:67](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L67)* - -___ - -### `Optional` baseDerivationPath - -• **baseDerivationPath**? : *undefined | string* - -*Defined in [subproviders/src/types.ts:68](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L68)* - -___ - -### mnemonic - -• **mnemonic**: *string* - -*Defined in [subproviders/src/types.ts:66](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L66)* - -
- -# Interface: PartialTxParams - - -## Properties - -### chainId - -• **chainId**: *number* - -*Defined in [subproviders/src/types.ts:92](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L92)* - -___ - -### `Optional` data - -• **data**? : *undefined | string* - -*Defined in [subproviders/src/types.ts:91](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L91)* - -___ - -### from - -• **from**: *string* - -*Defined in [subproviders/src/types.ts:89](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L89)* - -___ - -### gas - -• **gas**: *string* - -*Defined in [subproviders/src/types.ts:87](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L87)* - -___ - -### `Optional` gasPrice - -• **gasPrice**? : *undefined | string* - -*Defined in [subproviders/src/types.ts:86](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L86)* - -___ - -### nonce - -• **nonce**: *string* - -*Defined in [subproviders/src/types.ts:85](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L85)* - -___ - -### to - -• **to**: *string* - -*Defined in [subproviders/src/types.ts:88](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L88)* - -___ - -### `Optional` value - -• **value**? : *undefined | string* - -*Defined in [subproviders/src/types.ts:90](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L90)* - -
- - - - - - - -# Class: DebugSubprovider - -This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface. -For every request, a object for debugging will be sent to the function specified in the constructor -Useful for debugging RPC requests which are not expecting as you expect. - - -## Constructors - - - -\+ **new DebugSubprovider**(`debugCallback`: [WithDebugPayload](#withdebugpayload)): *[DebugSubprovider](#class-debugsubprovider)* - -*Defined in [subproviders/src/subproviders/debug_subprovider.ts:44](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/debug_subprovider.ts#L44)* - -**Parameters:** - -Name | Type | Default | ------- | ------ | ------ | -`debugCallback` | [WithDebugPayload](#withdebugpayload) | defaultDebugCallback | - -**Returns:** *[DebugSubprovider](#class-debugsubprovider)* - -## Methods - -### emitPayloadAsync - -▸ **emitPayloadAsync**(`payload`: `Partial`): *`Promise`* - -*Inherited from [Subprovider](#interface-subprovider).[emitPayloadAsync](#emitpayloadasync)* - -*Defined in [subproviders/src/subproviders/subprovider.ts:55](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L55)* - -Emits a JSON RPC payload that will then be handled by the ProviderEngine instance -this subprovider is a part of. The payload will cascade down the subprovider middleware -stack until finding the responsible entity for handling the request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `Partial` | JSON RPC payload | - -**Returns:** *`Promise`* - -JSON RPC response payload - -___ - -### handleRequest - -▸ **handleRequest**(`payload`: `JSONRPCRequestPayload`, `next`: [Callback](#callback), `end`: [ErrorCallback](#errorcallback)): *`Promise`* - -*Overrides [Subprovider](_subproviders_src_subproviders_subprovider_.subprovider.md).[handleRequest](#abstract-handlerequest)* - -*Defined in [subproviders/src/subproviders/debug_subprovider.ts:60](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/debug_subprovider.ts#L60)* - -This method conforms to the web3-provider-engine interface. -It is called internally by the ProviderEngine when it is this subproviders -turn to handle a JSON RPC request. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `JSONRPCRequestPayload` | JSON RPC payload | -`next` | [Callback](#callback) | Callback to call if this subprovider decides not to handle the request | -`end` | [ErrorCallback](#errorcallback) | Callback to call if subprovider handled the request and wants to pass back the request. | - -**Returns:** *`Promise`* - -___ - -### setEngine - -▸ **setEngine**(`engine`: `Web3ProviderEngine`): *void* - -*Inherited from [Subprovider](#interface-subprovider).[setEngine](#setengine)* - -*Defined in [subproviders/src/subproviders/subprovider.ts:68](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/subprovider.ts#L68)* - -Set's the subprovider's engine to the ProviderEngine it is added to. -This is only called within the ProviderEngine source code, do not call -directly. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`engine` | `Web3ProviderEngine` | The ProviderEngine this subprovider is added to | - -**Returns:** *void* - -
- - - - - - - -# Interface: TrezorSubproviderConfig - - -## Properties - -### accountFetchingConfigs - -• **accountFetchingConfigs**: *[AccountFetchingConfigs](#class-accountfetchingconfigs)* - -*Defined in [subproviders/src/types.ts:140](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L140)* - -___ - -### networkId - -• **networkId**: *number* - -*Defined in [subproviders/src/types.ts:142](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L142)* - -___ - -### trezorConnectClientApi - -• **trezorConnectClientApi**: *any* - -*Defined in [subproviders/src/types.ts:141](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L141)* - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# Interface: ECSignature - -Elliptic Curve signature - - -## Properties - -### r - -• **r**: *string* - -*Defined in [types/src/index.ts:62](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L62)* - -___ - -### s - -• **s**: *string* - -*Defined in [types/src/index.ts:63](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L63)* - -___ - -### v - -• **v**: *number* - -*Defined in [types/src/index.ts:61](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L61)* - -
- - - -# Interface: EIP712Object - - -## Hierarchy - -* **EIP712Parameter** - - -## Properties - -### name - -• **name**: *string* - -*Defined in [types/src/index.ts:732](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L732)* - -___ - -### type - -• **type**: *string* - -*Defined in [types/src/index.ts:733](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L733)* - -
- -# Interface: EIP712TypedData - - -## Properties - -### domain - -• **domain**: *[EIP712Object](#class-eip712object)* - -*Defined in [types/src/index.ts:748](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L748)* - -___ - -### message - -• **message**: *[EIP712Object](#class-eip712object)* - -*Defined in [types/src/index.ts:749](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L749)* - -___ - -### primaryType - -• **primaryType**: *string* - -*Defined in [types/src/index.ts:750](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L750)* - -___ - -### types - -• **types**: *[EIP712Types](#class-eip712types)* - -*Defined in [types/src/index.ts:747](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L747)* - -
- -# Interface: EIP712Types - - -## Hierarchy - -* **ElementType** - - -## Properties - -### name - -• **name**: *string* - -*Defined in [types/src/index.ts:686](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L686)* - -___ - -### typeDocType - -• **typeDocType**: *[TypeDocTypes](#enumeration-typedoctypes)* - -*Defined in [types/src/index.ts:687](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/types/src/index.ts#L687)* - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -## Functions - -### prependSubprovider - -▸ **prependSubprovider**(`provider`: `Web3ProviderEngine`, `subprovider`: [Subprovider](#class-subprovider)): *void* - -*Defined in [subproviders/src/utils/subprovider_utils.ts:10](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/utils/subprovider_utils.ts#L10)* - -Prepends a subprovider to a provider - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`provider` | `Web3ProviderEngine` | Given provider | -`subprovider` | [Subprovider](#class-subprovider) | Subprovider to prepend | - -**Returns:** *void* - -
- - - - -## Type aliases - - - - - - - - - - - - - -### EIP1193Event - -Ƭ **EIP1193Event**: *"accountsChanged" | "networkChanged" | "close" | "connect" | "notification"* - -*Defined in [ethereum-types/src/index.ts:70](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L70)* - -Interface for providers that conform to EIP 1193 -Source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md - -___ - - - - - - - -### JSONRPCErrorCallback - -Ƭ **JSONRPCErrorCallback**: *function* - -*Defined in [ethereum-types/src/index.ts:3](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L3)* - -#### Type declaration: - -▸ (`err`: `Error` | null, `result?`: [JSONRPCResponsePayload](#interface-jsonrpcresponsepayload)): *void* - -**Parameters:** - -Name | Type | ------- | ------ | -`err` | `Error` \| null | -`result?` | [JSONRPCResponsePayload](#interface-jsonrpcresponsepayload) | - -___ - - - - - - - - - - - -### SupportedProvider - -Ƭ **SupportedProvider**: *[Web3JsProvider](_ethereum_types_src_index_.md#web3jsprovider) | [GanacheProvider](#interface-ganacheprovider) | [EIP1193Provider](#interface-eip1193provider) | [ZeroExProvider](#interface-zeroexprovider)* - -*Defined in [ethereum-types/src/index.ts:9](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L9)* - -Do not create your own provider. Use an existing provider from a Web3 or ProviderEngine library -Read more about Providers in the guides section of the 0x docs. - -___ - - - - - -### Web3JsProvider - -Ƭ **Web3JsProvider**: *[Web3JsV1Provider](#interface-web3jsv1provider) | [Web3JsV2Provider](#interface-web3jsv2provider) | [Web3JsV3Provider](#interface-web3jsv3provider)* - -*Defined in [ethereum-types/src/index.ts:11](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L11)* - -
- - - - -## Functions - -### ledgerEthereumBrowserClientFactoryAsync - -▸ **ledgerEthereumBrowserClientFactoryAsync**(): *`Promise`* - -*Defined in [subproviders/src/index.ts:11](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/index.ts#L11)* - -A factory method for creating a LedgerEthereumClient usable in a browser context. - -**Returns:** *`Promise`* - -LedgerEthereumClient A browser client for the LedgerSubprovider - -
- - - - -## Type aliases - -### WithDebugPayload - -Ƭ **WithDebugPayload**: *function* - -*Defined in [subproviders/src/subproviders/debug_subprovider.ts:22](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/subproviders/debug_subprovider.ts#L22)* - -#### Type declaration: - -▸ (`debugPayload`: [DebugPayload](#interface-debugpayload)): *void* - -**Parameters:** - -Name | Type | ------- | ------ | -`debugPayload` | [DebugPayload](#interface-debugpayload) | - -
- - - -
- - - -
- - - -
- - - -
- - - -
- - - -
- - - -
- - - -
- - - -
- - - -
- - - -
- - - -
- - - -
- - - - -## Type aliases - -### Callback - -Ƭ **Callback**: *function* - -*Defined in [subproviders/src/types.ts:131](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L131)* - -#### Type declaration: - -▸ (): *void* - -___ - - - -### ErrorCallback - -Ƭ **ErrorCallback**: *function* - -*Defined in [subproviders/src/types.ts:130](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L130)* - -#### Type declaration: - -▸ (`err`: `Error` | null, `data?`: any): *void* - -**Parameters:** - -Name | Type | ------- | ------ | -`err` | `Error` \| null | -`data?` | any | - -___ - -### LedgerEthereumClientFactoryAsync - -Ƭ **LedgerEthereumClientFactoryAsync**: *function* - -*Defined in [subproviders/src/types.ts:33](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L33)* - -#### Type declaration: - -▸ (): *`Promise`* - -___ - -### NextCallback - -Ƭ **NextCallback**: *function* - -*Defined in [subproviders/src/types.ts:133](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L133)* - -#### Type declaration: - -▸ (`callback?`: [OnNextCompleted](#onnextcompleted)): *void* - -**Parameters:** - -Name | Type | ------- | ------ | -`callback?` | [OnNextCompleted](#onnextcompleted) | - -___ - -### OnNextCompleted - -Ƭ **OnNextCompleted**: *function* - -*Defined in [subproviders/src/types.ts:132](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/subproviders/src/types.ts#L132)* - -#### Type declaration: - -▸ (`err`: `Error` | null, `result`: any, `cb`: [Callback](#callback)): *void* - -**Parameters:** - -Name | Type | ------- | ------ | -`err` | `Error` \| null | -`result` | any | -`cb` | [Callback](#callback) | - -
- diff --git a/packages/subproviders/package.json b/packages/subproviders/package.json deleted file mode 100644 index e294c79be7..0000000000 --- a/packages/subproviders/package.json +++ /dev/null @@ -1,93 +0,0 @@ -{ - "name": "@0x/subproviders", - "version": "6.1.1", - "engines": { - "node": ">=6.12" - }, - "main": "lib/src/index.js", - "types": "lib/src/index.d.ts", - "license": "Apache-2.0", - "scripts": { - "build": "tsc -b", - "build:ci": "yarn build", - "clean": "shx rm -rf lib generated_docs", - "lint": "tslint --format stylish --project .", - "fix": "tslint --fix --format stylish --project .", - "run_mocha_unit": "mocha --require source-map-support/register --require make-promises-safe lib/test/unit/**/*_test.js --timeout 10000 --bail --exit", - "run_mocha_integration": "mocha --require source-map-support/register --require make-promises-safe lib/test/integration/**/*_test.js --timeout 10000 --bail --exit", - "test": "npm run test:unit", - "test:unit:coverage": "nyc npm run test:unit --all && yarn coverage:report:lcov", - "coverage:report:lcov": "nyc report --reporter=text-lcov > coverage/lcov.info", - "test:circleci": "npm run test:unit:coverage", - "test:all": "run-s test:unit test:integration", - "test:unit": "run-s clean build run_mocha_unit", - "test:integration": "run-s clean build run_mocha_integration", - "diff_docs": "git diff --exit-code ./docs", - "s3:sync_md_docs": "aws s3 sync ./docs s3://docs-markdown/${npm_package_name}/v${npm_package_version} --profile 0xproject --region us-east-1 --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers", - "docs:md": "ts-doc-gen --sourceDir='$PROJECT_FILES' --output=$MD_FILE_DIR --fileExtension=mdx --tsconfig=./typedoc-tsconfig.json", - "docs:json": "typedoc --excludePrivate --excludeExternals --excludeProtected --ignoreCompilerErrors --target ES5 --tsconfig typedoc-tsconfig.json --json $JSON_FILE_PATH $PROJECT_FILES", - "postinstall": "node -e \"try{ fs.unlinkSync(path.resolve(path.dirname(require.resolve('ganache-core')), './typings/index.d.ts')) } catch (err) {}\"" - }, - "config": { - "postpublish": { - "assets": [] - } - }, - "dependencies": { - "@0x/assert": "^3.0.9", - "@0x/types": "^3.2.0", - "@0x/typescript-typings": "^5.1.1", - "@0x/utils": "^5.5.1", - "@0x/web3-wrapper": "^7.2.0", - "@ledgerhq/hw-app-eth": "^4.3.0", - "@ledgerhq/hw-transport-u2f": "4.24.0", - "@types/hdkey": "^0.7.0", - "@types/web3-provider-engine": "^14.0.0", - "bip39": "^2.5.0", - "bn.js": "^4.11.8", - "ethereum-types": "^3.2.0", - "ethereumjs-tx": "^1.3.5", - "ethereumjs-util": "^5.1.1", - "ganache-core": "^2.10.2", - "hdkey": "^0.7.1", - "json-rpc-error": "2.0.0", - "lodash": "^4.17.11", - "semaphore-async-await": "^1.5.1", - "web3-provider-engine": "14.0.6" - }, - "devDependencies": { - "@0x/ts-doc-gen": "^0.0.22", - "@0x/tslint-config": "^4.1.0", - "@types/bip39": "^2.4.0", - "@types/bn.js": "^4.11.0", - "@types/ethereumjs-tx": "^1.0.1", - "@types/hdkey": "^0.7.0", - "@types/lodash": "4.14.104", - "@types/mocha": "^5.2.7", - "@types/node": "12.12.54", - "@types/sinon": "^2.2.2", - "chai": "^4.0.1", - "chai-as-promised": "^7.1.0", - "dirty-chai": "^2.0.1", - "make-promises-safe": "^1.1.0", - "mocha": "^6.2.0", - "npm-run-all": "^4.1.2", - "nyc": "^11.0.1", - "shx": "^0.2.2", - "sinon": "^4.0.0", - "tslint": "5.11.0", - "typedoc": "^0.15.0", - "typescript": "3.0.1", - "webpack": "^4.20.2" - }, - "optionalDependencies": { - "@ledgerhq/hw-transport-node-hid": "^4.3.0" - }, - "publishConfig": { - "access": "public" - }, - "browser": { - "ganache-core": false - }, - "gitHead": "4f91bfd907996b2f4dd383778b50c479c2602b56" -} diff --git a/packages/subproviders/src/globals.d.ts b/packages/subproviders/src/globals.d.ts deleted file mode 100644 index 3cbf84e370..0000000000 --- a/packages/subproviders/src/globals.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -declare module '*.json' { - const json: any; - /* tslint:disable */ - export default json; - /* tslint:enable */ -} -declare module 'web3-provider-engine/util/rpc-cache-utils' { - class ProviderEngineRpcUtils { - public static blockTagForPayload(payload: any): string | null; - } - export = ProviderEngineRpcUtils; -} -declare module 'web3-provider-engine/subproviders/fixture' { - import { JSONRPCRequestPayload, JSONRPCResponsePayload } from 'ethereum-types'; - class FixtureSubprovider { - constructor(staticResponses: any); - public handleRequest( - payload: JSONRPCRequestPayload, - next: () => void, - end: (err: Error | null, data?: JSONRPCResponsePayload) => void, - ): void; - } - export = FixtureSubprovider; -} diff --git a/packages/subproviders/src/index.ts b/packages/subproviders/src/index.ts deleted file mode 100644 index 6d720e3f9d..0000000000 --- a/packages/subproviders/src/index.ts +++ /dev/null @@ -1,74 +0,0 @@ -import Eth from '@ledgerhq/hw-app-eth'; -import TransportU2F from '@ledgerhq/hw-transport-u2f'; -export import Web3ProviderEngine = require('web3-provider-engine'); - -import { LedgerEthereumClient } from './types'; - -/** - * A factory method for creating a LedgerEthereumClient usable in a browser context. - * @return LedgerEthereumClient A browser client for the LedgerSubprovider - */ -export async function ledgerEthereumBrowserClientFactoryAsync(): Promise { - const ledgerConnection = await TransportU2F.create(); - const ledgerEthClient = new Eth(ledgerConnection); - return ledgerEthClient; -} - -export { prependSubprovider } from './utils/subprovider_utils'; - -export { EmptyWalletSubprovider } from './subproviders/empty_wallet_subprovider'; -export { FakeGasEstimateSubprovider } from './subproviders/fake_gas_estimate_subprovider'; -export { SignerSubprovider } from './subproviders/signer'; -export { RedundantSubprovider } from './subproviders/redundant_subprovider'; -export { LedgerSubprovider } from './subproviders/ledger'; -export { RPCSubprovider } from './subproviders/rpc_subprovider'; -export { GanacheSubprovider } from './subproviders/ganache'; -export { Subprovider } from './subproviders/subprovider'; -export { - DebugPayloadRawTransactionAttributes, - DebugPayload, - DebugSubprovider, - WithDebugPayload, -} from './subproviders/debug_subprovider'; -export { NonceTrackerSubprovider } from './subproviders/nonce_tracker'; -export { PrivateKeyWalletSubprovider } from './subproviders/private_key_wallet'; -export { MnemonicWalletSubprovider } from './subproviders/mnemonic_wallet'; -export { MetamaskSubprovider } from './subproviders/metamask_subprovider'; -export { TrezorSubprovider } from './subproviders/trezor'; - -export { - Callback, - ErrorCallback, - NextCallback, - LedgerCommunicationClient, - LedgerEthereumClient, - NonceSubproviderErrors, - LedgerSubproviderConfigs, - PartialTxParams, - JSONRPCRequestPayloadWithMethod, - ECSignatureString, - AccountFetchingConfigs, - LedgerEthereumClientFactoryAsync, - OnNextCompleted, - MnemonicWalletSubproviderConfigs, - LedgerGetAddressResult, - TrezorSubproviderConfig, -} from './types'; - -export { ECSignature, EIP712Object, EIP712ObjectValue, EIP712TypedData, EIP712Types, EIP712Parameter } from '@0x/types'; - -export { - JSONRPCRequestPayload, - SupportedProvider, - JSONRPCResponsePayload, - JSONRPCResponseError, - JSONRPCErrorCallback, - Web3JsProvider, - GanacheProvider, - EIP1193Provider, - ZeroExProvider, - EIP1193Event, - Web3JsV1Provider, - Web3JsV2Provider, - Web3JsV3Provider, -} from 'ethereum-types'; diff --git a/packages/subproviders/src/subproviders/base_wallet_subprovider.ts b/packages/subproviders/src/subproviders/base_wallet_subprovider.ts deleted file mode 100644 index 89b5958dcf..0000000000 --- a/packages/subproviders/src/subproviders/base_wallet_subprovider.ts +++ /dev/null @@ -1,151 +0,0 @@ -import { assert } from '@0x/assert'; -import { addressUtils } from '@0x/utils'; -import { JSONRPCRequestPayload, JSONRPCResponsePayload } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { Callback, ErrorCallback, PartialTxParams, WalletSubproviderErrors } from '../types'; - -import { Subprovider } from './subprovider'; - -export abstract class BaseWalletSubprovider extends Subprovider { - protected static _validateTxParams(txParams: PartialTxParams): void { - if (txParams.to !== undefined) { - assert.isETHAddressHex('to', txParams.to); - } - assert.isHexString('nonce', txParams.nonce); - } - private static _validateSender(sender: string): void { - if (sender === undefined || !addressUtils.isAddress(sender)) { - throw new Error(WalletSubproviderErrors.SenderInvalidOrNotSupplied); - } - } - - public abstract async getAccountsAsync(): Promise; - public abstract async signTransactionAsync(txParams: PartialTxParams): Promise; - public abstract async signPersonalMessageAsync(data: string, address: string): Promise; - public abstract async signTypedDataAsync(address: string, typedData: any): Promise; - - /** - * This method conforms to the web3-provider-engine interface. - * It is called internally by the ProviderEngine when it is this subproviders - * turn to handle a JSON RPC request. - * @param payload JSON RPC payload - * @param next Callback to call if this subprovider decides not to handle the request - * @param end Callback to call if subprovider handled the request and wants to pass back the request. - */ - // tslint:disable-next-line:async-suffix - public async handleRequest(payload: JSONRPCRequestPayload, next: Callback, end: ErrorCallback): Promise { - let accounts; - let txParams; - let address; - let typedData; - switch (payload.method) { - case 'eth_coinbase': - try { - accounts = await this.getAccountsAsync(); - end(null, accounts[0]); - } catch (err) { - end(err); - } - return; - - case 'eth_accounts': - try { - accounts = await this.getAccountsAsync(); - end(null, accounts); - } catch (err) { - end(err); - } - return; - - case 'eth_sendTransaction': - txParams = payload.params[0]; - try { - BaseWalletSubprovider._validateSender(txParams.from); - const filledParams = await this._populateMissingTxParamsAsync(txParams); - const signedTx = await this.signTransactionAsync(filledParams); - const response = await this._emitSendTransactionAsync(signedTx); - end(null, response.result); - } catch (err) { - end(err); - } - return; - - case 'eth_signTransaction': - txParams = payload.params[0]; - try { - const filledParams = await this._populateMissingTxParamsAsync(txParams); - const signedTx = await this.signTransactionAsync(filledParams); - const result = { - raw: signedTx, - tx: txParams, - }; - end(null, result); - } catch (err) { - end(err); - } - return; - - case 'eth_sign': - case 'personal_sign': - const data = payload.method === 'eth_sign' ? payload.params[1] : payload.params[0]; - address = payload.method === 'eth_sign' ? payload.params[0] : payload.params[1]; - try { - const ecSignatureHex = await this.signPersonalMessageAsync(data, address); - end(null, ecSignatureHex); - } catch (err) { - end(err); - } - return; - case 'eth_signTypedData': - [address, typedData] = payload.params; - try { - const signature = await this.signTypedDataAsync(address, typedData); - end(null, signature); - } catch (err) { - end(err); - } - return; - - default: - next(); - return; - } - } - private async _emitSendTransactionAsync(signedTx: string): Promise { - const payload = { - method: 'eth_sendRawTransaction', - params: [signedTx], - }; - const result = await this.emitPayloadAsync(payload); - return result; - } - private async _populateMissingTxParamsAsync(partialTxParams: PartialTxParams): Promise { - let txParams = partialTxParams; - if (partialTxParams.gasPrice === undefined) { - const gasPriceResult = await this.emitPayloadAsync({ - method: 'eth_gasPrice', - params: [], - }); - const gasPrice = gasPriceResult.result.toString(); - txParams = { ...txParams, gasPrice }; - } - if (partialTxParams.nonce === undefined) { - const nonceResult = await this.emitPayloadAsync({ - method: 'eth_getTransactionCount', - params: [partialTxParams.from, 'pending'], - }); - const nonce = nonceResult.result; - txParams = { ...txParams, nonce }; - } - if (partialTxParams.gas === undefined) { - const gasResult = await this.emitPayloadAsync({ - method: 'eth_estimateGas', - params: [partialTxParams], - }); - const gas = gasResult.result.toString(); - txParams = { ...txParams, gas }; - } - return txParams; - } -} diff --git a/packages/subproviders/src/subproviders/debug_subprovider.ts b/packages/subproviders/src/subproviders/debug_subprovider.ts deleted file mode 100644 index 332bcd81a8..0000000000 --- a/packages/subproviders/src/subproviders/debug_subprovider.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { BigNumber } from '@0x/utils'; -import { JSONRPCRequestPayload } from 'ethereum-types'; -import EthereumTx = require('ethereumjs-tx'); - -import { Callback, ErrorCallback } from '../types'; - -import { Subprovider } from './subprovider'; - -const HEX_BASE = 16; - -export interface DebugPayloadRawTransactionAttributes { - gasPrice: string; - gasLimit: string; - nonce: string; - value: string; - to: string; -} -export interface DebugPayload extends JSONRPCRequestPayload { - rawTransactionAttributes?: DebugPayloadRawTransactionAttributes; -} - -export type WithDebugPayload = (debugPayload: DebugPayload) => void; -// tslint:disable-next-line:no-console -const defaultDebugCallback = (debugPayload: DebugPayload) => console.debug(JSON.stringify(debugPayload, null, 2)); - -/** - * This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface. - * For every request, a object for debugging will be sent to the function specified in the constructor - * Useful for debugging RPC requests which are not expecting as you expect. - */ -export class DebugSubprovider extends Subprovider { - private readonly _debugCallback: WithDebugPayload; - - private static _generateRawTransactionAttributes(txn: EthereumTx): DebugPayloadRawTransactionAttributes { - const hexBufferToString = (value: Buffer): string => new BigNumber(value.toString('hex'), HEX_BASE).toString(); - - return { - gasLimit: hexBufferToString(txn.gasLimit), - gasPrice: hexBufferToString(txn.gasPrice), - nonce: hexBufferToString(txn.nonce), - value: hexBufferToString(txn.value), - to: `0x${txn.to.toString('hex')}`, - }; - } - - public constructor(debugCallback: WithDebugPayload = defaultDebugCallback) { - super(); - this._debugCallback = debugCallback; - } - - /** - * This method conforms to the web3-provider-engine interface. - * It is called internally by the ProviderEngine when it is this subproviders - * turn to handle a JSON RPC request. - * @param payload JSON RPC payload - * @param next Callback to call if this subprovider decides not to handle the request - * @param end Callback to call if subprovider handled the request and wants to pass back the request. - */ - // tslint:disable-next-line:prefer-function-over-method async-suffix - public async handleRequest(payload: JSONRPCRequestPayload, next: Callback, end: ErrorCallback): Promise { - const debugPayload: DebugPayload = payload; - if (payload.method === 'eth_sendRawTransaction' && payload.params[0]) { - const txn = new EthereumTx(payload.params[0]); - debugPayload.rawTransactionAttributes = DebugSubprovider._generateRawTransactionAttributes(txn); - } - this._debugCallback(debugPayload); - - next(); - } -} diff --git a/packages/subproviders/src/subproviders/empty_wallet_subprovider.ts b/packages/subproviders/src/subproviders/empty_wallet_subprovider.ts deleted file mode 100644 index 4268c67bd4..0000000000 --- a/packages/subproviders/src/subproviders/empty_wallet_subprovider.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { JSONRPCRequestPayload } from 'ethereum-types'; - -import { Callback, ErrorCallback } from '../types'; - -import { Subprovider } from './subprovider'; - -/** - * This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface. - * It intercepts the `eth_accounts` JSON RPC requests and never returns any addresses when queried. - */ -export class EmptyWalletSubprovider extends Subprovider { - /** - * This method conforms to the web3-provider-engine interface. - * It is called internally by the ProviderEngine when it is this subproviders - * turn to handle a JSON RPC request. - * @param payload JSON RPC payload - * @param next Callback to call if this subprovider decides not to handle the request - * @param end Callback to call if subprovider handled the request and wants to pass back the request. - */ - // tslint:disable-next-line:prefer-function-over-method async-suffix - public async handleRequest(payload: JSONRPCRequestPayload, next: Callback, end: ErrorCallback): Promise { - switch (payload.method) { - case 'eth_accounts': - end(null, []); - return; - - default: - next(); - return; - } - } -} diff --git a/packages/subproviders/src/subproviders/fake_gas_estimate_subprovider.ts b/packages/subproviders/src/subproviders/fake_gas_estimate_subprovider.ts deleted file mode 100644 index bc1b34abad..0000000000 --- a/packages/subproviders/src/subproviders/fake_gas_estimate_subprovider.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { JSONRPCRequestPayload } from 'ethereum-types'; - -import { Callback, ErrorCallback } from '../types'; - -import { Subprovider } from './subprovider'; - -// HACK: We need this so that our tests don't use testrpc gas estimation which sometimes kills the node. -// Source: https://github.com/trufflesuite/ganache-cli/issues/417 -// Source: https://github.com/trufflesuite/ganache-cli/issues/437 -// Source: https://github.com/MetaMask/provider-engine/blob/master/subproviders/subprovider.js - -/** - * This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface. - * It intercepts the `eth_estimateGas` JSON RPC call and always returns a constant gas amount when queried. - */ -export class FakeGasEstimateSubprovider extends Subprovider { - private readonly _constantGasAmount: number; - /** - * Instantiates an instance of the FakeGasEstimateSubprovider - * @param constantGasAmount The constant gas amount you want returned - */ - constructor(constantGasAmount: number) { - super(); - this._constantGasAmount = constantGasAmount; - } - /** - * This method conforms to the web3-provider-engine interface. - * It is called internally by the ProviderEngine when it is this subproviders - * turn to handle a JSON RPC request. - * @param payload JSON RPC payload - * @param next Callback to call if this subprovider decides not to handle the request - * @param end Callback to call if subprovider handled the request and wants to pass back the request. - */ - // tslint:disable-next-line:prefer-function-over-method async-suffix - public async handleRequest(payload: JSONRPCRequestPayload, next: Callback, end: ErrorCallback): Promise { - switch (payload.method) { - case 'eth_estimateGas': - end(null, this._constantGasAmount); - return; - - default: - next(); - return; - } - } -} diff --git a/packages/subproviders/src/subproviders/ganache.ts b/packages/subproviders/src/subproviders/ganache.ts deleted file mode 100644 index 6e53eeecca..0000000000 --- a/packages/subproviders/src/subproviders/ganache.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { GanacheProvider, JSONRPCRequestPayload } from 'ethereum-types'; -import * as Ganache from 'ganache-core'; - -import { Callback, ErrorCallback } from '../types'; - -import { Subprovider } from './subprovider'; - -/** - * This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface. - * It intercepts all JSON RPC requests and relays them to an in-process ganache instance. - */ -export class GanacheSubprovider extends Subprovider { - private readonly _ganacheProvider: GanacheProvider; - /** - * Instantiates a GanacheSubprovider - * @param opts The desired opts with which to instantiate the Ganache provider - */ - constructor(opts: Ganache.GanacheOpts) { - super(); - this._ganacheProvider = Ganache.provider(opts); - } - /** - * This method conforms to the web3-provider-engine interface. - * It is called internally by the ProviderEngine when it is this subproviders - * turn to handle a JSON RPC request. - * @param payload JSON RPC payload - * @param _next Callback to call if this subprovider decides not to handle the request - * @param end Callback to call if subprovider handled the request and wants to pass back the request. - */ - // tslint:disable-next-line:prefer-function-over-method async-suffix - public async handleRequest(payload: JSONRPCRequestPayload, _next: Callback, end: ErrorCallback): Promise { - this._ganacheProvider.sendAsync(payload, (err: Error | null, result: any) => { - end(err, result && result.result); - }); - } -} diff --git a/packages/subproviders/src/subproviders/ledger.ts b/packages/subproviders/src/subproviders/ledger.ts deleted file mode 100644 index caa3ecb71f..0000000000 --- a/packages/subproviders/src/subproviders/ledger.ts +++ /dev/null @@ -1,256 +0,0 @@ -import { assert } from '@0x/assert'; -import { addressUtils } from '@0x/utils'; -import EthereumTx = require('ethereumjs-tx'); -import ethUtil = require('ethereumjs-util'); -import HDNode = require('hdkey'); -import * as _ from 'lodash'; -import { Lock } from 'semaphore-async-await'; - -import { - DerivedHDKeyInfo, - LedgerEthereumClient, - LedgerEthereumClientFactoryAsync, - LedgerSubproviderConfigs, - LedgerSubproviderErrors, - PartialTxParams, - WalletSubproviderErrors, -} from '../types'; -import { walletUtils } from '../utils/wallet_utils'; - -import { BaseWalletSubprovider } from './base_wallet_subprovider'; - -const DEFAULT_BASE_DERIVATION_PATH = `44'/60'/0'`; -const ASK_FOR_ON_DEVICE_CONFIRMATION = false; -const SHOULD_GET_CHAIN_CODE = true; -const DEFAULT_NUM_ADDRESSES_TO_FETCH = 10; -const DEFAULT_ADDRESS_SEARCH_LIMIT = 1000; - -/** - * Subprovider for interfacing with a user's [Ledger Nano S](https://www.ledgerwallet.com/products/ledger-nano-s). - * This subprovider intercepts all account related RPC requests (e.g message/transaction signing, etc...) and - * re-routes them to a Ledger device plugged into the users computer. - */ -export class LedgerSubprovider extends BaseWalletSubprovider { - // tslint:disable-next-line:no-unused-variable - private readonly _connectionLock = new Lock(); - private readonly _networkId: number; - private _baseDerivationPath: string; - private readonly _ledgerEthereumClientFactoryAsync: LedgerEthereumClientFactoryAsync; - private _ledgerClientIfExists?: LedgerEthereumClient; - private readonly _shouldAlwaysAskForConfirmation: boolean; - private readonly _addressSearchLimit: number; - /** - * Instantiates a LedgerSubprovider. Defaults to derivationPath set to `44'/60'/0'`. - * TestRPC/Ganache defaults to `m/44'/60'/0'/0`, so set this in the configs if desired. - * @param config Several available configurations - * @return LedgerSubprovider instance - */ - constructor(config: LedgerSubproviderConfigs) { - super(); - this._networkId = config.networkId; - this._ledgerEthereumClientFactoryAsync = config.ledgerEthereumClientFactoryAsync; - this._baseDerivationPath = config.baseDerivationPath || DEFAULT_BASE_DERIVATION_PATH; - this._shouldAlwaysAskForConfirmation = - config.accountFetchingConfigs !== undefined && - config.accountFetchingConfigs.shouldAskForOnDeviceConfirmation !== undefined - ? config.accountFetchingConfigs.shouldAskForOnDeviceConfirmation - : ASK_FOR_ON_DEVICE_CONFIRMATION; - this._addressSearchLimit = - config.accountFetchingConfigs !== undefined && - config.accountFetchingConfigs.addressSearchLimit !== undefined - ? config.accountFetchingConfigs.addressSearchLimit - : DEFAULT_ADDRESS_SEARCH_LIMIT; - } - /** - * Retrieve the set derivation path - * @returns derivation path - */ - public getPath(): string { - return this._baseDerivationPath; - } - /** - * Set a desired derivation path when computing the available user addresses - * @param basDerivationPath The desired derivation path (e.g `44'/60'/0'`) - */ - public setPath(basDerivationPath: string): void { - this._baseDerivationPath = basDerivationPath; - } - /** - * Retrieve a users Ledger accounts. The accounts are derived from the derivationPath, - * master public key and chain code. Because of this, you can request as many accounts - * as you wish and it only requires a single request to the Ledger device. This method - * is automatically called when issuing a `eth_accounts` JSON RPC request via your providerEngine - * instance. - * @param numberOfAccounts Number of accounts to retrieve (default: 10) - * @return An array of accounts - */ - public async getAccountsAsync(numberOfAccounts: number = DEFAULT_NUM_ADDRESSES_TO_FETCH): Promise { - const initialDerivedKeyInfo = await this._initialDerivedKeyInfoAsync(); - const derivedKeyInfos = walletUtils.calculateDerivedHDKeyInfos(initialDerivedKeyInfo, numberOfAccounts); - const accounts = _.map(derivedKeyInfos, k => k.address); - return accounts; - } - /** - * Signs a transaction on the Ledger with the account specificed by the `from` field in txParams. - * If you've added the LedgerSubprovider to your app's provider, you can simply send an `eth_sendTransaction` - * JSON RPC request, and this method will be called auto-magically. If you are not using this via a ProviderEngine - * instance, you can call it directly. - * @param txParams Parameters of the transaction to sign - * @return Signed transaction hex string - */ - public async signTransactionAsync(txParams: PartialTxParams): Promise { - LedgerSubprovider._validateTxParams(txParams); - if (txParams.from === undefined || !addressUtils.isAddress(txParams.from)) { - throw new Error(WalletSubproviderErrors.FromAddressMissingOrInvalid); - } - const initialDerivedKeyInfo = await this._initialDerivedKeyInfoAsync(); - const derivedKeyInfo = this._findDerivedKeyInfoForAddress(initialDerivedKeyInfo, txParams.from); - - this._ledgerClientIfExists = await this._createLedgerClientAsync(); - - const tx = new EthereumTx(txParams); - - // Set the EIP155 bits - const vIndex = 6; - tx.raw[vIndex] = Buffer.from([this._networkId]); // v - const rIndex = 7; - tx.raw[rIndex] = Buffer.from([]); // r - const sIndex = 8; - tx.raw[sIndex] = Buffer.from([]); // s - - const txHex = tx.serialize().toString('hex'); - try { - const fullDerivationPath = derivedKeyInfo.derivationPath; - const result = await this._ledgerClientIfExists.signTransaction(fullDerivationPath, txHex); - // Store signature in transaction - tx.r = Buffer.from(result.r, 'hex'); - tx.s = Buffer.from(result.s, 'hex'); - tx.v = Buffer.from(result.v, 'hex'); - - // EIP155: v should be chain_id * 2 + {35, 36} - const eip55Constant = 35; - const signedChainId = Math.floor((tx.v[0] - eip55Constant) / 2); - if (signedChainId !== this._networkId) { - await this._destroyLedgerClientAsync(); - const err = new Error(LedgerSubproviderErrors.TooOldLedgerFirmware); - throw err; - } - - const signedTxHex = `0x${tx.serialize().toString('hex')}`; - await this._destroyLedgerClientAsync(); - return signedTxHex; - } catch (err) { - await this._destroyLedgerClientAsync(); - throw err; - } - } - /** - * Sign a personal Ethereum signed message. The signing account will be the account - * associated with the provided address. - * The Ledger adds the Ethereum signed message prefix on-device. If you've added - * the LedgerSubprovider to your app's provider, you can simply send an `eth_sign` - * or `personal_sign` JSON RPC request, and this method will be called auto-magically. - * If you are not using this via a ProviderEngine instance, you can call it directly. - * @param data Hex string message to sign - * @param address Address of the account to sign with - * @return Signature hex string (order: rsv) - */ - public async signPersonalMessageAsync(data: string, address: string): Promise { - if (data === undefined) { - throw new Error(WalletSubproviderErrors.DataMissingForSignPersonalMessage); - } - assert.isHexString('data', data); - assert.isETHAddressHex('address', address); - const initialDerivedKeyInfo = await this._initialDerivedKeyInfoAsync(); - const derivedKeyInfo = this._findDerivedKeyInfoForAddress(initialDerivedKeyInfo, address); - - this._ledgerClientIfExists = await this._createLedgerClientAsync(); - try { - const fullDerivationPath = derivedKeyInfo.derivationPath; - const result = await this._ledgerClientIfExists.signPersonalMessage( - fullDerivationPath, - ethUtil.stripHexPrefix(data), - ); - const lowestValidV = 27; - const v = result.v - lowestValidV; - const hexBase = 16; - let vHex = v.toString(hexBase); - if (vHex.length < 2) { - vHex = `0${v}`; - } - const signature = `0x${result.r}${result.s}${vHex}`; - await this._destroyLedgerClientAsync(); - return signature; - } catch (err) { - await this._destroyLedgerClientAsync(); - throw err; - } - } - /** - * eth_signTypedData is currently not supported on Ledger devices. - * @param address Address of the account to sign with - * @param data the typed data object - * @return Signature hex string (order: rsv) - */ - // tslint:disable-next-line:prefer-function-over-method - public async signTypedDataAsync(address: string, typedData: any): Promise { - throw new Error(WalletSubproviderErrors.MethodNotSupported); - } - private async _createLedgerClientAsync(): Promise { - await this._connectionLock.acquire(); - if (this._ledgerClientIfExists !== undefined) { - this._connectionLock.release(); - throw new Error(LedgerSubproviderErrors.MultipleOpenConnectionsDisallowed); - } - const ledgerEthereumClient = await this._ledgerEthereumClientFactoryAsync(); - this._connectionLock.release(); - return ledgerEthereumClient; - } - private async _destroyLedgerClientAsync(): Promise { - await this._connectionLock.acquire(); - if (this._ledgerClientIfExists === undefined) { - this._connectionLock.release(); - return; - } - await this._ledgerClientIfExists.transport.close(); - this._ledgerClientIfExists = undefined; - this._connectionLock.release(); - } - private async _initialDerivedKeyInfoAsync(): Promise { - this._ledgerClientIfExists = await this._createLedgerClientAsync(); - - const parentKeyDerivationPath = `m/${this._baseDerivationPath}`; - let ledgerResponse; - try { - ledgerResponse = await this._ledgerClientIfExists.getAddress( - parentKeyDerivationPath, - this._shouldAlwaysAskForConfirmation, - SHOULD_GET_CHAIN_CODE, - ); - } finally { - await this._destroyLedgerClientAsync(); - } - const hdKey = new HDNode(); - hdKey.publicKey = new Buffer(ledgerResponse.publicKey, 'hex'); - hdKey.chainCode = new Buffer(ledgerResponse.chainCode, 'hex'); - const address = walletUtils.addressOfHDKey(hdKey); - const initialDerivedKeyInfo = { - hdKey, - address, - derivationPath: parentKeyDerivationPath, - baseDerivationPath: this._baseDerivationPath, - }; - return initialDerivedKeyInfo; - } - private _findDerivedKeyInfoForAddress(initalHDKey: DerivedHDKeyInfo, address: string): DerivedHDKeyInfo { - const matchedDerivedKeyInfo = walletUtils.findDerivedKeyInfoForAddressIfExists( - address, - initalHDKey, - this._addressSearchLimit, - ); - if (matchedDerivedKeyInfo === undefined) { - throw new Error(`${WalletSubproviderErrors.AddressNotFound}: ${address}`); - } - return matchedDerivedKeyInfo; - } -} diff --git a/packages/subproviders/src/subproviders/metamask_subprovider.ts b/packages/subproviders/src/subproviders/metamask_subprovider.ts deleted file mode 100644 index 3efb113ef2..0000000000 --- a/packages/subproviders/src/subproviders/metamask_subprovider.ts +++ /dev/null @@ -1,131 +0,0 @@ -import { providerUtils } from '@0x/utils'; -import { marshaller, Web3Wrapper } from '@0x/web3-wrapper'; -import { JSONRPCRequestPayload, SupportedProvider, ZeroExProvider } from 'ethereum-types'; - -import { Callback, ErrorCallback } from '../types'; - -import { Subprovider } from './subprovider'; - -/** - * This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) - * subprovider interface and the provider sendAsync interface. - * It handles inconsistencies with Metamask implementations of various JSON RPC methods. - * It forwards JSON RPC requests involving the domain of a signer (getAccounts, - * sendTransaction, signMessage etc...) to the provider instance supplied at instantiation. All other requests - * are passed onwards for subsequent subproviders to handle. - */ -export class MetamaskSubprovider extends Subprovider { - private readonly _web3Wrapper: Web3Wrapper; - private readonly _provider: ZeroExProvider; - /** - * Instantiates a new MetamaskSubprovider - * @param supportedProvider Web3 provider that should handle all user account related requests - */ - constructor(supportedProvider: SupportedProvider) { - super(); - const provider = providerUtils.standardizeOrThrow(supportedProvider); - this._web3Wrapper = new Web3Wrapper(provider); - this._provider = provider; - } - /** - * This method conforms to the web3-provider-engine interface. - * It is called internally by the ProviderEngine when it is this subproviders - * turn to handle a JSON RPC request. - * @param payload JSON RPC payload - * @param next Callback to call if this subprovider decides not to handle the request - * @param end Callback to call if subprovider handled the request and wants to pass back the request. - */ - // tslint:disable-next-line:prefer-function-over-method async-suffix - public async handleRequest(payload: JSONRPCRequestPayload, next: Callback, end: ErrorCallback): Promise { - let message; - let address; - switch (payload.method) { - case 'web3_clientVersion': - try { - const nodeVersion = await this._web3Wrapper.getNodeVersionAsync(); - end(null, nodeVersion); - } catch (err) { - end(err); - } - return; - case 'eth_accounts': - try { - const accounts = await this._web3Wrapper.getAvailableAddressesAsync(); - end(null, accounts); - } catch (err) { - end(err); - } - return; - case 'eth_sendTransaction': - const [txParams] = payload.params; - try { - const txData = marshaller.unmarshalTxData(txParams); - const txHash = await this._web3Wrapper.sendTransactionAsync(txData); - end(null, txHash); - } catch (err) { - end(err); - } - return; - case 'eth_sign': - [address, message] = payload.params; - try { - // Metamask incorrectly implements eth_sign and does not prefix the message as per the spec - // It does however implement personal_sign and will leave off the prefix when used as a proxy for hardware wallets - // Source: https://metamask.github.io/metamask-docs/API_Reference/Signing_Data/Personal_Sign - // See: https://github.com/MetaMask/eth-ledger-bridge-keyring/blob/master/index.js#L192 - // and https://github.com/MetaMask/eth-trezor-keyring/blob/master/index.js#L211 - // and https://github.com/MetaMask/eth-sig-util/blob/master/index.js#L250 - const signature = await this._web3Wrapper.sendRawPayloadAsync({ - method: 'personal_sign', - params: [message, address], - }); - signature ? end(null, signature) : end(new Error('Error performing eth_sign'), null); - } catch (err) { - end(err); - } - return; - case 'eth_signTypedData': - case 'eth_signTypedData_v3': - [address, message] = payload.params; - try { - // Metamask supports multiple versions and has namespaced signTypedData to v3 for an indeterminate period of time. - // eth_signTypedData is mapped to an older implementation before the spec was finalized. - // Source: https://github.com/MetaMask/metamask-extension/blob/c49d854b55b3efd34c7fd0414b76f7feaa2eec7c/app/scripts/metamask-controller.js#L1262 - // and expects message to be serialised as JSON - const messageJSON = JSON.stringify(message); - const signature = await this._web3Wrapper.sendRawPayloadAsync({ - method: 'eth_signTypedData_v3', - params: [address, messageJSON], - }); - signature ? end(null, signature) : end(new Error('Error performing eth_signTypedData'), null); - } catch (err) { - end(err); - } - return; - default: - next(); - return; - } - } - /** - * This method conforms to the provider sendAsync interface. - * Allowing the MetamaskSubprovider to be used as a generic provider (outside of Web3ProviderEngine) with the - * addition of wrapping the inconsistent Metamask behaviour - * @param payload JSON RPC payload - * @return The contents nested under the result key of the response body - */ - public sendAsync(payload: JSONRPCRequestPayload, callback: ErrorCallback): void { - void this.handleRequest( - payload, - // handleRequest has decided to not handle this, so fall through to the provider - () => { - const sendAsync = this._provider.sendAsync.bind(this._provider); - sendAsync(payload, callback); - }, - // handleRequest has called end and will handle this - (err, data) => { - err ? callback(err) : callback(null, { ...payload, result: data }); - }, - ); - } -} diff --git a/packages/subproviders/src/subproviders/mnemonic_wallet.ts b/packages/subproviders/src/subproviders/mnemonic_wallet.ts deleted file mode 100644 index ef01948e83..0000000000 --- a/packages/subproviders/src/subproviders/mnemonic_wallet.ts +++ /dev/null @@ -1,164 +0,0 @@ -import { assert } from '@0x/assert'; -import { EIP712TypedData } from '@0x/types'; -import { addressUtils } from '@0x/utils'; -import * as bip39 from 'bip39'; -import HDNode = require('hdkey'); -import * as _ from 'lodash'; - -import { DerivedHDKeyInfo, MnemonicWalletSubproviderConfigs, PartialTxParams, WalletSubproviderErrors } from '../types'; -import { walletUtils } from '../utils/wallet_utils'; - -import { BaseWalletSubprovider } from './base_wallet_subprovider'; -import { PrivateKeyWalletSubprovider } from './private_key_wallet'; - -const DEFAULT_BASE_DERIVATION_PATH = `44'/60'/0'/0`; -const DEFAULT_NUM_ADDRESSES_TO_FETCH = 10; -const DEFAULT_ADDRESS_SEARCH_LIMIT = 1000; - -/** - * This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface. - * This subprovider intercepts all account related RPC requests (e.g message/transaction signing, etc...) and handles - * all requests with accounts derived from the supplied mnemonic. - */ -export class MnemonicWalletSubprovider extends BaseWalletSubprovider { - private readonly _addressSearchLimit: number; - private _baseDerivationPath: string; - private _derivedKeyInfo: DerivedHDKeyInfo; - private readonly _mnemonic: string; - - /** - * Instantiates a MnemonicWalletSubprovider. Defaults to baseDerivationPath set to `44'/60'/0'/0`. - * This is the default in TestRPC/Ganache, it can be overridden if desired. - * @param config Configuration for the mnemonic wallet, must contain the mnemonic - * @return MnemonicWalletSubprovider instance - */ - constructor(config: MnemonicWalletSubproviderConfigs) { - assert.isString('mnemonic', config.mnemonic); - const baseDerivationPath = config.baseDerivationPath || DEFAULT_BASE_DERIVATION_PATH; - assert.isString('baseDerivationPath', baseDerivationPath); - const addressSearchLimit = config.addressSearchLimit || DEFAULT_ADDRESS_SEARCH_LIMIT; - assert.isNumber('addressSearchLimit', addressSearchLimit); - super(); - - this._mnemonic = config.mnemonic; - this._baseDerivationPath = baseDerivationPath; - this._addressSearchLimit = addressSearchLimit; - this._derivedKeyInfo = this._initialDerivedKeyInfo(this._baseDerivationPath); - } - /** - * Retrieve the set derivation path - * @returns derivation path - */ - public getPath(): string { - return this._baseDerivationPath; - } - /** - * Set a desired derivation path when computing the available user addresses - * @param baseDerivationPath The desired derivation path (e.g `44'/60'/0'`) - */ - public setPath(baseDerivationPath: string): void { - this._baseDerivationPath = baseDerivationPath; - this._derivedKeyInfo = this._initialDerivedKeyInfo(this._baseDerivationPath); - } - /** - * Retrieve the accounts associated with the mnemonic. - * This method is implicitly called when issuing a `eth_accounts` JSON RPC request - * via your providerEngine instance. - * @param numberOfAccounts Number of accounts to retrieve (default: 10) - * @return An array of accounts - */ - public async getAccountsAsync(numberOfAccounts: number = DEFAULT_NUM_ADDRESSES_TO_FETCH): Promise { - const derivedKeys = walletUtils.calculateDerivedHDKeyInfos(this._derivedKeyInfo, numberOfAccounts); - const accounts = _.map(derivedKeys, k => k.address); - return accounts; - } - - /** - * Signs a transaction with the account specificed by the `from` field in txParams. - * If you've added this Subprovider to your app's provider, you can simply send - * an `eth_sendTransaction` JSON RPC request, and this method will be called auto-magically. - * If you are not using this via a ProviderEngine instance, you can call it directly. - * @param txParams Parameters of the transaction to sign - * @return Signed transaction hex string - */ - public async signTransactionAsync(txParams: PartialTxParams): Promise { - if (txParams.from === undefined || !addressUtils.isAddress(txParams.from)) { - throw new Error(WalletSubproviderErrors.FromAddressMissingOrInvalid); - } - const privateKeyWallet = this._privateKeyWalletForAddress(txParams.from); - const signedTx = privateKeyWallet.signTransactionAsync(txParams); - return signedTx; - } - /** - * Sign a personal Ethereum signed message. The signing account will be the account - * associated with the provided address. If you've added the MnemonicWalletSubprovider to - * your app's provider, you can simply send an `eth_sign` or `personal_sign` JSON RPC request, - * and this method will be called auto-magically. If you are not using this via a ProviderEngine - * instance, you can call it directly. - * @param data Hex string message to sign - * @param address Address of the account to sign with - * @return Signature hex string (order: rsv) - */ - public async signPersonalMessageAsync(data: string, address: string): Promise { - if (data === undefined) { - throw new Error(WalletSubproviderErrors.DataMissingForSignPersonalMessage); - } - assert.isHexString('data', data); - assert.isETHAddressHex('address', address); - const privateKeyWallet = this._privateKeyWalletForAddress(address); - const sig = await privateKeyWallet.signPersonalMessageAsync(data, address); - return sig; - } - /** - * Sign an EIP712 Typed Data message. The signing account will be the account - * associated with the provided address. If you've added this MnemonicWalletSubprovider to - * your app's provider, you can simply send an `eth_signTypedData` JSON RPC request, and - * this method will be called auto-magically. If you are not using this via a ProviderEngine - * instance, you can call it directly. - * @param address Address of the account to sign with - * @param data the typed data object - * @return Signature hex string (order: rsv) - */ - public async signTypedDataAsync(address: string, typedData: EIP712TypedData): Promise { - if (typedData === undefined) { - throw new Error(WalletSubproviderErrors.DataMissingForSignPersonalMessage); - } - assert.isETHAddressHex('address', address); - const privateKeyWallet = this._privateKeyWalletForAddress(address); - const sig = await privateKeyWallet.signTypedDataAsync(address, typedData); - return sig; - } - private _privateKeyWalletForAddress(address: string): PrivateKeyWalletSubprovider { - const derivedKeyInfo = this._findDerivedKeyInfoForAddress(address); - const privateKeyHex = derivedKeyInfo.hdKey.privateKey.toString('hex'); - const privateKeyWallet = new PrivateKeyWalletSubprovider(privateKeyHex); - return privateKeyWallet; - } - private _findDerivedKeyInfoForAddress(address: string): DerivedHDKeyInfo { - const matchedDerivedKeyInfo = walletUtils.findDerivedKeyInfoForAddressIfExists( - address, - this._derivedKeyInfo, - this._addressSearchLimit, - ); - if (matchedDerivedKeyInfo === undefined) { - throw new Error(`${WalletSubproviderErrors.AddressNotFound}: ${address}`); - } - return matchedDerivedKeyInfo; - } - private _initialDerivedKeyInfo(baseDerivationPath: string): DerivedHDKeyInfo { - const seed = bip39.mnemonicToSeed(this._mnemonic); - const hdKey = HDNode.fromMasterSeed(seed); - // Walk down to base derivation level (i.e m/44'/60'/0') and create an initial key at that level - // all children will then be walked relative (i.e m/0) - const parentKeyDerivationPath = `m/${baseDerivationPath}`; - const parentHDKeyAtDerivationPath = hdKey.derive(parentKeyDerivationPath); - const address = walletUtils.addressOfHDKey(parentHDKeyAtDerivationPath); - const derivedKeyInfo = { - address, - baseDerivationPath, - derivationPath: parentKeyDerivationPath, - hdKey: parentHDKeyAtDerivationPath, - }; - return derivedKeyInfo; - } -} diff --git a/packages/subproviders/src/subproviders/nonce_tracker.ts b/packages/subproviders/src/subproviders/nonce_tracker.ts deleted file mode 100644 index 82ff7b6fb3..0000000000 --- a/packages/subproviders/src/subproviders/nonce_tracker.ts +++ /dev/null @@ -1,110 +0,0 @@ -import * as _ from 'lodash'; - -import { BlockParamLiteral, JSONRPCRequestPayload } from 'ethereum-types'; -import EthereumTx = require('ethereumjs-tx'); -import ethUtil = require('ethereumjs-util'); -import providerEngineUtils = require('web3-provider-engine/util/rpc-cache-utils'); - -import { Callback, ErrorCallback, NextCallback, NonceSubproviderErrors } from '../types'; - -import { Subprovider } from './subprovider'; - -const NONCE_TOO_LOW_ERROR_MESSAGE = 'Transaction nonce is too low'; - -/** - * This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface. - * It is heavily inspired by the [NonceSubprovider](https://github.com/MetaMask/provider-engine/blob/master/subproviders/nonce-tracker.js). - * We added the additional feature of clearing the cached nonce value when a `nonce value too low` error occurs. - */ -export class NonceTrackerSubprovider extends Subprovider { - private readonly _nonceCache: { [address: string]: string } = {}; - private static _reconstructTransaction(payload: JSONRPCRequestPayload): EthereumTx { - const raw = payload.params[0]; - if (raw === undefined) { - throw new Error(NonceSubproviderErrors.EmptyParametersFound); - } - const rawData = ethUtil.toBuffer(raw); - const transaction = new EthereumTx(rawData); - return transaction; - } - private static _determineAddress(payload: JSONRPCRequestPayload): string { - let address: string; - switch (payload.method) { - case 'eth_getTransactionCount': - address = payload.params[0].toLowerCase(); - return address; - case 'eth_sendRawTransaction': - const transaction = NonceTrackerSubprovider._reconstructTransaction(payload); - const addressRaw = transaction - .getSenderAddress() - .toString('hex') - .toLowerCase(); - address = `0x${addressRaw}`; - return address; - default: - throw new Error(NonceSubproviderErrors.CannotDetermineAddressFromPayload); - } - } - /** - * This method conforms to the web3-provider-engine interface. - * It is called internally by the ProviderEngine when it is this subproviders - * turn to handle a JSON RPC request. - * @param payload JSON RPC payload - * @param next Callback to call if this subprovider decides not to handle the request - * @param end Callback to call if subprovider handled the request and wants to pass back the request. - */ - // tslint:disable-next-line:async-suffix - public async handleRequest(payload: JSONRPCRequestPayload, next: NextCallback, end: ErrorCallback): Promise { - switch (payload.method) { - case 'eth_getTransactionCount': - const requestDefaultBlock = providerEngineUtils.blockTagForPayload(payload); - if (requestDefaultBlock === BlockParamLiteral.Pending) { - const address = NonceTrackerSubprovider._determineAddress(payload); - const cachedResult = this._nonceCache[address]; - if (cachedResult !== undefined) { - return end(null, cachedResult); - } else { - return next((requestError: Error | null, requestResult: any, cb: Callback) => { - if (requestError === null) { - this._nonceCache[address] = requestResult as string; - } - cb(); - }); - } - } else { - return next(); - } - case 'eth_sendRawTransaction': - return next((sendTransactionError: Error | null, _txResult: any, cb: Callback) => { - if (sendTransactionError === null) { - this._handleSuccessfulTransaction(payload); - } else { - this._handleSendTransactionError(payload, sendTransactionError); - } - cb(); - }); - default: - return next(); - } - } - private _handleSuccessfulTransaction(payload: JSONRPCRequestPayload): void { - const address = NonceTrackerSubprovider._determineAddress(payload); - const transaction = NonceTrackerSubprovider._reconstructTransaction(payload); - // Increment the nonce from the previous successfully submitted transaction - let nonce = ethUtil.bufferToInt(transaction.nonce); - nonce++; - const hexBase = 16; - let nextHexNonce = nonce.toString(hexBase); - if (nextHexNonce.length % 2) { - nextHexNonce = `0${nextHexNonce}`; - } - const nextPrefixedHexNonce = `0x${nextHexNonce}`; - this._nonceCache[address] = nextPrefixedHexNonce; - } - private _handleSendTransactionError(payload: JSONRPCRequestPayload, err: Error): void { - const address = NonceTrackerSubprovider._determineAddress(payload); - if (this._nonceCache[address] && _.includes(err.message, NONCE_TOO_LOW_ERROR_MESSAGE)) { - delete this._nonceCache[address]; - } - } -} diff --git a/packages/subproviders/src/subproviders/private_key_wallet.ts b/packages/subproviders/src/subproviders/private_key_wallet.ts deleted file mode 100644 index 67693ac44d..0000000000 --- a/packages/subproviders/src/subproviders/private_key_wallet.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { assert } from '@0x/assert'; -import { EIP712TypedData } from '@0x/types'; -import { signTypedDataUtils } from '@0x/utils'; -import EthereumTx = require('ethereumjs-tx'); -import * as ethUtil from 'ethereumjs-util'; -import * as _ from 'lodash'; - -import { PartialTxParams, WalletSubproviderErrors } from '../types'; - -import { BaseWalletSubprovider } from './base_wallet_subprovider'; - -/** - * This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface. - * This subprovider intercepts all account related RPC requests (e.g message/transaction signing, etc...) and handles - * all requests with the supplied Ethereum private key. - */ -export class PrivateKeyWalletSubprovider extends BaseWalletSubprovider { - private readonly _address: string; - private readonly _privateKeyBuffer: Buffer; - /** - * Instantiates a PrivateKeyWalletSubprovider. - * @param privateKey The corresponding private key to an Ethereum address - * @return PrivateKeyWalletSubprovider instance - */ - constructor(privateKey: string) { - assert.isString('privateKey', privateKey); - super(); - this._privateKeyBuffer = Buffer.from(privateKey, 'hex'); - this._address = `0x${ethUtil.privateToAddress(this._privateKeyBuffer).toString('hex')}`; - } - /** - * Retrieve the account associated with the supplied private key. - * This method is implicitly called when issuing a `eth_accounts` JSON RPC request - * via your providerEngine instance. - * @return An array of accounts - */ - public async getAccountsAsync(): Promise { - return [this._address]; - } - /** - * Sign a transaction with the private key. If you've added this Subprovider to your - * app's provider, you can simply send an `eth_sendTransaction` JSON RPC request, and - * this method will be called auto-magically. If you are not using this via a ProviderEngine - * instance, you can call it directly. - * @param txParams Parameters of the transaction to sign - * @return Signed transaction hex string - */ - public async signTransactionAsync(txParams: PartialTxParams): Promise { - PrivateKeyWalletSubprovider._validateTxParams(txParams); - if (txParams.from !== undefined && txParams.from.toLowerCase() !== this._address.toLowerCase()) { - throw new Error( - `Requested to sign transaction with address: ${txParams.from}, instantiated with address: ${ - this._address - }`, - ); - } - const tx = new EthereumTx(txParams); - tx.sign(this._privateKeyBuffer); - const rawTx = `0x${tx.serialize().toString('hex')}`; - return rawTx; - } - /** - * Sign a personal Ethereum signed message. The signing address will be calculated from the private key. - * The address must be provided it must match the address calculated from the private key. - * If you've added this Subprovider to your app's provider, you can simply send an `eth_sign` - * or `personal_sign` JSON RPC request, and this method will be called auto-magically. - * If you are not using this via a ProviderEngine instance, you can call it directly. - * @param data Hex string message to sign - * @param address Address of the account to sign with - * @return Signature hex string (order: rsv) - */ - public async signPersonalMessageAsync(data: string, address: string): Promise { - if (data === undefined) { - throw new Error(WalletSubproviderErrors.DataMissingForSignPersonalMessage); - } - assert.isHexString('data', data); - assert.isETHAddressHex('address', address); - if (address !== this._address) { - throw new Error( - `Requested to sign message with address: ${address}, instantiated with address: ${this._address}`, - ); - } - const dataBuff = ethUtil.toBuffer(data); - const msgHashBuff = ethUtil.hashPersonalMessage(dataBuff); - const sig = ethUtil.ecsign(msgHashBuff, this._privateKeyBuffer); - const rpcSig = ethUtil.toRpcSig(sig.v, sig.r, sig.s); - return rpcSig; - } - /** - * Sign an EIP712 Typed Data message. The signing address will be calculated from the private key. - * The address must be provided it must match the address calculated from the private key. - * If you've added this Subprovider to your app's provider, you can simply send an `eth_signTypedData` - * JSON RPC request, and this method will be called auto-magically. - * If you are not using this via a ProviderEngine instance, you can call it directly. - * @param address Address of the account to sign with - * @param data the typed data object - * @return Signature hex string (order: rsv) - */ - public async signTypedDataAsync(address: string, typedData: EIP712TypedData): Promise { - if (typedData === undefined) { - throw new Error(WalletSubproviderErrors.DataMissingForSignTypedData); - } - assert.isETHAddressHex('address', address); - if (address !== this._address) { - throw new Error( - `Requested to sign message with address: ${address}, instantiated with address: ${this._address}`, - ); - } - const dataBuff = signTypedDataUtils.generateTypedDataHash(typedData); - const sig = ethUtil.ecsign(dataBuff, this._privateKeyBuffer); - const rpcSig = ethUtil.toRpcSig(sig.v, sig.r, sig.s); - return rpcSig; - } -} diff --git a/packages/subproviders/src/subproviders/redundant_subprovider.ts b/packages/subproviders/src/subproviders/redundant_subprovider.ts deleted file mode 100644 index d9d2d97c22..0000000000 --- a/packages/subproviders/src/subproviders/redundant_subprovider.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { promisify } from '@0x/utils'; -import { JSONRPCRequestPayload } from 'ethereum-types'; - -import { Callback } from '../types'; - -import { Subprovider } from './subprovider'; - -/** - * This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface. - * It attempts to handle each JSON RPC request by sequentially attempting to receive a valid response from one of a - * set of JSON RPC endpoints. - */ -export class RedundantSubprovider extends Subprovider { - private readonly _subproviders: Subprovider[]; - private static async _firstSuccessAsync( - subproviders: Subprovider[], - payload: JSONRPCRequestPayload, - next: Callback, - ): Promise { - let lastErr: Error | undefined; - for (const subprovider of subproviders) { - try { - const data = await promisify(subprovider.handleRequest.bind(subprovider))(payload, next); - return data; - } catch (err) { - lastErr = err; - continue; - } - } - if (lastErr !== undefined) { - throw lastErr; - } - } - /** - * Instantiates a new RedundantSubprovider - * @param subproviders Subproviders to attempt the request with - */ - constructor(subproviders: Subprovider[]) { - super(); - this._subproviders = subproviders; - } - /** - * This method conforms to the web3-provider-engine interface. - * It is called internally by the ProviderEngine when it is this subproviders - * turn to handle a JSON RPC request. - * @param payload JSON RPC payload - * @param next Callback to call if this subprovider decides not to handle the request - * @param end Callback to call if subprovider handled the request and wants to pass back the request. - */ - // tslint:disable-next-line:async-suffix - public async handleRequest( - payload: JSONRPCRequestPayload, - next: Callback, - end: (err: Error | null, data?: any) => void, - ): Promise { - const subprovidersCopy = this._subproviders.slice(); - try { - const data = await RedundantSubprovider._firstSuccessAsync(subprovidersCopy, payload, next); - end(null, data); - } catch (err) { - end(err); - } - } -} diff --git a/packages/subproviders/src/subproviders/rpc_subprovider.ts b/packages/subproviders/src/subproviders/rpc_subprovider.ts deleted file mode 100644 index 437518e127..0000000000 --- a/packages/subproviders/src/subproviders/rpc_subprovider.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { assert } from '@0x/assert'; -import { StatusCodes } from '@0x/types'; -import { fetchAsync } from '@0x/utils'; -import { JSONRPCRequestPayload } from 'ethereum-types'; -import JsonRpcError = require('json-rpc-error'); - -import { Callback, ErrorCallback } from '../types'; - -import { Subprovider } from './subprovider'; - -/** - * This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface. - * It forwards on JSON RPC requests to the supplied `rpcUrl` endpoint - */ -export class RPCSubprovider extends Subprovider { - private readonly _rpcUrl: string; - private readonly _requestTimeoutMs: number; - /** - * @param rpcUrl URL to the backing Ethereum node to which JSON RPC requests should be sent - * @param requestTimeoutMs Amount of miliseconds to wait before timing out the JSON RPC request - */ - constructor(rpcUrl: string, requestTimeoutMs: number = 20000) { - super(); - assert.isString('rpcUrl', rpcUrl); - assert.isNumber('requestTimeoutMs', requestTimeoutMs); - this._rpcUrl = rpcUrl; - this._requestTimeoutMs = requestTimeoutMs; - } - /** - * This method conforms to the web3-provider-engine interface. - * It is called internally by the ProviderEngine when it is this subproviders - * turn to handle a JSON RPC request. - * @param payload JSON RPC payload - * @param _next Callback to call if this subprovider decides not to handle the request - * @param end Callback to call if subprovider handled the request and wants to pass back the request. - */ - // tslint:disable-next-line:prefer-function-over-method async-suffix - public async handleRequest(payload: JSONRPCRequestPayload, _next: Callback, end: ErrorCallback): Promise { - const finalPayload = Subprovider._createFinalPayload(payload); - const headers = new Headers({ - Accept: 'application/json', - 'Content-Type': 'application/json', - }); - - let response; - try { - response = await fetchAsync( - this._rpcUrl, - { - method: 'POST', - headers, - body: JSON.stringify(finalPayload), - }, - this._requestTimeoutMs, - ); - } catch (err) { - end(new JsonRpcError.InternalError(err)); - return; - } - - const text = await response.text(); - if (!response.ok) { - const statusCode = response.status; - switch (statusCode) { - case StatusCodes.MethodNotAllowed: - end(new JsonRpcError.MethodNotFound()); - return; - case StatusCodes.GatewayTimeout: - const errMsg = - 'Gateway timeout. The request took too long to process. This can happen when querying logs over too wide a block range.'; - const err = new Error(errMsg); - end(new JsonRpcError.InternalError(err)); - return; - default: - end(new JsonRpcError.InternalError(text)); - return; - } - } - - let data; - try { - data = JSON.parse(text); - } catch (err) { - end(new JsonRpcError.InternalError(err)); - return; - } - - if (data.error) { - end(data.error); - return; - } - end(null, data.result); - } -} diff --git a/packages/subproviders/src/subproviders/signer.ts b/packages/subproviders/src/subproviders/signer.ts deleted file mode 100644 index 21752c4069..0000000000 --- a/packages/subproviders/src/subproviders/signer.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { marshaller, Web3Wrapper } from '@0x/web3-wrapper'; -import { JSONRPCRequestPayload, SupportedProvider } from 'ethereum-types'; - -import { Callback, ErrorCallback } from '../types'; - -import { Subprovider } from './subprovider'; - -/** - * This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) - * subprovider interface. It forwards JSON RPC requests involving the domain of a signer (getAccounts, - * sendTransaction, signMessage etc...) to the provider instance supplied at instantiation. All other requests - * are passed onwards for subsequent subproviders to handle. - */ -export class SignerSubprovider extends Subprovider { - private readonly _web3Wrapper: Web3Wrapper; - /** - * Instantiates a new SignerSubprovider. - * @param supportedProvider Web3 provider that should handle all user account related requests - */ - constructor(supportedProvider: SupportedProvider) { - super(); - this._web3Wrapper = new Web3Wrapper(supportedProvider); - } - /** - * This method conforms to the web3-provider-engine interface. - * It is called internally by the ProviderEngine when it is this subproviders - * turn to handle a JSON RPC request. - * @param payload JSON RPC payload - * @param next Callback to call if this subprovider decides not to handle the request - * @param end Callback to call if subprovider handled the request and wants to pass back the request. - */ - // tslint:disable-next-line:prefer-function-over-method async-suffix - public async handleRequest(payload: JSONRPCRequestPayload, next: Callback, end: ErrorCallback): Promise { - let message; - let address; - switch (payload.method) { - case 'web3_clientVersion': - try { - const nodeVersion = await this._web3Wrapper.getNodeVersionAsync(); - end(null, nodeVersion); - } catch (err) { - end(err); - } - return; - case 'eth_accounts': - try { - const accounts = await this._web3Wrapper.getAvailableAddressesAsync(); - end(null, accounts); - } catch (err) { - end(err); - } - return; - case 'eth_sendTransaction': - const [txParams] = payload.params; - try { - const txData = marshaller.unmarshalTxData(txParams); - const txHash = await this._web3Wrapper.sendTransactionAsync(txData); - end(null, txHash); - } catch (err) { - end(err); - } - return; - case 'eth_sign': - [address, message] = payload.params; - try { - const signature = await this._web3Wrapper.signMessageAsync(address, message); - end(null, signature); - } catch (err) { - end(err); - } - return; - case 'eth_signTypedData': - [address, message] = payload.params; - try { - const signature = await this._web3Wrapper.signTypedDataAsync(address, message); - end(null, signature); - } catch (err) { - end(err); - } - return; - default: - next(); - return; - } - } -} diff --git a/packages/subproviders/src/subproviders/subprovider.ts b/packages/subproviders/src/subproviders/subprovider.ts deleted file mode 100644 index 444a8786bf..0000000000 --- a/packages/subproviders/src/subproviders/subprovider.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { promisify } from '@0x/utils'; -import { JSONRPCRequestPayload, JSONRPCResponsePayload } from 'ethereum-types'; -import Web3ProviderEngine = require('web3-provider-engine'); - -import { Callback, ErrorCallback, JSONRPCRequestPayloadWithMethod } from '../types'; -/** - * A altered version of the base class Subprovider found in [web3-provider-engine](https://github.com/MetaMask/provider-engine). - * This one has an async/await `emitPayloadAsync` and also defined types. - */ -export abstract class Subprovider { - // tslint:disable-next-line:underscore-private-and-protected - private engine!: Web3ProviderEngine; - protected static _createFinalPayload( - payload: Partial, - ): Partial { - const finalPayload = { - // defaults - id: Subprovider._getRandomId(), - jsonrpc: '2.0', - params: [], - ...payload, - }; - return finalPayload; - } - // Ported from: https://github.com/MetaMask/provider-engine/blob/master/util/random-id.js - private static _getRandomId(): number { - const extraDigits = 3; - const baseTen = 10; - // 13 time digits - const datePart = new Date().getTime() * Math.pow(baseTen, extraDigits); - // 3 random digits - const extraPart = Math.floor(Math.random() * Math.pow(baseTen, extraDigits)); - // 16 digits - return datePart + extraPart; - } - /** - * @param payload JSON RPC request payload - * @param next A callback to pass the request to the next subprovider in the stack - * @param end A callback called once the subprovider is done handling the request - */ - // tslint:disable-next-line:async-suffix - public abstract async handleRequest( - payload: JSONRPCRequestPayload, - next: Callback, - end: ErrorCallback, - ): Promise; - - /** - * Emits a JSON RPC payload that will then be handled by the ProviderEngine instance - * this subprovider is a part of. The payload will cascade down the subprovider middleware - * stack until finding the responsible entity for handling the request. - * @param payload JSON RPC payload - * @returns JSON RPC response payload - */ - public async emitPayloadAsync(payload: Partial): Promise { - const finalPayload = Subprovider._createFinalPayload(payload); - // Promisify does the binding internally and `this` is supplied as a second argument - // tslint:disable-next-line:no-unbound-method - const response = await promisify(this.engine.sendAsync, this.engine)(finalPayload); - return response; - } - /** - * Set's the subprovider's engine to the ProviderEngine it is added to. - * This is only called within the ProviderEngine source code, do not call - * directly. - * @param engine The ProviderEngine this subprovider is added to - */ - public setEngine(engine: Web3ProviderEngine): void { - this.engine = engine; - } -} diff --git a/packages/subproviders/src/subproviders/trezor.ts b/packages/subproviders/src/subproviders/trezor.ts deleted file mode 100644 index 354cea2681..0000000000 --- a/packages/subproviders/src/subproviders/trezor.ts +++ /dev/null @@ -1,205 +0,0 @@ -import { assert } from '@0x/assert'; -import { addressUtils } from '@0x/utils'; -import EthereumTx = require('ethereumjs-tx'); -import * as _ from 'lodash'; - -import HDNode = require('hdkey'); - -import { - DerivedHDKeyInfo, - PartialTxParams, - TrezorConnectResponse, - TrezorGetPublicKeyResponsePayload, - TrezorResponseErrorPayload, - TrezorSignMsgResponsePayload, - TrezorSignTxResponsePayload, - TrezorSubproviderConfig, - WalletSubproviderErrors, -} from '../types'; -import { walletUtils } from '../utils/wallet_utils'; - -import { BaseWalletSubprovider } from './base_wallet_subprovider'; - -const PRIVATE_KEY_PATH = `44'/60'/0'/0`; -const DEFAULT_NUM_ADDRESSES_TO_FETCH = 10; -const DEFAULT_ADDRESS_SEARCH_LIMIT = 1000; - -export class TrezorSubprovider extends BaseWalletSubprovider { - private readonly _privateKeyPath: string; - private readonly _trezorConnectClientApi: any; - private readonly _networkId: number; - private readonly _addressSearchLimit: number; - private _initialDerivedKeyInfo: DerivedHDKeyInfo | undefined; - /** - * Instantiates a TrezorSubprovider. Defaults to private key path set to `44'/60'/0'/0/`. - * Must be initialized with trezor-connect API module https://github.com/trezor/connect. - * @param TrezorSubprovider config object containing trezor-connect API - * @return TrezorSubprovider instance - */ - constructor(config: TrezorSubproviderConfig) { - super(); - this._privateKeyPath = PRIVATE_KEY_PATH; - this._trezorConnectClientApi = config.trezorConnectClientApi; - this._networkId = config.networkId; - this._addressSearchLimit = - config.accountFetchingConfigs !== undefined && - config.accountFetchingConfigs.addressSearchLimit !== undefined - ? config.accountFetchingConfigs.addressSearchLimit - : DEFAULT_ADDRESS_SEARCH_LIMIT; - } - /** - * Retrieve a users Trezor account. This method is automatically called - * when issuing a `eth_accounts` JSON RPC request via your providerEngine - * instance. - * @return An array of accounts - */ - public async getAccountsAsync(numberOfAccounts: number = DEFAULT_NUM_ADDRESSES_TO_FETCH): Promise { - const initialDerivedKeyInfo = await this._initialDerivedKeyInfoAsync(); - const derivedKeyInfos = walletUtils.calculateDerivedHDKeyInfos(initialDerivedKeyInfo, numberOfAccounts); - const accounts = _.map(derivedKeyInfos, k => k.address); - return accounts; - } - /** - * Signs a transaction on the Trezor with the account specificed by the `from` field in txParams. - * If you've added the TrezorSubprovider to your app's provider, you can simply send an `eth_sendTransaction` - * JSON RPC request, and this method will be called auto-magically. If you are not using this via a ProviderEngine - * instance, you can call it directly. - * @param txParams Parameters of the transaction to sign - * @return Signed transaction hex string - */ - public async signTransactionAsync(txData: PartialTxParams): Promise { - if (txData.from === undefined || !addressUtils.isAddress(txData.from)) { - throw new Error(WalletSubproviderErrors.FromAddressMissingOrInvalid); - } - txData.value = txData.value ? txData.value : '0x0'; - txData.data = txData.data ? txData.data : '0x'; - txData.gas = txData.gas ? txData.gas : '0x0'; - txData.gasPrice = txData.gasPrice ? txData.gasPrice : '0x0'; - - const initialDerivedKeyInfo = await this._initialDerivedKeyInfoAsync(); - const derivedKeyInfo = this._findDerivedKeyInfoForAddress(initialDerivedKeyInfo, txData.from); - const fullDerivationPath = derivedKeyInfo.derivationPath; - - const response: TrezorConnectResponse = await this._trezorConnectClientApi.ethereumSignTransaction({ - path: fullDerivationPath, - transaction: { - to: txData.to, - value: txData.value, - data: txData.data, - chainId: this._networkId, - nonce: txData.nonce, - gasLimit: txData.gas, - gasPrice: txData.gasPrice, - }, - }); - - if (response.success) { - const payload: TrezorSignTxResponsePayload = response.payload; - const tx = new EthereumTx(txData); - - // Set the EIP155 bits - const vIndex = 6; - tx.raw[vIndex] = Buffer.from([1]); // v - const rIndex = 7; - tx.raw[rIndex] = Buffer.from([]); // r - const sIndex = 8; - tx.raw[sIndex] = Buffer.from([]); // s - - // slice off leading 0x - tx.v = Buffer.from(payload.v.slice(2), 'hex'); - tx.r = Buffer.from(payload.r.slice(2), 'hex'); - tx.s = Buffer.from(payload.s.slice(2), 'hex'); - - return `0x${tx.serialize().toString('hex')}`; - } else { - const payload: TrezorResponseErrorPayload = response.payload; - throw new Error(payload.error); - } - } - /** - * Sign a personal Ethereum signed message. The signing account will be the account - * associated with the provided address. If you've added the TrezorSubprovider to - * your app's provider, you can simply send an `eth_sign` or `personal_sign` JSON RPC - * request, and this method will be called auto-magically. - * If you are not using this via a ProviderEngine instance, you can call it directly. - * @param data Hex string message to sign - * @param address Address of the account to sign with - * @return Signature hex string (order: rsv) - */ - public async signPersonalMessageAsync(data: string, address: string): Promise { - if (data === undefined) { - throw new Error(WalletSubproviderErrors.DataMissingForSignPersonalMessage); - } - assert.isHexString('data', data); - assert.isETHAddressHex('address', address); - - const initialDerivedKeyInfo = await this._initialDerivedKeyInfoAsync(); - const derivedKeyInfo = this._findDerivedKeyInfoForAddress(initialDerivedKeyInfo, address); - const fullDerivationPath = derivedKeyInfo.derivationPath; - - const response: TrezorConnectResponse = await this._trezorConnectClientApi.ethereumSignMessage({ - path: fullDerivationPath, - message: data, - hex: true, - }); - - if (response.success) { - const payload: TrezorSignMsgResponsePayload = response.payload; - return `0x${payload.signature}`; - } else { - const payload: TrezorResponseErrorPayload = response.payload; - throw new Error(payload.error); - } - } - /** - * TODO:: eth_signTypedData is currently not supported on Trezor devices. - * @param address Address of the account to sign with - * @param data the typed data object - * @return Signature hex string (order: rsv) - */ - // tslint:disable-next-line:prefer-function-over-method - public async signTypedDataAsync(address: string, typedData: any): Promise { - throw new Error(WalletSubproviderErrors.MethodNotSupported); - } - private async _initialDerivedKeyInfoAsync(): Promise { - if (this._initialDerivedKeyInfo) { - return this._initialDerivedKeyInfo; - } else { - const parentKeyDerivationPath = `m/${this._privateKeyPath}`; - - const response: TrezorConnectResponse = await this._trezorConnectClientApi.getPublicKey({ - path: parentKeyDerivationPath, - }); - - if (response.success) { - const payload: TrezorGetPublicKeyResponsePayload = response.payload; - const hdKey = new HDNode(); - hdKey.publicKey = new Buffer(payload.publicKey, 'hex'); - hdKey.chainCode = new Buffer(payload.chainCode, 'hex'); - const address = walletUtils.addressOfHDKey(hdKey); - const initialDerivedKeyInfo = { - hdKey, - address, - derivationPath: parentKeyDerivationPath, - baseDerivationPath: this._privateKeyPath, - }; - this._initialDerivedKeyInfo = initialDerivedKeyInfo; - return initialDerivedKeyInfo; - } else { - const payload: TrezorResponseErrorPayload = response.payload; - throw new Error(payload.error); - } - } - } - private _findDerivedKeyInfoForAddress(initalHDKey: DerivedHDKeyInfo, address: string): DerivedHDKeyInfo { - const matchedDerivedKeyInfo = walletUtils.findDerivedKeyInfoForAddressIfExists( - address, - initalHDKey, - this._addressSearchLimit, - ); - if (matchedDerivedKeyInfo === undefined) { - throw new Error(`${WalletSubproviderErrors.AddressNotFound}: ${address}`); - } - return matchedDerivedKeyInfo; - } -} diff --git a/packages/subproviders/src/types.ts b/packages/subproviders/src/types.ts deleted file mode 100644 index 2cb4ae4cfa..0000000000 --- a/packages/subproviders/src/types.ts +++ /dev/null @@ -1,177 +0,0 @@ -import { ECSignature } from '@0x/types'; -import { JSONRPCRequestPayload } from 'ethereum-types'; -import HDNode = require('hdkey'); -export interface LedgerCommunicationClient { - close: () => Promise; -} - -/** - * Elliptic Curve signature - * The LedgerEthereumClient sends Ethereum-specific requests to the Ledger Nano S - * It uses an internal LedgerCommunicationClient to relay these requests. Currently - * NodeJs and Browser communication are supported. - */ -export interface LedgerEthereumClient { - // shouldGetChainCode is defined as `true` instead of `boolean` because other types rely on the assumption - // that we get back the chain code and we don't have dependent types to express it properly - getAddress: ( - derivationPath: string, - askForDeviceConfirmation: boolean, - shouldGetChainCode: true, - ) => Promise; - signTransaction: (derivationPath: string, rawTxHex: string) => Promise; - signPersonalMessage: (derivationPath: string, messageHex: string) => Promise; - transport: LedgerCommunicationClient; -} - -export interface ECSignatureString { - v: string; - r: string; - s: string; -} - -export type LedgerEthereumClientFactoryAsync = () => Promise; - -/** - * networkId: The ethereum networkId to set as the chainId from EIP155 - * ledgerConnectionType: Environment in which you wish to connect to Ledger (nodejs or browser) - * derivationPath: Initial derivation path to use e.g 44'/60'/0' - * accountFetchingConfigs: configs related to fetching accounts from a Ledger - */ -export interface LedgerSubproviderConfigs { - networkId: number; - ledgerEthereumClientFactoryAsync: LedgerEthereumClientFactoryAsync; - baseDerivationPath?: string; - accountFetchingConfigs?: AccountFetchingConfigs; -} - -/** - * addressSearchLimit: The maximum number of addresses to search through, defaults to 1000 - * numAddressesToReturn: Number of addresses to return from 'eth_accounts' call - * shouldAskForOnDeviceConfirmation: Whether you wish to prompt the user on their Ledger - * before fetching their addresses - */ -export interface AccountFetchingConfigs { - addressSearchLimit?: number; - numAddressesToReturn?: number; - shouldAskForOnDeviceConfirmation?: boolean; -} - -/** - * mnemonic: The string mnemonic seed - * addressSearchLimit: The maximum number of addresses to search through, defaults to 1000 - * baseDerivationPath: The base derivation path (e.g 44'/60'/0'/0) - */ -export interface MnemonicWalletSubproviderConfigs { - mnemonic: string; - addressSearchLimit?: number; - baseDerivationPath?: string; -} - -export interface SignatureData { - hash: string; - r: string; - s: string; - v: number; -} - -export interface LedgerGetAddressResult { - address: string; - publicKey: string; - chainCode: string; -} - -export interface PartialTxParams { - nonce: string; - gasPrice?: string; - gas: string; - to: string; - from: string; - value?: string; - data?: string; - chainId: number; // EIP 155 chainId - mainnet: 1, ropsten: 3 -} - -export type DoneCallback = (err?: Error) => void; - -export interface LedgerCommunication { - close_async: () => Promise; -} - -export interface ResponseWithTxParams { - raw: string; - tx: PartialTxParams; -} - -export enum WalletSubproviderErrors { - AddressNotFound = 'ADDRESS_NOT_FOUND', - DataMissingForSignPersonalMessage = 'DATA_MISSING_FOR_SIGN_PERSONAL_MESSAGE', - DataMissingForSignTypedData = 'DATA_MISSING_FOR_SIGN_TYPED_DATA', - SenderInvalidOrNotSupplied = 'SENDER_INVALID_OR_NOT_SUPPLIED', - FromAddressMissingOrInvalid = 'FROM_ADDRESS_MISSING_OR_INVALID', - MethodNotSupported = 'METHOD_NOT_SUPPORTED', -} -export enum LedgerSubproviderErrors { - TooOldLedgerFirmware = 'TOO_OLD_LEDGER_FIRMWARE', - MultipleOpenConnectionsDisallowed = 'MULTIPLE_OPEN_CONNECTIONS_DISALLOWED', -} - -export enum NonceSubproviderErrors { - EmptyParametersFound = 'EMPTY_PARAMETERS_FOUND', - CannotDetermineAddressFromPayload = 'CANNOT_DETERMINE_ADDRESS_FROM_PAYLOAD', -} -export interface DerivedHDKeyInfo { - address: string; - baseDerivationPath: string; - derivationPath: string; - hdKey: HDNode; -} - -export type ErrorCallback = (err: Error | null, data?: any) => void; -export type Callback = () => void; -export type OnNextCompleted = (err: Error | null, result: any, cb: Callback) => void; -export type NextCallback = (callback?: OnNextCompleted) => void; - -export interface JSONRPCRequestPayloadWithMethod extends JSONRPCRequestPayload { - method: string; -} - -export interface TrezorSubproviderConfig { - accountFetchingConfigs: AccountFetchingConfigs; - trezorConnectClientApi: any; - networkId: number; -} - -export interface TrezorGetPublicKeyResponsePayload { - path: { - [index: number]: number; - }; - serializedPath: string; - childNumb: number; - xpub: string; - chainCode: string; - publicKey: string; - fingerprint: number; - depth: number; -} - -export interface TrezorSignTxResponsePayload { - v: string; - r: string; - s: string; -} - -export interface TrezorSignMsgResponsePayload { - address: string; - signature: string; -} - -export interface TrezorResponseErrorPayload { - error: string; -} - -export interface TrezorConnectResponse { - payload: any; - id: number; - success: boolean; -} diff --git a/packages/subproviders/src/utils/subprovider_utils.ts b/packages/subproviders/src/utils/subprovider_utils.ts deleted file mode 100644 index beda408ab3..0000000000 --- a/packages/subproviders/src/utils/subprovider_utils.ts +++ /dev/null @@ -1,15 +0,0 @@ -import Web3ProviderEngine = require('web3-provider-engine'); - -import { Subprovider } from '../subproviders/subprovider'; - -/** - * Prepends a subprovider to a provider - * @param provider Given provider - * @param subprovider Subprovider to prepend - */ -export function prependSubprovider(provider: Web3ProviderEngine, subprovider: Subprovider): void { - subprovider.setEngine(provider); - // HACK: We use implementation details of provider engine here - // https://github.com/MetaMask/provider-engine/blob/master/index.js#L68 - (provider as any)._providers = [subprovider, ...(provider as any)._providers]; -} diff --git a/packages/subproviders/src/utils/wallet_utils.ts b/packages/subproviders/src/utils/wallet_utils.ts deleted file mode 100644 index 7027ca8a0a..0000000000 --- a/packages/subproviders/src/utils/wallet_utils.ts +++ /dev/null @@ -1,79 +0,0 @@ -import ethUtil = require('ethereumjs-util'); -import HDNode = require('hdkey'); - -import { DerivedHDKeyInfo } from '../types'; - -const DEFAULT_ADDRESS_SEARCH_LIMIT = 1000; - -class DerivedHDKeyInfoIterator implements IterableIterator { - private readonly _parentDerivedKeyInfo: DerivedHDKeyInfo; - private readonly _searchLimit: number; - private _index: number; - - constructor(initialDerivedKey: DerivedHDKeyInfo, searchLimit: number = DEFAULT_ADDRESS_SEARCH_LIMIT) { - this._searchLimit = searchLimit; - this._parentDerivedKeyInfo = initialDerivedKey; - this._index = 0; - } - - public next(): IteratorResult { - const baseDerivationPath = this._parentDerivedKeyInfo.baseDerivationPath; - const derivationIndex = this._index; - const fullDerivationPath = `m/${baseDerivationPath}/${derivationIndex}`; - const path = `m/${derivationIndex}`; - const hdKey = this._parentDerivedKeyInfo.hdKey.derive(path); - const address = walletUtils.addressOfHDKey(hdKey); - const derivedKey: DerivedHDKeyInfo = { - address, - hdKey, - baseDerivationPath, - derivationPath: fullDerivationPath, - }; - const isDone = this._index === this._searchLimit; - this._index++; - return { - done: isDone, - value: derivedKey, - }; - } - - public [Symbol.iterator](): IterableIterator { - return this; - } -} - -export const walletUtils = { - calculateDerivedHDKeyInfos(parentDerivedKeyInfo: DerivedHDKeyInfo, numberOfKeys: number): DerivedHDKeyInfo[] { - const derivedKeys: DerivedHDKeyInfo[] = []; - const derivedKeyIterator = new DerivedHDKeyInfoIterator(parentDerivedKeyInfo, numberOfKeys); - for (const key of derivedKeyIterator) { - derivedKeys.push(key); - } - return derivedKeys; - }, - findDerivedKeyInfoForAddressIfExists( - address: string, - parentDerivedKeyInfo: DerivedHDKeyInfo, - searchLimit: number, - ): DerivedHDKeyInfo | undefined { - const lowercaseAddress = address.toLowerCase(); - let matchedKey: DerivedHDKeyInfo | undefined; - const derivedKeyIterator = new DerivedHDKeyInfoIterator(parentDerivedKeyInfo, searchLimit); - for (const key of derivedKeyIterator) { - if (key.address === lowercaseAddress) { - matchedKey = key; - break; - } - } - return matchedKey; - }, - addressOfHDKey(hdKey: HDNode): string { - const shouldSanitizePublicKey = true; - const derivedPublicKey = hdKey.publicKey; - const ethereumAddressUnprefixed = ethUtil - .publicToAddress(derivedPublicKey, shouldSanitizePublicKey) - .toString('hex'); - const address = ethUtil.addHexPrefix(ethereumAddressUnprefixed).toLowerCase(); - return address; - }, -}; diff --git a/packages/subproviders/test/chai_setup.ts b/packages/subproviders/test/chai_setup.ts deleted file mode 100644 index 6c24dc2225..0000000000 --- a/packages/subproviders/test/chai_setup.ts +++ /dev/null @@ -1,11 +0,0 @@ -import * as chai from 'chai'; -import chaiAsPromised = require('chai-as-promised'); -import * as dirtyChai from 'dirty-chai'; - -export const chaiSetup = { - configure(): void { - chai.config.includeStack = true; - chai.use(dirtyChai); - chai.use(chaiAsPromised); - }, -}; diff --git a/packages/subproviders/test/integration/ledger_subprovider_test.ts b/packages/subproviders/test/integration/ledger_subprovider_test.ts deleted file mode 100644 index 347a97380a..0000000000 --- a/packages/subproviders/test/integration/ledger_subprovider_test.ts +++ /dev/null @@ -1,205 +0,0 @@ -import { DoneCallback } from '@0x/types'; -import { promisify, providerUtils } from '@0x/utils'; -import Eth from '@ledgerhq/hw-app-eth'; -// HACK: This dependency is optional and tslint skips optional dependencies -// tslint:disable-next-line:no-implicit-dependencies -import TransportNodeHid from '@ledgerhq/hw-transport-node-hid'; -import * as chai from 'chai'; -import { JSONRPCResponsePayload } from 'ethereum-types'; -import * as ethUtils from 'ethereumjs-util'; - -import { LedgerSubprovider, RPCSubprovider, Web3ProviderEngine } from '../../src'; -import { LedgerEthereumClient } from '../../src/types'; -import { chaiSetup } from '../chai_setup'; -import { fixtureData } from '../utils/fixture_data'; -import { reportCallbackErrors } from '../utils/report_callback_errors'; - -chaiSetup.configure(); -const expect = chai.expect; -const DEFAULT_NUM_ACCOUNTS = 10; -const EXPECTED_SIGNATURE_LENGTH = 132; - -async function ledgerEthereumNodeJsClientFactoryAsync(): Promise { - const ledgerConnection = await TransportNodeHid.create(); - const ledgerEthClient = new Eth(ledgerConnection); - return ledgerEthClient; -} - -describe('LedgerSubprovider', () => { - let ledgerSubprovider: LedgerSubprovider; - const networkId: number = fixtureData.NETWORK_ID; - before(async () => { - ledgerSubprovider = new LedgerSubprovider({ - networkId, - ledgerEthereumClientFactoryAsync: ledgerEthereumNodeJsClientFactoryAsync, - baseDerivationPath: fixtureData.TESTRPC_BASE_DERIVATION_PATH, - }); - }); - describe('direct method calls', () => { - it('returns default number of accounts', async () => { - const accounts = await ledgerSubprovider.getAccountsAsync(); - expect(accounts[0]).to.not.be.an('undefined'); - expect(accounts.length).to.be.equal(DEFAULT_NUM_ACCOUNTS); - }); - it('returns the expected accounts from a ledger set up with the test mnemonic', async () => { - const accounts = await ledgerSubprovider.getAccountsAsync(); - expect(accounts[0]).to.be.equal(fixtureData.TEST_RPC_ACCOUNT_0); - expect(accounts[1]).to.be.equal(fixtureData.TEST_RPC_ACCOUNT_1); - }); - it('returns requested number of accounts', async () => { - const numberOfAccounts = 20; - const accounts = await ledgerSubprovider.getAccountsAsync(numberOfAccounts); - expect(accounts[0]).to.not.be.an('undefined'); - expect(accounts.length).to.be.equal(numberOfAccounts); - }); - it('signs a personal message', async () => { - const data = ethUtils.bufferToHex(ethUtils.toBuffer(fixtureData.PERSONAL_MESSAGE_STRING)); - const ecSignatureHex = await ledgerSubprovider.signPersonalMessageAsync( - data, - fixtureData.TEST_RPC_ACCOUNT_0, - ); - expect(ecSignatureHex).to.be.equal(fixtureData.PERSONAL_MESSAGE_SIGNED_RESULT); - }); - it('signs a personal message with second address', async () => { - const data = ethUtils.bufferToHex(ethUtils.toBuffer(fixtureData.PERSONAL_MESSAGE_STRING)); - const ecSignatureHex = await ledgerSubprovider.signPersonalMessageAsync( - data, - fixtureData.TEST_RPC_ACCOUNT_1, - ); - expect(ecSignatureHex).to.be.equal(fixtureData.PERSONAL_MESSAGE_ACCOUNT_1_SIGNED_RESULT); - }); - it('signs a transaction', async () => { - const txHex = await ledgerSubprovider.signTransactionAsync(fixtureData.TX_DATA); - expect(txHex).to.be.equal(fixtureData.TX_DATA_SIGNED_RESULT); - }); - it('signs a transaction with the second address', async () => { - const txData = { ...fixtureData.TX_DATA, from: fixtureData.TEST_RPC_ACCOUNT_1 }; - const txHex = await ledgerSubprovider.signTransactionAsync(txData); - expect(txHex).to.be.equal(fixtureData.TX_DATA_ACCOUNT_1_SIGNED_RESULT); - }); - }); - describe('calls through a provider', () => { - let defaultProvider: Web3ProviderEngine; - let ledgerProvider: Web3ProviderEngine; - before(() => { - ledgerProvider = new Web3ProviderEngine(); - ledgerProvider.addProvider(ledgerSubprovider); - const httpProvider = new RPCSubprovider('http://localhost:8545'); - ledgerProvider.addProvider(httpProvider); - providerUtils.startProviderEngine(ledgerProvider); - - defaultProvider = new Web3ProviderEngine(); - defaultProvider.addProvider(httpProvider); - providerUtils.startProviderEngine(defaultProvider); - }); - it('returns a list of accounts', (done: DoneCallback) => { - const payload = { - jsonrpc: '2.0', - method: 'eth_accounts', - params: [], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { - expect(err).to.be.a('null'); - expect(response.result.length).to.be.equal(DEFAULT_NUM_ACCOUNTS); - done(); - }); - ledgerProvider.sendAsync(payload, callback); - }); - it('signs a personal message with eth_sign', (done: DoneCallback) => { - (async () => { - const messageHex = ethUtils.bufferToHex(ethUtils.toBuffer('hello world')); - const accounts = await ledgerSubprovider.getAccountsAsync(); - const signer = accounts[0]; - const payload = { - jsonrpc: '2.0', - method: 'eth_sign', - params: [signer, messageHex], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { - expect(err).to.be.a('null'); - expect(response.result.length).to.be.equal(EXPECTED_SIGNATURE_LENGTH); - expect(response.result.substr(0, 2)).to.be.equal('0x'); - done(); - }); - ledgerProvider.sendAsync(payload, callback); - })().catch(done); - }); - it('signs a personal message with personal_sign', (done: DoneCallback) => { - (async () => { - const messageHex = ethUtils.bufferToHex(ethUtils.toBuffer('hello world')); - const accounts = await ledgerSubprovider.getAccountsAsync(); - const signer = accounts[0]; - const payload = { - jsonrpc: '2.0', - method: 'personal_sign', - params: [messageHex, signer], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { - expect(err).to.be.a('null'); - expect(response.result.length).to.be.equal(EXPECTED_SIGNATURE_LENGTH); - expect(response.result.substr(0, 2)).to.be.equal('0x'); - done(); - }); - ledgerProvider.sendAsync(payload, callback); - })().catch(done); - }); - it('signs a transaction', (done: DoneCallback) => { - const payload = { - jsonrpc: '2.0', - method: 'eth_signTransaction', - params: [fixtureData.TX_DATA], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { - expect(err).to.be.a('null'); - expect(response.result.raw).to.be.equal(fixtureData.TX_DATA_SIGNED_RESULT); - done(); - }); - ledgerProvider.sendAsync(payload, callback); - }); - it('signs and sends a transaction', (done: DoneCallback) => { - (async () => { - const accounts = await ledgerSubprovider.getAccountsAsync(); - - // Give first account on Ledger sufficient ETH to complete tx send - let tx = { - to: accounts[0], - from: fixtureData.TEST_RPC_ACCOUNT_0, - value: '0x8ac7230489e80000', // 10 ETH - }; - let payload = { - jsonrpc: '2.0', - method: 'eth_sendTransaction', - params: [tx], - id: 1, - }; - await promisify(defaultProvider.sendAsync.bind(defaultProvider))(payload); - - // Send transaction from Ledger - tx = { - to: '0xafa3f8684e54059998bc3a7b0d2b0da075154d66', - from: accounts[0], - value: '0xde0b6b3a7640000', - }; - payload = { - jsonrpc: '2.0', - method: 'eth_sendTransaction', - params: [tx], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { - expect(err).to.be.a('null'); - const result = response.result; - const signedTxLength = 66; - expect(result.length).to.be.equal(signedTxLength); - expect(result.substr(0, 2)).to.be.equal('0x'); - done(); - }); - ledgerProvider.sendAsync(payload, callback); - })().catch(done); - }); - }); -}); diff --git a/packages/subproviders/test/unit/debug_subprovider_test.ts b/packages/subproviders/test/unit/debug_subprovider_test.ts deleted file mode 100644 index 1c2e178639..0000000000 --- a/packages/subproviders/test/unit/debug_subprovider_test.ts +++ /dev/null @@ -1,87 +0,0 @@ -import * as chai from 'chai'; - -import { chaiSetup } from '../chai_setup'; -import { fixtureData } from '../utils/fixture_data'; - -import { DebugPayload, DebugSubprovider } from './../../src/subproviders/debug_subprovider'; - -chaiSetup.configure(); -const expect = chai.expect; - -const blankCallback = () => { - return; -}; - -describe('DebugSubprovider', () => { - describe('sends debug message to callback', async () => { - let sentDebugData: DebugPayload | undefined; - const debugCallback = (curDebugData: DebugPayload) => { - sentDebugData = curDebugData; - return; - }; - before(() => { - sentDebugData = undefined; - }); - it('for ERC20 transfer', async () => { - const fixtureRpcPayload = fixtureData.ERC20_TRANSFER_RPC_PAYLOAD; - const debugSubprovider = new DebugSubprovider(debugCallback); - await debugSubprovider.handleRequest(fixtureRpcPayload, blankCallback, blankCallback); - - if (!sentDebugData) { - fail('No debug data sent'); - } else { - expect(sentDebugData.id).to.eql(fixtureRpcPayload.id); - expect(sentDebugData.jsonrpc).to.eql(fixtureRpcPayload.jsonrpc); - expect(sentDebugData.params).to.eql(fixtureRpcPayload.params); - expect(sentDebugData.method).to.eql(fixtureRpcPayload.method); - - const rawTxnAttrs = sentDebugData.rawTransactionAttributes; - if (!rawTxnAttrs) { - fail('No rawTransactionAttributes'); - } else { - expect(rawTxnAttrs.gasLimit).to.eql('37428'); - expect(rawTxnAttrs.gasPrice).to.eql('1000000000'); - expect(rawTxnAttrs.nonce).to.eql('32'); - expect(rawTxnAttrs.value).to.eql('0'); - expect(rawTxnAttrs.to).to.eql('0x2002d3812f58e35f0ea1ffbf80a75a38c32175fa'); - } - } - }); - it('for eth_blockNumber command', async () => { - const fixtureRpcPayload = fixtureData.ETH_GETBLOCK_RPC_PAYLOAD; - const debugSubprovider = new DebugSubprovider(debugCallback); - await debugSubprovider.handleRequest(fixtureRpcPayload, blankCallback, blankCallback); - - if (!sentDebugData) { - fail('No debug data sent'); - } else { - expect(sentDebugData).to.eql(fixtureRpcPayload); - } - }); - it('for regular ETH transfer', async () => { - const fixtureRpcPayload = fixtureData.ETH_TRANSFER_PAYLOAD; - const debugSubprovider = new DebugSubprovider(debugCallback); - await debugSubprovider.handleRequest(fixtureRpcPayload, blankCallback, blankCallback); - - if (!sentDebugData) { - fail('No debug data sent'); - } else { - expect(sentDebugData.id).to.eql(fixtureRpcPayload.id); - expect(sentDebugData.jsonrpc).to.eql(fixtureRpcPayload.jsonrpc); - expect(sentDebugData.params).to.eql(fixtureRpcPayload.params); - expect(sentDebugData.method).to.eql(fixtureRpcPayload.method); - - const rawTxnAttrs = sentDebugData.rawTransactionAttributes; - if (!rawTxnAttrs) { - fail('No rawTransactionAttributes'); - } else { - expect(rawTxnAttrs.gasLimit).to.eql('21000'); - expect(rawTxnAttrs.gasPrice).to.eql('8000000000'); - expect(rawTxnAttrs.nonce).to.eql('38'); - expect(rawTxnAttrs.value).to.eql('410000000000000'); - expect(rawTxnAttrs.to).to.eql('0x8a333a18b924554d6e83ef9e9944de6260f61d3b'); - } - } - }); - }); -}); diff --git a/packages/subproviders/test/unit/ledger_subprovider_test.ts b/packages/subproviders/test/unit/ledger_subprovider_test.ts deleted file mode 100644 index 062df4ee06..0000000000 --- a/packages/subproviders/test/unit/ledger_subprovider_test.ts +++ /dev/null @@ -1,256 +0,0 @@ -import { providerUtils } from '@0x/utils'; -import * as chai from 'chai'; -import { JSONRPCResponsePayload } from 'ethereum-types'; -import * as ethUtils from 'ethereumjs-util'; -import * as _ from 'lodash'; - -import { LedgerSubprovider, Web3ProviderEngine } from '../../src'; -import { - DoneCallback, - LedgerCommunicationClient, - LedgerSubproviderErrors, - WalletSubproviderErrors, -} from '../../src/types'; -import { chaiSetup } from '../chai_setup'; -import { fixtureData } from '../utils/fixture_data'; -import { ganacheSubprovider } from '../utils/ganache_subprovider'; -import { reportCallbackErrors } from '../utils/report_callback_errors'; - -chaiSetup.configure(); -const expect = chai.expect; -const FAKE_ADDRESS = '0xb088a3bc93f71b4de97b9de773e9647645983688'; -const DEFAULT_NUM_ACCOUNTS = 10; - -describe('LedgerSubprovider', () => { - const networkId: number = 42; - let ledgerSubprovider: LedgerSubprovider; - before(async () => { - const ledgerEthereumClientFactoryAsync = async () => { - // tslint:disable:no-object-literal-type-assertion - const ledgerEthClient = { - getAddress: async () => { - const publicKey = - '04f428290f4c5ed6a198f71b8205f488141dbb3f0840c923bbfa798ecbee6370986c03b5575d94d506772fb48a6a44e345e4ebd4f028a6f609c44b655d6d3e71a1'; - const chainCode = 'ac055a5537c0c7e9e02d14a197cad6b857836da2a12043b46912a37d959b5ae8'; - const address = '0xBa388BA5e5EEF2c6cE42d831c2B3A28D3c99bdB1'; - return { - publicKey, - address, - chainCode, - }; - }, - signPersonalMessage: async () => { - const ecSignature = { - v: 28, - r: 'a6cc284bff14b42bdf5e9286730c152be91719d478605ec46b3bebcd0ae49148', - s: '0652a1a7b742ceb0213d1e744316e285f41f878d8af0b8e632cbca4c279132d0', - }; - return ecSignature; - }, - signTransaction: async (_derivationPath: string, _txHex: string) => { - const ecSignature = { - v: '77', - r: '88a95ef1378487bc82be558e82c8478baf840c545d5b887536bb1da63673a98b', - s: '019f4a4b9a107d1e6752bf7f701e275f28c13791d6e76af895b07373462cefaa', - }; - return ecSignature; - }, - transport: { - close: _.noop.bind(_), - } as LedgerCommunicationClient, - }; - // tslint:enable:no-object-literal-type-assertion - return ledgerEthClient; - }; - ledgerSubprovider = new LedgerSubprovider({ - networkId, - ledgerEthereumClientFactoryAsync, - }); - }); - describe('direct method calls', () => { - describe('success cases', () => { - it('returns default number of accounts', async () => { - const accounts = await ledgerSubprovider.getAccountsAsync(); - expect(accounts[0]).to.be.equal(FAKE_ADDRESS); - expect(accounts.length).to.be.equal(DEFAULT_NUM_ACCOUNTS); - }); - it('returns requested number of accounts', async () => { - const numberOfAccounts = 20; - const accounts = await ledgerSubprovider.getAccountsAsync(numberOfAccounts); - expect(accounts[0]).to.be.equal(FAKE_ADDRESS); - expect(accounts.length).to.be.equal(numberOfAccounts); - }); - it('signs a personal message', async () => { - const data = ethUtils.bufferToHex(ethUtils.toBuffer(fixtureData.PERSONAL_MESSAGE_STRING)); - const ecSignatureHex = await ledgerSubprovider.signPersonalMessageAsync(data, FAKE_ADDRESS); - expect(ecSignatureHex).to.be.equal( - '0xa6cc284bff14b42bdf5e9286730c152be91719d478605ec46b3bebcd0ae491480652a1a7b742ceb0213d1e744316e285f41f878d8af0b8e632cbca4c279132d001', - ); - }); - }); - describe('failure cases', () => { - it('cannot open multiple simultaneous connections to the Ledger device', async () => { - const data = ethUtils.bufferToHex(ethUtils.toBuffer('hello world')); - return expect( - Promise.all([ - ledgerSubprovider.getAccountsAsync(), - ledgerSubprovider.signPersonalMessageAsync(data, FAKE_ADDRESS), - ]), - ).to.be.rejectedWith(LedgerSubproviderErrors.MultipleOpenConnectionsDisallowed); - }); - }); - }); - describe('calls through a provider', () => { - let provider: Web3ProviderEngine; - before(() => { - provider = new Web3ProviderEngine(); - provider.addProvider(ledgerSubprovider); - provider.addProvider(ganacheSubprovider); - providerUtils.startProviderEngine(provider); - }); - describe('success cases', () => { - it('returns a list of accounts', (done: DoneCallback) => { - const payload = { - jsonrpc: '2.0', - method: 'eth_accounts', - params: [], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { - expect(err).to.be.a('null'); - expect(response.result.length).to.be.equal(DEFAULT_NUM_ACCOUNTS); - expect(response.result[0]).to.be.equal(FAKE_ADDRESS); - done(); - }); - provider.sendAsync(payload, callback); - }); - it('signs a personal message with eth_sign', (done: DoneCallback) => { - const messageHex = ethUtils.bufferToHex(ethUtils.toBuffer('hello world')); - const payload = { - jsonrpc: '2.0', - method: 'eth_sign', - params: [FAKE_ADDRESS, messageHex], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { - expect(err).to.be.a('null'); - expect(response.result).to.be.equal( - '0xa6cc284bff14b42bdf5e9286730c152be91719d478605ec46b3bebcd0ae491480652a1a7b742ceb0213d1e744316e285f41f878d8af0b8e632cbca4c279132d001', - ); - done(); - }); - provider.sendAsync(payload, callback); - }); - it('signs a personal message with personal_sign', (done: DoneCallback) => { - const messageHex = ethUtils.bufferToHex(ethUtils.toBuffer(fixtureData.PERSONAL_MESSAGE_STRING)); - const payload = { - jsonrpc: '2.0', - method: 'personal_sign', - params: [messageHex, FAKE_ADDRESS], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { - expect(err).to.be.a('null'); - expect(response.result).to.be.equal( - '0xa6cc284bff14b42bdf5e9286730c152be91719d478605ec46b3bebcd0ae491480652a1a7b742ceb0213d1e744316e285f41f878d8af0b8e632cbca4c279132d001', - ); - done(); - }); - provider.sendAsync(payload, callback); - }); - it('signs a transaction', (done: DoneCallback) => { - const tx = { - to: '0xafa3f8684e54059998bc3a7b0d2b0da075154d66', - value: '0x00', - gasPrice: '0x00', - nonce: '0x00', - gas: '0x00', - from: FAKE_ADDRESS, - }; - const payload = { - jsonrpc: '2.0', - method: 'eth_signTransaction', - params: [tx], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { - expect(err).to.be.a('null'); - const rawTxLength = 192; - expect(response.result.raw.length).to.be.equal(rawTxLength); - expect(response.result.raw.substr(0, 2)).to.be.equal('0x'); - done(); - }); - provider.sendAsync(payload, callback); - }); - }); - describe('failure cases', () => { - it('should throw if `data` param not hex when calling eth_sign', (done: DoneCallback) => { - const nonHexMessage = 'hello world'; - const payload = { - jsonrpc: '2.0', - method: 'eth_sign', - params: [FAKE_ADDRESS, nonHexMessage], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, _response: JSONRPCResponsePayload) => { - expect(err).to.not.be.a('null'); - expect(err.message).to.be.equal('Expected data to be of type HexString, encountered: hello world'); - done(); - }); - provider.sendAsync(payload, callback); - }); - it('should throw if `data` param not hex when calling personal_sign', (done: DoneCallback) => { - const nonHexMessage = 'hello world'; - const payload = { - jsonrpc: '2.0', - method: 'personal_sign', - params: [nonHexMessage, FAKE_ADDRESS], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, _response: JSONRPCResponsePayload) => { - expect(err).to.not.be.a('null'); - expect(err.message).to.be.equal('Expected data to be of type HexString, encountered: hello world'); - done(); - }); - provider.sendAsync(payload, callback); - }); - it('should throw if `from` param missing when calling eth_sendTransaction', (done: DoneCallback) => { - const tx = { - to: '0xafa3f8684e54059998bc3a7b0d2b0da075154d66', - value: '0xde0b6b3a7640000', - }; - const payload = { - jsonrpc: '2.0', - method: 'eth_sendTransaction', - params: [tx], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, _response: JSONRPCResponsePayload) => { - expect(err).to.not.be.a('null'); - expect(err.message).to.be.equal(WalletSubproviderErrors.SenderInvalidOrNotSupplied); - done(); - }); - provider.sendAsync(payload, callback); - }); - it('should throw if `from` param invalid address when calling eth_sendTransaction', (done: DoneCallback) => { - const tx = { - to: '0xafa3f8684e54059998bc3a7b0d2b0da075154d66', - from: '0xIncorrectEthereumAddress', - value: '0xde0b6b3a7640000', - }; - const payload = { - jsonrpc: '2.0', - method: 'eth_sendTransaction', - params: [tx], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, _response: JSONRPCResponsePayload) => { - expect(err).to.not.be.a('null'); - expect(err.message).to.be.equal(WalletSubproviderErrors.SenderInvalidOrNotSupplied); - done(); - }); - provider.sendAsync(payload, callback); - }); - }); - }); -}); diff --git a/packages/subproviders/test/unit/mnemonic_wallet_subprovider_test.ts b/packages/subproviders/test/unit/mnemonic_wallet_subprovider_test.ts deleted file mode 100644 index 456d93e761..0000000000 --- a/packages/subproviders/test/unit/mnemonic_wallet_subprovider_test.ts +++ /dev/null @@ -1,232 +0,0 @@ -import { providerUtils } from '@0x/utils'; -import * as chai from 'chai'; -import { JSONRPCResponsePayload } from 'ethereum-types'; -import * as ethUtils from 'ethereumjs-util'; - -import { GanacheSubprovider, MnemonicWalletSubprovider, Web3ProviderEngine } from '../../src/'; - -import { DoneCallback, WalletSubproviderErrors } from '../../src/types'; -import { chaiSetup } from '../chai_setup'; -import { fixtureData } from '../utils/fixture_data'; -import { reportCallbackErrors } from '../utils/report_callback_errors'; - -chaiSetup.configure(); -const expect = chai.expect; -const DEFAULT_NUM_ACCOUNTS = 10; - -describe('MnemonicWalletSubprovider', () => { - let subprovider: MnemonicWalletSubprovider; - before(async () => { - subprovider = new MnemonicWalletSubprovider({ - mnemonic: fixtureData.TEST_RPC_MNEMONIC, - baseDerivationPath: fixtureData.TEST_RPC_MNEMONIC_BASE_DERIVATION_PATH, - }); - }); - describe('direct method calls', () => { - describe('success cases', () => { - it('returns the accounts', async () => { - const accounts = await subprovider.getAccountsAsync(); - expect(accounts[0]).to.be.equal(fixtureData.TEST_RPC_ACCOUNT_0); - expect(accounts[1]).to.be.equal(fixtureData.TEST_RPC_ACCOUNT_1); - expect(accounts.length).to.be.equal(DEFAULT_NUM_ACCOUNTS); - }); - it('signs a personal message', async () => { - const data = ethUtils.bufferToHex(ethUtils.toBuffer(fixtureData.PERSONAL_MESSAGE_STRING)); - const ecSignatureHex = await subprovider.signPersonalMessageAsync(data, fixtureData.TEST_RPC_ACCOUNT_0); - expect(ecSignatureHex).to.be.equal(fixtureData.PERSONAL_MESSAGE_SIGNED_RESULT); - }); - it('signs a personal message with second address', async () => { - const data = ethUtils.bufferToHex(ethUtils.toBuffer(fixtureData.PERSONAL_MESSAGE_STRING)); - const ecSignatureHex = await subprovider.signPersonalMessageAsync(data, fixtureData.TEST_RPC_ACCOUNT_1); - expect(ecSignatureHex).to.be.equal(fixtureData.PERSONAL_MESSAGE_ACCOUNT_1_SIGNED_RESULT); - }); - it('signs a transaction', async () => { - const txHex = await subprovider.signTransactionAsync(fixtureData.TX_DATA); - expect(txHex).to.be.equal(fixtureData.TX_DATA_SIGNED_RESULT); - }); - it('signs a transaction with the second address', async () => { - const txData = { ...fixtureData.TX_DATA, from: fixtureData.TEST_RPC_ACCOUNT_1 }; - const txHex = await subprovider.signTransactionAsync(txData); - expect(txHex).to.be.equal(fixtureData.TX_DATA_ACCOUNT_1_SIGNED_RESULT); - }); - it('signs an EIP712 sign typed data message', async () => { - const signature = await subprovider.signTypedDataAsync( - fixtureData.TEST_RPC_ACCOUNT_0, - fixtureData.EIP712_TEST_TYPED_DATA, - ); - expect(signature).to.be.equal(fixtureData.EIP712_TEST_TYPED_DATA_SIGNED_RESULT); - }); - }); - describe('failure cases', () => { - it('throws an error if address is invalid ', async () => { - const txData = { ...fixtureData.TX_DATA, from: '0x0' }; - return expect(subprovider.signTransactionAsync(txData)).to.be.rejectedWith( - WalletSubproviderErrors.FromAddressMissingOrInvalid, - ); - }); - it('throws an error if address is valid format but not found', async () => { - const txData = { ...fixtureData.TX_DATA, from: fixtureData.NULL_ADDRESS }; - return expect(subprovider.signTransactionAsync(txData)).to.be.rejectedWith( - `${WalletSubproviderErrors.AddressNotFound}: ${fixtureData.NULL_ADDRESS}`, - ); - }); - }); - }); - describe('calls through a provider', () => { - let provider: Web3ProviderEngine; - before(() => { - provider = new Web3ProviderEngine(); - provider.addProvider(subprovider); - const ganacheSubprovider = new GanacheSubprovider({}); - provider.addProvider(ganacheSubprovider); - providerUtils.startProviderEngine(provider); - }); - describe('success cases', () => { - it('returns a list of accounts', (done: DoneCallback) => { - const payload = { - jsonrpc: '2.0', - method: 'eth_accounts', - params: [], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { - expect(err).to.be.a('null'); - expect(response.result[0]).to.be.equal(fixtureData.TEST_RPC_ACCOUNT_0); - expect(response.result.length).to.be.equal(DEFAULT_NUM_ACCOUNTS); - done(); - }); - provider.sendAsync(payload, callback); - }); - it('signs a personal message with eth_sign', (done: DoneCallback) => { - const messageHex = ethUtils.bufferToHex(ethUtils.toBuffer(fixtureData.PERSONAL_MESSAGE_STRING)); - const payload = { - jsonrpc: '2.0', - method: 'eth_sign', - params: [fixtureData.TEST_RPC_ACCOUNT_0, messageHex], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { - expect(err).to.be.a('null'); - expect(response.result).to.be.equal(fixtureData.PERSONAL_MESSAGE_SIGNED_RESULT); - done(); - }); - provider.sendAsync(payload, callback); - }); - it('signs a personal message with personal_sign', (done: DoneCallback) => { - const messageHex = ethUtils.bufferToHex(ethUtils.toBuffer(fixtureData.PERSONAL_MESSAGE_STRING)); - const payload = { - jsonrpc: '2.0', - method: 'personal_sign', - params: [messageHex, fixtureData.TEST_RPC_ACCOUNT_0], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { - expect(err).to.be.a('null'); - expect(response.result).to.be.equal(fixtureData.PERSONAL_MESSAGE_SIGNED_RESULT); - done(); - }); - provider.sendAsync(payload, callback); - }); - it('signs an EIP712 sign typed data message with eth_signTypedData', (done: DoneCallback) => { - const payload = { - jsonrpc: '2.0', - method: 'eth_signTypedData', - params: [fixtureData.TEST_RPC_ACCOUNT_0, fixtureData.EIP712_TEST_TYPED_DATA], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { - expect(err).to.be.a('null'); - expect(response.result).to.be.equal(fixtureData.EIP712_TEST_TYPED_DATA_SIGNED_RESULT); - done(); - }); - provider.sendAsync(payload, callback); - }); - }); - describe('failure cases', () => { - it('should throw if `data` param not hex when calling eth_sign', (done: DoneCallback) => { - const nonHexMessage = 'hello world'; - const payload = { - jsonrpc: '2.0', - method: 'eth_sign', - params: [fixtureData.TEST_RPC_ACCOUNT_0, nonHexMessage], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, _response: JSONRPCResponsePayload) => { - expect(err).to.not.be.a('null'); - expect(err.message).to.be.equal('Expected data to be of type HexString, encountered: hello world'); - done(); - }); - provider.sendAsync(payload, callback); - }); - it('should throw if `data` param not hex when calling personal_sign', (done: DoneCallback) => { - const nonHexMessage = 'hello world'; - const payload = { - jsonrpc: '2.0', - method: 'personal_sign', - params: [nonHexMessage, fixtureData.TEST_RPC_ACCOUNT_0], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, _response: JSONRPCResponsePayload) => { - expect(err).to.not.be.a('null'); - expect(err.message).to.be.equal('Expected data to be of type HexString, encountered: hello world'); - done(); - }); - provider.sendAsync(payload, callback); - }); - it('should throw if `address` param not found when calling personal_sign', (done: DoneCallback) => { - const messageHex = ethUtils.bufferToHex(ethUtils.toBuffer(fixtureData.PERSONAL_MESSAGE_STRING)); - const payload = { - jsonrpc: '2.0', - method: 'personal_sign', - params: [messageHex, fixtureData.NULL_ADDRESS], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, _response: JSONRPCResponsePayload) => { - expect(err).to.not.be.a('null'); - expect(err.message).to.be.equal( - `${WalletSubproviderErrors.AddressNotFound}: ${fixtureData.NULL_ADDRESS}`, - ); - done(); - }); - provider.sendAsync(payload, callback); - }); - it('should throw if `from` param missing when calling eth_sendTransaction', (done: DoneCallback) => { - const tx = { - to: '0xafa3f8684e54059998bc3a7b0d2b0da075154d66', - value: '0xde0b6b3a7640000', - }; - const payload = { - jsonrpc: '2.0', - method: 'eth_sendTransaction', - params: [tx], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, _response: JSONRPCResponsePayload) => { - expect(err).to.not.be.a('null'); - expect(err.message).to.be.equal(WalletSubproviderErrors.SenderInvalidOrNotSupplied); - done(); - }); - provider.sendAsync(payload, callback); - }); - it('should throw if `from` param invalid address when calling eth_sendTransaction', (done: DoneCallback) => { - const tx = { - to: '0xafa3f8684e54059998bc3a7b0d2b0da075154d66', - from: '0xIncorrectEthereumAddress', - value: '0xde0b6b3a7640000', - }; - const payload = { - jsonrpc: '2.0', - method: 'eth_sendTransaction', - params: [tx], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, _response: JSONRPCResponsePayload) => { - expect(err).to.not.be.a('null'); - expect(err.message).to.be.equal(WalletSubproviderErrors.SenderInvalidOrNotSupplied); - done(); - }); - provider.sendAsync(payload, callback); - }); - }); - }); -}); diff --git a/packages/subproviders/test/unit/nonce_tracker_subprovider_test.ts b/packages/subproviders/test/unit/nonce_tracker_subprovider_test.ts deleted file mode 100644 index 25566ebc06..0000000000 --- a/packages/subproviders/test/unit/nonce_tracker_subprovider_test.ts +++ /dev/null @@ -1,149 +0,0 @@ -import * as chai from 'chai'; -import FixtureSubprovider = require('web3-provider-engine/subproviders/fixture'); - -import { promisify, providerUtils } from '@0x/utils'; -import EthereumTx = require('ethereumjs-tx'); - -import { NonceTrackerSubprovider, Web3ProviderEngine } from '../../src'; -import { chaiSetup } from '../chai_setup'; - -const expect = chai.expect; -chaiSetup.configure(); - -describe('NonceTrackerSubprovider', () => { - let provider: Web3ProviderEngine; - const getTransactionCountPayload = { - jsonrpc: '2.0', - method: 'eth_getTransactionCount', - params: ['0x0', 'pending'], - id: 1, - }; - const sendTransactionPayload = { - jsonrpc: '2.0', - method: 'eth_sendRawTransaction', - params: [], - id: 1, - }; - const txParams = [ - '0x', - '0x09184e72a000', - '0x2710', - '0x0000000000000000000000000000000000000000', - '0x', - '0x7f7465737432000000000000000000000000000000000000000000000000000000600057', - '0x1c', - '0x5e1d3a76fbf824220eafc8c79ad578ad2b67d01b0c2425eb1f1347e8f50882ab', - '0x5bd428537f05f9830e93792f90ea6a3e2d1ee84952dd96edbae9f658f831ab13', - ]; - function createFixtureSubprovider(): FixtureSubprovider { - let isFirstGetTransactionCount = true; - const fixedBlockNumberAndTransactionCountProvider = new FixtureSubprovider({ - eth_getBlockByNumber: '0x01', - eth_getTransactionCount: (_data: any, _next: any, end: any) => { - // For testing caching we return different results on the second call - if (isFirstGetTransactionCount) { - isFirstGetTransactionCount = false; - end(null, '0x00'); - } else { - end(null, '0x99'); - } - }, - }); - return fixedBlockNumberAndTransactionCountProvider; - } - it('successfully caches the transaction count', async () => { - provider = new Web3ProviderEngine(); - const nonceTrackerSubprovider = new NonceTrackerSubprovider(); - provider.addProvider(nonceTrackerSubprovider); - provider.addProvider(createFixtureSubprovider()); - providerUtils.startProviderEngine(provider); - - const payload = { ...getTransactionCountPayload, params: ['0x0', 'pending'] }; - - const response = await promisify(provider.sendAsync.bind(provider))(payload); - expect(response.result).to.be.eq('0x00'); - const secondResponse = await promisify(provider.sendAsync.bind(provider))(payload); - expect(secondResponse.result).to.be.eq('0x00'); - }); - it('does not cache the result for latest transaction count', async () => { - provider = new Web3ProviderEngine(); - const nonceTrackerSubprovider = new NonceTrackerSubprovider(); - provider.addProvider(nonceTrackerSubprovider); - provider.addProvider(createFixtureSubprovider()); - providerUtils.startProviderEngine(provider); - - const payload = { ...getTransactionCountPayload, params: ['0x0', 'latest'] }; - - const response = await promisify(provider.sendAsync.bind(provider))(payload); - expect(response.result).to.be.eq('0x00'); - const secondResponse = await promisify(provider.sendAsync.bind(provider))(payload); - expect(secondResponse.result).to.be.eq('0x99'); - }); - it('clears the cache on a Nonce Too Low Error', async () => { - provider = new Web3ProviderEngine(); - const nonceTrackerSubprovider = new NonceTrackerSubprovider(); - provider.addProvider(nonceTrackerSubprovider); - provider.addProvider(createFixtureSubprovider()); - provider.addProvider( - new FixtureSubprovider({ - eth_sendRawTransaction: (_data: any, _next: any, end: any) => { - end(new Error('Transaction nonce is too low')); - }, - }), - ); - providerUtils.startProviderEngine(provider); - - const noncePayload = { - ...getTransactionCountPayload, - params: ['0x1f36f546477cda21bf2296c50976f2740247906f', 'pending'], - }; - const transaction = new EthereumTx(txParams); - const txPayload = { - ...sendTransactionPayload, - params: [transaction.serialize()], - }; - - const response = await promisify(provider.sendAsync.bind(provider))(noncePayload); - expect(response.result).to.be.eq('0x00'); - const secondResponse = await promisify(provider.sendAsync.bind(provider))(noncePayload); - expect(secondResponse.result).to.be.eq('0x00'); - try { - await promisify(provider.sendAsync.bind(provider))(txPayload); - } catch (err) { - const thirdResponse = await promisify(provider.sendAsync.bind(provider))(noncePayload); - expect(thirdResponse.result).to.be.eq('0x99'); - } - }); - it('increments the used nonce when a transaction successfully submits', async () => { - provider = new Web3ProviderEngine(); - const nonceTrackerSubprovider = new NonceTrackerSubprovider(); - provider.addProvider(nonceTrackerSubprovider); - provider.addProvider(createFixtureSubprovider()); - provider.addProvider( - new FixtureSubprovider({ - eth_sendRawTransaction: (_data: any, _next: any, end: any) => { - end(null); - }, - }), - ); - providerUtils.startProviderEngine(provider); - - const noncePayload = { - ...getTransactionCountPayload, - params: ['0x1f36f546477cda21bf2296c50976f2740247906f', 'pending'], - }; - const transaction = new EthereumTx(txParams); - const txPayload = { - ...sendTransactionPayload, - params: [transaction.serialize()], - }; - - const response = await promisify(provider.sendAsync.bind(provider))(noncePayload); - expect(response.result).to.be.eq('0x00'); - const secondResponse = await promisify(provider.sendAsync.bind(provider))(noncePayload); - expect(secondResponse.result).to.be.eq('0x00'); - await promisify(provider.sendAsync.bind(provider))(txPayload); - const thirdResponse = await promisify(provider.sendAsync.bind(provider))(noncePayload); - expect(thirdResponse.result).to.be.eq('0x01'); - }); -}); diff --git a/packages/subproviders/test/unit/private_key_wallet_subprovider_test.ts b/packages/subproviders/test/unit/private_key_wallet_subprovider_test.ts deleted file mode 100644 index 3d6b0cc9de..0000000000 --- a/packages/subproviders/test/unit/private_key_wallet_subprovider_test.ts +++ /dev/null @@ -1,241 +0,0 @@ -import { providerUtils } from '@0x/utils'; -import * as chai from 'chai'; -import { JSONRPCResponsePayload } from 'ethereum-types'; -import * as ethUtils from 'ethereumjs-util'; - -import { GanacheSubprovider, PrivateKeyWalletSubprovider, Web3ProviderEngine } from '../../src/'; -import { DoneCallback, WalletSubproviderErrors } from '../../src/types'; -import { chaiSetup } from '../chai_setup'; -import { fixtureData } from '../utils/fixture_data'; -import { reportCallbackErrors } from '../utils/report_callback_errors'; - -chaiSetup.configure(); -const expect = chai.expect; - -describe('PrivateKeyWalletSubprovider', () => { - let subprovider: PrivateKeyWalletSubprovider; - before(async () => { - subprovider = new PrivateKeyWalletSubprovider(fixtureData.TEST_RPC_ACCOUNT_0_ACCOUNT_PRIVATE_KEY); - }); - describe('direct method calls', () => { - describe('success cases', () => { - it('returns the account', async () => { - const accounts = await subprovider.getAccountsAsync(); - expect(accounts[0]).to.be.equal(fixtureData.TEST_RPC_ACCOUNT_0); - expect(accounts.length).to.be.equal(1); - }); - it('signs a personal message', async () => { - const data = ethUtils.bufferToHex(ethUtils.toBuffer(fixtureData.PERSONAL_MESSAGE_STRING)); - const ecSignatureHex = await subprovider.signPersonalMessageAsync(data, fixtureData.TEST_RPC_ACCOUNT_0); - expect(ecSignatureHex).to.be.equal(fixtureData.PERSONAL_MESSAGE_SIGNED_RESULT); - }); - it('signs a transaction', async () => { - const txHex = await subprovider.signTransactionAsync(fixtureData.TX_DATA); - expect(txHex).to.be.equal(fixtureData.TX_DATA_SIGNED_RESULT); - }); - it('signs a transaction where the tx.origin is checksummed.', async () => { - const TX_DATA_CHECKSUMMED_ORIGIN = { - ...fixtureData.TX_DATA, - from: fixtureData.TEST_RPC_ACCOUNT_0_CHECKSUMMED, - }; - const txHex = await subprovider.signTransactionAsync(TX_DATA_CHECKSUMMED_ORIGIN); - expect(txHex).to.be.equal(fixtureData.TX_DATA_SIGNED_RESULT); - }); - it('signs an EIP712 sign typed data message', async () => { - const signature = await subprovider.signTypedDataAsync( - fixtureData.TEST_RPC_ACCOUNT_0, - fixtureData.EIP712_TEST_TYPED_DATA, - ); - expect(signature).to.be.equal(fixtureData.EIP712_TEST_TYPED_DATA_SIGNED_RESULT); - }); - }); - }); - describe('calls through a provider', () => { - let provider: Web3ProviderEngine; - before(() => { - provider = new Web3ProviderEngine(); - provider.addProvider(subprovider); - const ganacheSubprovider = new GanacheSubprovider({}); - provider.addProvider(ganacheSubprovider); - providerUtils.startProviderEngine(provider); - }); - describe('success cases', () => { - it('returns a list of accounts', (done: DoneCallback) => { - const payload = { - jsonrpc: '2.0', - method: 'eth_accounts', - params: [], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { - expect(err).to.be.a('null'); - expect(response.result[0]).to.be.equal(fixtureData.TEST_RPC_ACCOUNT_0); - expect(response.result.length).to.be.equal(1); - done(); - }); - provider.sendAsync(payload, callback); - }); - it('signs a transaction', (done: DoneCallback) => { - const payload = { - jsonrpc: '2.0', - method: 'eth_signTransaction', - params: [fixtureData.TX_DATA], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { - expect(err).to.be.a('null'); - expect(response.result.raw).to.be.equal(fixtureData.TX_DATA_SIGNED_RESULT); - done(); - }); - provider.sendAsync(payload, callback); - }); - it('signs a personal message with eth_sign', (done: DoneCallback) => { - const messageHex = ethUtils.bufferToHex(ethUtils.toBuffer(fixtureData.PERSONAL_MESSAGE_STRING)); - const payload = { - jsonrpc: '2.0', - method: 'eth_sign', - params: [fixtureData.TEST_RPC_ACCOUNT_0, messageHex], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { - expect(err).to.be.a('null'); - expect(response.result).to.be.equal(fixtureData.PERSONAL_MESSAGE_SIGNED_RESULT); - done(); - }); - provider.sendAsync(payload, callback); - }); - it('signs a personal message with personal_sign', (done: DoneCallback) => { - const messageHex = ethUtils.bufferToHex(ethUtils.toBuffer(fixtureData.PERSONAL_MESSAGE_STRING)); - const payload = { - jsonrpc: '2.0', - method: 'personal_sign', - params: [messageHex, fixtureData.TEST_RPC_ACCOUNT_0], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { - expect(err).to.be.a('null'); - expect(response.result).to.be.equal(fixtureData.PERSONAL_MESSAGE_SIGNED_RESULT); - done(); - }); - provider.sendAsync(payload, callback); - }); - it('signs an EIP712 sign typed data message with eth_signTypedData', (done: DoneCallback) => { - const payload = { - jsonrpc: '2.0', - method: 'eth_signTypedData', - params: [fixtureData.TEST_RPC_ACCOUNT_0, fixtureData.EIP712_TEST_TYPED_DATA], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { - expect(err).to.be.a('null'); - expect(response.result).to.be.equal(fixtureData.EIP712_TEST_TYPED_DATA_SIGNED_RESULT); - done(); - }); - provider.sendAsync(payload, callback); - }); - }); - describe('failure cases', () => { - it('should throw if `data` param not hex when calling eth_sign', (done: DoneCallback) => { - const nonHexMessage = 'hello world'; - const payload = { - jsonrpc: '2.0', - method: 'eth_sign', - params: [fixtureData.TEST_RPC_ACCOUNT_0, nonHexMessage], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, _response: JSONRPCResponsePayload) => { - expect(err).to.not.be.a('null'); - expect(err.message).to.be.equal('Expected data to be of type HexString, encountered: hello world'); - done(); - }); - provider.sendAsync(payload, callback); - }); - it('should throw if `data` param not hex when calling personal_sign', (done: DoneCallback) => { - const nonHexMessage = 'hello world'; - const payload = { - jsonrpc: '2.0', - method: 'personal_sign', - params: [nonHexMessage, fixtureData.TEST_RPC_ACCOUNT_0], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, _response: JSONRPCResponsePayload) => { - expect(err).to.not.be.a('null'); - expect(err.message).to.be.equal('Expected data to be of type HexString, encountered: hello world'); - done(); - }); - provider.sendAsync(payload, callback); - }); - it('should throw if `address` param is not the address from private key when calling personal_sign', (done: DoneCallback) => { - const messageHex = ethUtils.bufferToHex(ethUtils.toBuffer(fixtureData.PERSONAL_MESSAGE_STRING)); - const payload = { - jsonrpc: '2.0', - method: 'personal_sign', - params: [messageHex, fixtureData.TEST_RPC_ACCOUNT_1], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, _response: JSONRPCResponsePayload) => { - expect(err).to.not.be.a('null'); - expect(err.message).to.be.equal( - `Requested to sign message with address: ${ - fixtureData.TEST_RPC_ACCOUNT_1 - }, instantiated with address: ${fixtureData.TEST_RPC_ACCOUNT_0}`, - ); - done(); - }); - provider.sendAsync(payload, callback); - }); - it('should throw if `from` param missing when calling eth_sendTransaction', (done: DoneCallback) => { - const tx = { - to: '0xafa3f8684e54059998bc3a7b0d2b0da075154d66', - value: '0xde0b6b3a7640000', - }; - const payload = { - jsonrpc: '2.0', - method: 'eth_sendTransaction', - params: [tx], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, _response: JSONRPCResponsePayload) => { - expect(err).to.not.be.a('null'); - expect(err.message).to.be.equal(WalletSubproviderErrors.SenderInvalidOrNotSupplied); - done(); - }); - provider.sendAsync(payload, callback); - }); - it('should throw if `from` param invalid address when calling eth_sendTransaction', (done: DoneCallback) => { - const tx = { - to: '0xafa3f8684e54059998bc3a7b0d2b0da075154d66', - from: '0xIncorrectEthereumAddress', - value: '0xde0b6b3a7640000', - }; - const payload = { - jsonrpc: '2.0', - method: 'eth_sendTransaction', - params: [tx], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, _response: JSONRPCResponsePayload) => { - expect(err).to.not.be.a('null'); - expect(err.message).to.be.equal(WalletSubproviderErrors.SenderInvalidOrNotSupplied); - done(); - }); - provider.sendAsync(payload, callback); - }); - it('should throw if `address` param not found when calling personal_sign', (done: DoneCallback) => { - const messageHex = ethUtils.bufferToHex(ethUtils.toBuffer(fixtureData.PERSONAL_MESSAGE_STRING)); - const payload = { - jsonrpc: '2.0', - method: 'personal_sign', - params: [messageHex, '0x0'], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, _response: JSONRPCResponsePayload) => { - expect(err).to.not.be.a('null'); - expect(err.message).to.be.equal(`Expected address to be of type ETHAddressHex, encountered: 0x0`); - done(); - }); - provider.sendAsync(payload, callback); - }); - }); - }); -}); diff --git a/packages/subproviders/test/unit/redundant_rpc_subprovider_test.ts b/packages/subproviders/test/unit/redundant_rpc_subprovider_test.ts deleted file mode 100644 index caeed14d6f..0000000000 --- a/packages/subproviders/test/unit/redundant_rpc_subprovider_test.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { DoneCallback } from '@0x/types'; -import { providerUtils } from '@0x/utils'; -import * as chai from 'chai'; -import { JSONRPCResponsePayload } from 'ethereum-types'; -import * as Sinon from 'sinon'; - -import { RedundantSubprovider, RPCSubprovider, Web3ProviderEngine } from '../../src'; -import { Subprovider } from '../../src/subproviders/subprovider'; -import { chaiSetup } from '../chai_setup'; -import { ganacheSubprovider } from '../utils/ganache_subprovider'; -import { reportCallbackErrors } from '../utils/report_callback_errors'; - -const expect = chai.expect; -chaiSetup.configure(); -const DEFAULT_NUM_ACCOUNTS = 10; - -describe('RedundantSubprovider', () => { - let provider: Web3ProviderEngine; - it('succeeds when supplied a healthy endpoint', (done: DoneCallback) => { - provider = new Web3ProviderEngine(); - const subproviders = [ganacheSubprovider]; - const redundantSubprovider = new RedundantSubprovider(subproviders); - provider.addProvider(redundantSubprovider); - providerUtils.startProviderEngine(provider); - - const payload = { - jsonrpc: '2.0', - method: 'eth_accounts', - params: [], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { - expect(err).to.be.a('null'); - expect(response.result.length).to.be.equal(DEFAULT_NUM_ACCOUNTS); - done(); - }); - provider.sendAsync(payload, callback); - }); - it('succeeds when supplied at least one healthy endpoint', (done: DoneCallback) => { - provider = new Web3ProviderEngine(); - const nonExistentSubprovider = new RPCSubprovider('http://does-not-exist:3000'); - const handleRequestStub = Sinon.stub(nonExistentSubprovider, 'handleRequest').throws( - new Error('REQUEST_FAILED'), - ); - const subproviders = [nonExistentSubprovider as Subprovider, ganacheSubprovider]; - const redundantSubprovider = new RedundantSubprovider(subproviders); - provider.addProvider(redundantSubprovider); - providerUtils.startProviderEngine(provider); - - const payload = { - jsonrpc: '2.0', - method: 'eth_accounts', - params: [], - id: 1, - }; - const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { - expect(err).to.be.a('null'); - expect(response.result.length).to.be.equal(DEFAULT_NUM_ACCOUNTS); - handleRequestStub.restore(); - done(); - }); - provider.sendAsync(payload, callback); - }); -}); diff --git a/packages/subproviders/test/utils/configs.ts b/packages/subproviders/test/utils/configs.ts deleted file mode 100644 index 341037e4f6..0000000000 --- a/packages/subproviders/test/utils/configs.ts +++ /dev/null @@ -1,5 +0,0 @@ -export const configs = { - port: 8545, - networkId: 50, - mnemonic: 'concert load couple harbor equip island argue ramp clarify fence smart topic', -}; diff --git a/packages/subproviders/test/utils/fixture_data.ts b/packages/subproviders/test/utils/fixture_data.ts deleted file mode 100644 index 7a8d907e3d..0000000000 --- a/packages/subproviders/test/utils/fixture_data.ts +++ /dev/null @@ -1,88 +0,0 @@ -const TEST_RPC_ACCOUNT_0 = '0x5409ed021d9299bf6814279a6a1411a7e866a631'; -const TEST_RPC_ACCOUNT_0_CHECKSUMMED = '0x5409ED021D9299bf6814279A6A1411A7e866A631'; -const TEST_RPC_ACCOUNT_1 = '0x6ecbe1db9ef729cbe972c83fb886247691fb6beb'; -const NULL_ADDRESS = '0x0000000000000000000000000000000000000000'; -const networkId = 42; -export const fixtureData = { - NULL_ADDRESS, - TEST_RPC_ACCOUNT_0, - TEST_RPC_ACCOUNT_0_CHECKSUMMED, - TEST_RPC_ACCOUNT_0_ACCOUNT_PRIVATE_KEY: 'F2F48EE19680706196E2E339E5DA3491186E0C4C5030670656B0E0164837257D', - TEST_RPC_ACCOUNT_1, - TEST_RPC_MNEMONIC: 'concert load couple harbor equip island argue ramp clarify fence smart topic', - TEST_RPC_MNEMONIC_BASE_DERIVATION_PATH: `44'/60'/0'/0`, - PERSONAL_MESSAGE_STRING: 'hello world', - PERSONAL_MESSAGE_SIGNED_RESULT: - '0x1b0ec5e2908e993d0c8ab6b46da46be2688fdf03c7ea6686075de37392e50a7d7fcc531446699132fbda915bd989882e0064d417018773a315fb8d43ed063c9b00', - PERSONAL_MESSAGE_ACCOUNT_1_SIGNED_RESULT: - '0xe7ae0c21d02eb38f2c2a20d9d7876a98cc7ef035b7a4559d49375e2ec735e06f0d0ab0ff92ee56c5ffc28d516e6ed0692d0270feae8796408dbef060c6c7100f01', - TESTRPC_BASE_DERIVATION_PATH: `m/44'/60'/0'/0`, - NETWORK_ID: networkId, - TX_DATA: { - nonce: '0x00', - gasPrice: '0x0', - gas: '0x2710', - to: NULL_ADDRESS, - value: '0x00', - chainId: networkId, - from: TEST_RPC_ACCOUNT_0, - }, - // This is the signed result of the above Transaction Data - TX_DATA_SIGNED_RESULT: - '0xf85f8080822710940000000000000000000000000000000000000000808078a0712854c73c69445cc1b22a7c3d7312ff9a97fe4ffba35fd636e8236b211b6e7ca0647cee031615e52d916c7c707025bc64ad525d8f1b9876c3435a863b42743178', - TX_DATA_ACCOUNT_1_SIGNED_RESULT: - '0xf85f8080822710940000000000000000000000000000000000000000808078a04b02af7ff3f18ce114b601542cc8ebdc50921354f75dd510d31793453a0710e6a0540082a01e475465801b8186a2edc79ec1a2dcf169b9781c25a58a417023c9ca', - EIP712_TEST_TYPED_DATA: { - types: { - EIP712Domain: [ - { - name: 'name', - type: 'string', - }, - ], - Test: [ - { - name: 'testAddress', - type: 'address', - }, - { - name: 'testNumber', - type: 'uint256', - }, - ], - }, - domain: { - name: 'Test', - }, - message: { - testAddress: '0x0000000000000000000000000000000000000000', - testNumber: '12345', - }, - primaryType: 'Test', - }, - EIP712_TEST_TYPED_DATA_HASH: '0xb460d69ca60383293877cd765c0f97bd832d66bca720f7e32222ce1118832493', - EIP712_TEST_TYPED_DATA_SIGNED_RESULT: - '0x20af5b6bfc3658942198d6eeda159b4ed589f90cee6eac3ba117818ffba5fd7e354a353aad93faabd6eb6c66e17921c92bd1cd09c92a770f554470dc3e254ce701', - ERC20_TRANSFER_RPC_PAYLOAD: { - id: 1573248819933307, - jsonrpc: '2.0', - params: [ - '0xf8a820843b9aca00829234942002d3812f58e35f0ea1ffbf80a75a38c32175fa80b844a9059cbb0000000000000000000000008a333a18b924554d6e83ef9e9944de6260f61d3b00000000000000000000000000000000000000000000000000005af3107a40001ba0aef7ea75bfc9c8fd6ecd9572e78de6aabfe856a69658ce259a64cffd5b31ac22a0386d4669313a21a59e27d629810fc4ab4e1ff08eb7c20f5fa4f533a23fd5533f', - ], - method: 'eth_sendRawTransaction', - }, - ETH_TRANSFER_PAYLOAD: { - id: 1573451366422343, - jsonrpc: '2.0', - params: [ - '0xf86b268501dcd65000825208948a333a18b924554d6e83ef9e9944de6260f61d3b870174e4905ba000801ba0b71c9f67a42b53288cbf8d73741e8d189e79031c00f0e029f6501057fdb71affa035f306598dbc3f1f60db8ca0a4fe0d2e189c4caead7c6179da512e6abc481cbb', - ], - method: 'eth_sendRawTransaction', - }, - ETH_GETBLOCK_RPC_PAYLOAD: { - id: 1, - params: [], - jsonrpc: '2.0', - method: 'eth_blockNumber', - }, -}; diff --git a/packages/subproviders/test/utils/ganache_subprovider.ts b/packages/subproviders/test/utils/ganache_subprovider.ts deleted file mode 100644 index ac4a9325c3..0000000000 --- a/packages/subproviders/test/utils/ganache_subprovider.ts +++ /dev/null @@ -1,18 +0,0 @@ -import * as fs from 'fs'; - -import { GanacheSubprovider } from '../../src/subproviders/ganache'; -import { configs } from '../utils/configs'; - -const logger = { - log: (arg: any) => { - fs.appendFileSync('ganache.log', `${arg}\n`); - }, -}; - -export const ganacheSubprovider = new GanacheSubprovider({ - logger, - verbose: false, - port: configs.port, - networkId: configs.networkId, - mnemonic: configs.mnemonic, -}); diff --git a/packages/subproviders/test/utils/report_callback_errors.ts b/packages/subproviders/test/utils/report_callback_errors.ts deleted file mode 100644 index 6eb7420c3e..0000000000 --- a/packages/subproviders/test/utils/report_callback_errors.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { DoneCallback } from '@0x/types'; - -export const reportCallbackErrors = (done: DoneCallback) => { - return (f: (...args: any[]) => void) => { - const wrapped = async (...args: any[]) => { - try { - f(...args); - } catch (err) { - done(err); - } - }; - return wrapped; - }; -}; diff --git a/packages/subproviders/tsconfig.json b/packages/subproviders/tsconfig.json deleted file mode 100644 index 2ee711adcc..0000000000 --- a/packages/subproviders/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../tsconfig", - "compilerOptions": { - "outDir": "lib", - "rootDir": "." - }, - "include": ["./src/**/*", "./test/**/*"] -} diff --git a/packages/subproviders/tslint.json b/packages/subproviders/tslint.json deleted file mode 100644 index dd9053357e..0000000000 --- a/packages/subproviders/tslint.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": ["@0x/tslint-config"] -} diff --git a/packages/subproviders/typedoc-tsconfig.json b/packages/subproviders/typedoc-tsconfig.json deleted file mode 100644 index c9b0af1ae6..0000000000 --- a/packages/subproviders/typedoc-tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "../../typedoc-tsconfig", - "compilerOptions": { - "outDir": "lib" - }, - "include": ["./src/**/*", "./test/**/*"] -} diff --git a/packages/tslint-config/.npmignore b/packages/tslint-config/.npmignore deleted file mode 100644 index ea588d4859..0000000000 --- a/packages/tslint-config/.npmignore +++ /dev/null @@ -1,9 +0,0 @@ -# Blacklist all files -.* -* -# Whitelist lib -!lib/**/* -# Blacklist tests and publish scripts -/lib/test/* -/lib/monorepo_scripts/ -# Package specific ignore diff --git a/packages/tslint-config/CHANGELOG.json b/packages/tslint-config/CHANGELOG.json deleted file mode 100644 index 6ed37b7666..0000000000 --- a/packages/tslint-config/CHANGELOG.json +++ /dev/null @@ -1,338 +0,0 @@ -[ - { - "version": "4.1.0", - "changes": [ - { - "note": "Set `no-non-null-assertion` to false", - "pr": 2613 - } - ], - "timestamp": 1594788383 - }, - { - "version": "4.0.0", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1575296764 - }, - { - "version": "3.1.0-beta.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1574030254 - }, - { - "version": "3.1.0-beta.1", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1573159180 - }, - { - "version": "3.1.0-beta.0", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1554997931 - }, - { - "version": "3.0.0", - "changes": [ - { - "note": "Upgrade the bignumber.js to v8.0.2", - "pr": 1517 - } - ], - "timestamp": 1549373905 - }, - { - "timestamp": 1547561734, - "version": "2.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547225310, - "version": "2.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.0", - "changes": [ - { - "note": "Improve async-suffix rule to check functions too, not just methods", - "pr": 1425 - } - ], - "timestamp": 1544739608 - }, - { - "version": "1.0.10", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1541740904 - }, - { - "timestamp": 1539871071, - "version": "1.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1538693146, - "version": "1.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1536142250, - "version": "1.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1535133899, - "version": "1.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1534210131, - "version": "1.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532614997, - "version": "1.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532605697, - "version": "1.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532551340, - "version": "1.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532357734, - "version": "1.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532043000, - "version": "1.0.0", - "changes": [ - { - "note": "Added a bunch of rules", - "pr": 883 - } - ] - }, - { - "timestamp": 1531149657, - "version": "0.4.21", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1529397769, - "version": "0.4.20", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.4.19", - "changes": [ - { - "note": "Incorrect publish that was unpublished" - } - ], - "timestamp": 1527810075 - }, - { - "timestamp": 1527009133, - "version": "0.4.18", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1525428773, - "version": "0.4.17", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1524044013, - "version": "0.4.16", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1523462196, - "version": "0.4.15", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1522673609, - "version": "0.4.14", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1522658513, - "version": "0.4.13", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.4.9", - "changes": [ - { - "note": "Move devDeps to deps to fix missed dependency issue in published package." - } - ], - "timestamp": 1518102000 - }, - { - "version": "0.4.8", - "changes": [ - { - "note": "Fix publish issue where custom TSLint rules were not being included", - "pr": 389 - } - ], - "timestamp": 1518102000 - }, - { - "version": "0.4.7", - "changes": [ - { - "note": "Modified custom 'underscore-privates' rule, changing it to 'underscore-private-and-protected' requiring underscores to be prepended to both private and protected variable names", - "pr": 354 - } - ], - "timestamp": 1517929200 - }, - { - "version": "0.4.0", - "changes": [ - { - "note": "Added custom 'underscore-privates' rule, requiring underscores to be prepended to private variable names" - }, - { - "note": "Because our tools can be used in both a TS and JS environment, we want to make the private methods of any public facing interface show up at the bottom of auto-complete lists. Additionally, we wanted to remain consistent with respect to our usage of underscores in order to enforce this rule with a linter rule, rather then manual code reviews." - } - ], - "timestamp": 1514386800 - }, - { - "version": "0.3.0", - "changes": [ - { - "note": "Added rules for unused imports, variables and Async suffixes", - "pr": 265 - } - ], - "timestamp": 1513695600 - }, - { - "version": "0.1.0", - "changes": [ - { - "note": "Re-published TsLintConfig previously published under NPM package `tslint-config-0xproject`" - }, - { - "note": "Updated to TSLint v5.8.0, requiring several rule additions to keep our conventions aligned." - } - ], - "timestamp": 1510585200 - } -] diff --git a/packages/tslint-config/CHANGELOG.md b/packages/tslint-config/CHANGELOG.md deleted file mode 100644 index a1038d211d..0000000000 --- a/packages/tslint-config/CHANGELOG.md +++ /dev/null @@ -1,152 +0,0 @@ - - -CHANGELOG - -## v4.1.0 - _July 15, 2020_ - - * Set `no-non-null-assertion` to false (#2613) - -## v4.0.0 - _December 2, 2019_ - - * Dependencies updated - -## v3.1.0-beta.2 - _November 17, 2019_ - - * Dependencies updated - -## v3.1.0-beta.1 - _November 7, 2019_ - - * Dependencies updated - -## v3.1.0-beta.0 - _Invalid date_ - - * Dependencies updated - -## v3.0.1 - _April 11, 2019_ - - * Dependencies updated - -## v3.0.0 - _February 5, 2019_ - - * Upgrade the bignumber.js to v8.0.2 (#1517) - -## v2.0.2 - _January 15, 2019_ - - * Dependencies updated - -## v2.0.1 - _January 11, 2019_ - - * Dependencies updated - -## v2.0.0 - _December 13, 2018_ - - * Improve async-suffix rule to check functions too, not just methods (#1425) - -## v1.0.10 - _November 9, 2018_ - - * Dependencies updated - -## v1.0.9 - _October 18, 2018_ - - * Dependencies updated - -## v1.0.8 - _October 4, 2018_ - - * Dependencies updated - -## v1.0.7 - _September 5, 2018_ - - * Dependencies updated - -## v1.0.6 - _August 24, 2018_ - - * Dependencies updated - -## v1.0.5 - _August 14, 2018_ - - * Dependencies updated - -## v1.0.4 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.3 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.2 - _July 25, 2018_ - - * Dependencies updated - -## v1.0.1 - _July 23, 2018_ - - * Dependencies updated - -## v1.0.0 - _July 19, 2018_ - - * Added a bunch of rules (#883) - -## v0.4.21 - _July 9, 2018_ - - * Dependencies updated - -## v0.4.20 - _June 19, 2018_ - - * Dependencies updated - -## v0.4.19 - _May 31, 2018_ - - * Incorrect publish that was unpublished - -## v0.4.18 - _May 22, 2018_ - - * Dependencies updated - -## v0.4.17 - _May 4, 2018_ - - * Dependencies updated - -## v0.4.16 - _April 18, 2018_ - - * Dependencies updated - -## v0.4.15 - _April 11, 2018_ - - * Dependencies updated - -## v0.4.14 - _April 2, 2018_ - - * Dependencies updated - -## v0.4.13 - _April 2, 2018_ - - * Dependencies updated - -## v0.4.9 - _February 8, 2018_ - - * Move devDeps to deps to fix missed dependency issue in published package. - -## v0.4.8 - _February 8, 2018_ - - * Fix publish issue where custom TSLint rules were not being included (#389) - -## v0.4.7 - _February 6, 2018_ - - * Modified custom 'underscore-privates' rule, changing it to 'underscore-private-and-protected' requiring underscores to be prepended to both private and protected variable names (#354) - -## v0.4.0 - _December 27, 2017_ - - * Added custom 'underscore-privates' rule, requiring underscores to be prepended to private variable names - * Because our tools can be used in both a TS and JS environment, we want to make the private methods of any public facing interface show up at the bottom of auto-complete lists. Additionally, we wanted to remain consistent with respect to our usage of underscores in order to enforce this rule with a linter rule, rather then manual code reviews. - -## v0.3.0 - _December 19, 2017_ - - * Added rules for unused imports, variables and Async suffixes (#265) - -## v0.1.0 - _November 13, 2017_ - - * Re-published TsLintConfig previously published under NPM package `tslint-config-0xproject` - * Updated to TSLint v5.8.0, requiring several rule additions to keep our conventions aligned. diff --git a/packages/tslint-config/README.md b/packages/tslint-config/README.md deleted file mode 100644 index 5614e5e546..0000000000 --- a/packages/tslint-config/README.md +++ /dev/null @@ -1,71 +0,0 @@ -## @0x/tslint-config - -TSLint configuration and custom linter rules used by 0xProject. - -## Installation - -```bash -yarn add --dev @0x/tslint-config -``` - -## Usage - -Add the following to your `tslint.json` file - -```json -{ - "extends": ["@0x/tslint-config"] -} -``` - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install dependencies - -If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: - -```bash -yarn config set workspaces-experimental true -``` - -Then install dependencies - -```bash -yarn install -``` - -### Build - -To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory: - -```bash -PKG=@0x/tslint-config yarn build -``` - -Or continuously rebuild on change: - -```bash -PKG=@0x/tslint-config yarn watch -``` - -### Clean - -```bash -yarn clean -``` - -### Lint - -```bash -yarn lint -``` - -### Run Tests - -```bash -yarn test -``` diff --git a/packages/tslint-config/package.json b/packages/tslint-config/package.json deleted file mode 100644 index c8057e5c90..0000000000 --- a/packages/tslint-config/package.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "name": "@0x/tslint-config", - "version": "4.1.0", - "engines": { - "node": ">=6.12" - }, - "description": "Lint rules related to 0xProject for TSLint", - "main": "tslint.json", - "scripts": { - "build": "tsc -b", - "build:ci": "yarn build", - "test": "mocha ./lib/test/*.spec.js", - "clean": "shx rm -rf lib", - "lint": "tslint --format stylish --project ." - }, - "repository": { - "type": "git", - "url": "git://github.com/0xProject/0x-monorepo.git" - }, - "keywords": [ - "tslint", - "config", - "0xProject", - "typescript", - "ts" - ], - "author": { - "name": "Fabio Berger", - "email": "fabio@0xproject.com" - }, - "license": "Apache-2.0", - "bugs": { - "url": "https://github.com/0xProject/0x-monorepo/issues" - }, - "homepage": "https://github.com/0xProject/0x-monorepo/packages/tslint-config/README.md", - "devDependencies": { - "@types/lodash": "4.14.104", - "make-promises-safe": "^1.1.0", - "shx": "^0.2.2", - "typescript": "3.0.1" - }, - "dependencies": { - "lodash": "^4.17.11", - "tslint": "5.11.0", - "tslint-eslint-rules": "5.4.0", - "tslint-react": "^3.2.0", - "tsutils": "3.0.0" - }, - "publishConfig": { - "access": "public" - } -} diff --git a/packages/tslint-config/rules/asyncSuffixRule.ts b/packages/tslint-config/rules/asyncSuffixRule.ts deleted file mode 100644 index 5215c71514..0000000000 --- a/packages/tslint-config/rules/asyncSuffixRule.ts +++ /dev/null @@ -1,10 +0,0 @@ -import * as Lint from 'tslint'; -import * as ts from 'typescript'; - -import { AsyncSuffixWalker } from './walkers/async_suffix'; - -export class Rule extends Lint.Rules.AbstractRule { - public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - return this.applyWithWalker(new AsyncSuffixWalker(sourceFile, this.getOptions())); - } -} diff --git a/packages/tslint-config/rules/booleanNamingRule.ts b/packages/tslint-config/rules/booleanNamingRule.ts deleted file mode 100644 index 238d6223f5..0000000000 --- a/packages/tslint-config/rules/booleanNamingRule.ts +++ /dev/null @@ -1,68 +0,0 @@ -import * as _ from 'lodash'; -import * as Lint from 'tslint'; -import * as ts from 'typescript'; - -const VALID_BOOLEAN_PREFIXES = ['is', 'does', 'should', 'was', 'has', 'can', 'did', 'would', 'are']; -// tslint:disable:no-unnecessary-type-assertion -export class Rule extends Lint.Rules.TypedRule { - public static FAILURE_STRING = `Boolean variable names should begin with: ${VALID_BOOLEAN_PREFIXES.join(', ')}`; - - public applyWithProgram(sourceFile: ts.SourceFile, program: ts.Program): Lint.RuleFailure[] { - return this.applyWithFunction(sourceFile, walk, undefined, program.getTypeChecker()); - } -} - -function walk(ctx: Lint.WalkContext, tc: ts.TypeChecker): void { - traverse(ctx.sourceFile); - - function traverse(node: ts.Node): void { - checkNodeForViolations(ctx, node, tc); - return ts.forEachChild(node, traverse); - } -} - -function checkNodeForViolations(ctx: Lint.WalkContext, node: ts.Node, tc: ts.TypeChecker): void { - switch (node.kind) { - // Handle: const { timestamp } = ... - case ts.SyntaxKind.BindingElement: { - const bindingElementNode = node as ts.BindingElement; - if (bindingElementNode.name.kind === ts.SyntaxKind.Identifier) { - handleBooleanNaming(bindingElementNode, tc, ctx); - } - break; - } - - // Handle regular assignments: const block = ... - case ts.SyntaxKind.VariableDeclaration: - const variableDeclarationNode = node as ts.VariableDeclaration; - if (variableDeclarationNode.name.kind === ts.SyntaxKind.Identifier) { - handleBooleanNaming(node as ts.VariableDeclaration, tc, ctx); - } - break; - - default: - _.noop(); - } -} - -function handleBooleanNaming( - node: ts.VariableDeclaration | ts.BindingElement, - tc: ts.TypeChecker, - ctx: Lint.WalkContext, -): void { - const nodeName = node.name; - const variableName = nodeName.getText(); - const lowercasedName = _.toLower(variableName); - const typeNode = tc.getTypeAtLocation(node); - const typeName = (typeNode as any).intrinsicName; - if (typeName === 'boolean') { - const hasProperName = - _.find(VALID_BOOLEAN_PREFIXES, prefix => { - return _.startsWith(lowercasedName, prefix); - }) !== undefined; - if (!hasProperName) { - ctx.addFailureAtNode(node, Rule.FAILURE_STRING); - } - } -} -// tslint:enable:no-unnecessary-type-assertion diff --git a/packages/tslint-config/rules/customNoMagicNumbersRule.ts b/packages/tslint-config/rules/customNoMagicNumbersRule.ts deleted file mode 100644 index cb124f7389..0000000000 --- a/packages/tslint-config/rules/customNoMagicNumbersRule.ts +++ /dev/null @@ -1,79 +0,0 @@ -import * as Lint from 'tslint'; -import { isPrefixUnaryExpression } from 'tsutils'; -import * as ts from 'typescript'; - -// tslint:disable:no-unnecessary-type-assertion -/** - * A modified version of the no-magic-numbers rule that allows for magic numbers - * when instantiating a BigNumber instance. - * E.g We want to be able to write: - * const amount = new BigNumber(5); - * Original source: https://github.com/palantir/tslint/blob/42b058a6baa688f8be8558b277eb056c3ff79818/src/rules/noMagicNumbersRule.ts - */ -export class Rule extends Lint.Rules.AbstractRule { - public static ALLOWED_NODES = new Set([ - ts.SyntaxKind.ExportAssignment, - ts.SyntaxKind.FirstAssignment, - ts.SyntaxKind.LastAssignment, - ts.SyntaxKind.PropertyAssignment, - ts.SyntaxKind.ShorthandPropertyAssignment, - ts.SyntaxKind.VariableDeclaration, - ts.SyntaxKind.VariableDeclarationList, - ts.SyntaxKind.EnumMember, - ts.SyntaxKind.PropertyDeclaration, - ts.SyntaxKind.Parameter, - ]); - - public static DEFAULT_ALLOWED = [-1, 0, 1]; - - public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - const allowedNumbers = this.ruleArguments.length > 0 ? this.ruleArguments : Rule.DEFAULT_ALLOWED; - return this.applyWithWalker( - // tslint:disable-next-line:no-inferred-empty-object-type - new CustomNoMagicNumbersWalker(sourceFile, this.ruleName, new Set(allowedNumbers.map(String))), - ); - } -} - -// tslint:disable-next-line:max-classes-per-file -class CustomNoMagicNumbersWalker extends Lint.AbstractWalker> { - public static FAILURE_STRING = "'magic numbers' are not allowed"; - private static _isNegativeNumberLiteral( - node: ts.Node, - ): node is ts.PrefixUnaryExpression & { operand: ts.NumericLiteral } { - return ( - isPrefixUnaryExpression(node) && - node.operator === ts.SyntaxKind.MinusToken && - node.operand.kind === ts.SyntaxKind.NumericLiteral - ); - } - public walk(sourceFile: ts.SourceFile): void { - const cb = (node: ts.Node): void => { - if (node.kind === ts.SyntaxKind.NumericLiteral) { - return this.checkNumericLiteral(node, (node as ts.NumericLiteral).text); - } - if (CustomNoMagicNumbersWalker._isNegativeNumberLiteral(node)) { - return this.checkNumericLiteral(node, `-${(node.operand as ts.NumericLiteral).text}`); - } - return ts.forEachChild(node, cb); - }; - return ts.forEachChild(sourceFile, cb); - } - - // tslint:disable:no-non-null-assertion - // tslint:disable-next-line:underscore-private-and-protected - private checkNumericLiteral(node: ts.Node, num: string): void { - if (!Rule.ALLOWED_NODES.has(node.parent!.kind) && !this.options.has(num)) { - if (node.parent!.kind === ts.SyntaxKind.NewExpression) { - const className = (node.parent! as any).expression.escapedText; - const BIG_NUMBER_NEW_EXPRESSION = 'BigNumber'; - if (className === BIG_NUMBER_NEW_EXPRESSION) { - return; // noop - } - } - this.addFailureAtNode(node, CustomNoMagicNumbersWalker.FAILURE_STRING); - } - } - // tslint:enable:no-non-null-assertion -} -// tslint:enable:no-unnecessary-type-assertion diff --git a/packages/tslint-config/rules/enumNamingRule.ts b/packages/tslint-config/rules/enumNamingRule.ts deleted file mode 100644 index 56499618fb..0000000000 --- a/packages/tslint-config/rules/enumNamingRule.ts +++ /dev/null @@ -1,60 +0,0 @@ -import * as Lint from 'tslint'; -import * as ts from 'typescript'; - -export class Rule extends Lint.Rules.AbstractRule { - public static FAILURE_STRING = `Enum member names should be PascalCase`; - - public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - return this.applyWithFunction(sourceFile, walk); - } -} - -function walk(ctx: Lint.WalkContext): void { - // Recursively walk the AST starting with root node, `ctx.sourceFile`. - // Call the function `cb` (defined below) for each child. - return ts.forEachChild(ctx.sourceFile, cb); - - function cb(node: ts.Node): void { - if (node.kind === ts.SyntaxKind.EnumMember) { - const keyNode = node.getFirstToken(ctx.sourceFile); - if (keyNode !== undefined) { - const keyText = keyNode.getText(ctx.sourceFile); - if (!isPascalCase(keyText)) { - return ctx.addFailureAtNode(node, Rule.FAILURE_STRING, getFix(keyText, node)); - } - } - } - // Continue recursion into the AST by calling function `cb` for every child of the current node. - return ts.forEachChild(node, cb); - } - - function getFix(text: string, node: ts.Node): Lint.Replacement { - let fix = toPascalCase(text); - // check for `member = value` - if (node.getChildCount(ctx.sourceFile) === 3) { - const value = node.getLastToken(ctx.sourceFile); - if (value !== undefined) { - fix += ` = ${value.getText(ctx.sourceFile)}`; - } - } - return new Lint.Replacement(node.getStart(ctx.sourceFile), node.getWidth(ctx.sourceFile), fix); - } -} - -// Modified from: https://github.com/jonschlinkert/pascalcase/ -function toPascalCase(str: string): string { - let result = str.replace(/([a-z0-9\W])([A-Z])/g, '$1 $2'); - if (result.length === 1) { - return result.toUpperCase(); - } - result = result.replace(/^[\W_\.]+|[\W_\.]+$/g, '').toLowerCase(); - result = result.charAt(0).toUpperCase() + result.slice(1); - return result.replace(/[\W_\.]+(\w|$)/g, (_, ch) => { - return ch.toUpperCase(); - }); -} -function isPascalCase(s: string): boolean { - const regex = /^([A-Z0-9]+[a-z0-9]+)+$/g; - const key = s.split('=')[0].trim(); - return regex.test(key); -} diff --git a/packages/tslint-config/rules/noLodashIsnullRule.ts b/packages/tslint-config/rules/noLodashIsnullRule.ts deleted file mode 100644 index cda0ecca14..0000000000 --- a/packages/tslint-config/rules/noLodashIsnullRule.ts +++ /dev/null @@ -1,49 +0,0 @@ -import * as Lint from 'tslint'; -import * as ts from 'typescript'; - -export class Rule extends Lint.Rules.AbstractRule { - public static FAILURE_STRING = `Use built-in equivalent`; - - public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - return this.applyWithFunction(sourceFile, walk); - } -} - -function walk(ctx: Lint.WalkContext): void { - // Recursively walk the AST starting with root node, `ctx.sourceFile`. - // Call the function `cb` (defined below) for each child. - return ts.forEachChild(ctx.sourceFile, cb); - - function cb(node: ts.Node): void { - if (node.kind === ts.SyntaxKind.CallExpression) { - const firstChild = node.getChildAt(0, ctx.sourceFile); - if ( - firstChild.kind === ts.SyntaxKind.PropertyAccessExpression && - firstChild.getText(ctx.sourceFile) === '_.isNull' - ) { - return ctx.addFailureAtNode(node, Rule.FAILURE_STRING, getFix(node)); - } - } - // Continue recursion into the AST by calling function `cb` for every child of the current node. - return ts.forEachChild(node, cb); - } - - function getFix(node: ts.Node): Lint.Replacement { - const isNegated = - node.parent.kind === ts.SyntaxKind.PrefixUnaryExpression && node.parent.getText(ctx.sourceFile)[0] === '!'; - const args = node.getChildAt(2, ctx.sourceFile).getText(ctx.sourceFile); - if (isNegated) { - return new Lint.Replacement( - node.parent.getStart(ctx.sourceFile), - node.parent.getWidth(ctx.sourceFile), - `${args} !== null`, - ); - } else { - return new Lint.Replacement( - node.getStart(ctx.sourceFile), - node.getWidth(ctx.sourceFile), - `${args} === null`, - ); - } - } -} diff --git a/packages/tslint-config/rules/noLodashIsundefinedRule.ts b/packages/tslint-config/rules/noLodashIsundefinedRule.ts deleted file mode 100644 index 6da70b21aa..0000000000 --- a/packages/tslint-config/rules/noLodashIsundefinedRule.ts +++ /dev/null @@ -1,49 +0,0 @@ -import * as Lint from 'tslint'; -import * as ts from 'typescript'; - -export class Rule extends Lint.Rules.AbstractRule { - public static FAILURE_STRING = `Use built-in equivalent`; - - public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - return this.applyWithFunction(sourceFile, walk); - } -} - -function walk(ctx: Lint.WalkContext): void { - // Recursively walk the AST starting with root node, `ctx.sourceFile`. - // Call the function `cb` (defined below) for each child. - return ts.forEachChild(ctx.sourceFile, cb); - - function cb(node: ts.Node): void { - if (node.kind === ts.SyntaxKind.CallExpression) { - const firstChild = node.getChildAt(0, ctx.sourceFile); - if ( - firstChild.kind === ts.SyntaxKind.PropertyAccessExpression && - firstChild.getText(ctx.sourceFile) === '_.isUndefined' - ) { - return ctx.addFailureAtNode(node, Rule.FAILURE_STRING, getFix(node)); - } - } - // Continue recursion into the AST by calling function `cb` for every child of the current node. - return ts.forEachChild(node, cb); - } - - function getFix(node: ts.Node): Lint.Replacement { - const isNegated = - node.parent.kind === ts.SyntaxKind.PrefixUnaryExpression && node.parent.getText(ctx.sourceFile)[0] === '!'; - const args = node.getChildAt(2, ctx.sourceFile).getText(ctx.sourceFile); - if (isNegated) { - return new Lint.Replacement( - node.parent.getStart(ctx.sourceFile), - node.parent.getWidth(ctx.sourceFile), - `${args} !== undefined`, - ); - } else { - return new Lint.Replacement( - node.getStart(ctx.sourceFile), - node.getWidth(ctx.sourceFile), - `${args} === undefined`, - ); - } - } -} diff --git a/packages/tslint-config/rules/underscorePrivateAndProtectedRule.ts b/packages/tslint-config/rules/underscorePrivateAndProtectedRule.ts deleted file mode 100644 index 8c039bea76..0000000000 --- a/packages/tslint-config/rules/underscorePrivateAndProtectedRule.ts +++ /dev/null @@ -1,61 +0,0 @@ -import * as Lint from 'tslint'; -import * as ts from 'typescript'; - -const UNDERSCORE = '_'; - -type RelevantClassMember = - | ts.MethodDeclaration - | ts.PropertyDeclaration - | ts.GetAccessorDeclaration - | ts.SetAccessorDeclaration; - -// Copied from: https://github.com/DanielRosenwasser/underscore-privates-tslint-rule -// The version on github is not published on npm -export class Rule extends Lint.Rules.AbstractRule { - public static FAILURE_STRING = 'private and protected members must be prefixed with an underscore'; - - public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - return this.applyWithFunction(sourceFile, walk); - } -} -function walk(ctx: Lint.WalkContext): void { - traverse(ctx.sourceFile); - - function traverse(node: ts.Node): void { - checkNodeForViolations(ctx, node); - return ts.forEachChild(node, traverse); - } -} -function checkNodeForViolations(ctx: Lint.WalkContext, node: ts.Node): void { - if (!isRelevantClassMember(node)) { - return; - } - // The declaration might have a computed property name or a numeric name. - const name = node.name; - if (!nameIsIdentifier(name)) { - return; - } - if (!nameStartsWithUnderscore(name.text) && memberIsPrivate(node)) { - ctx.addFailureAtNode(name, Rule.FAILURE_STRING); - } -} -function isRelevantClassMember(node: ts.Node): node is RelevantClassMember { - switch (node.kind) { - case ts.SyntaxKind.MethodDeclaration: - case ts.SyntaxKind.PropertyDeclaration: - case ts.SyntaxKind.GetAccessor: - case ts.SyntaxKind.SetAccessor: - return true; - default: - return false; - } -} -function nameStartsWithUnderscore(text: string): boolean { - return text.charCodeAt(0) === UNDERSCORE.charCodeAt(0); -} -function memberIsPrivate(node: ts.Declaration): boolean { - return Lint.hasModifier(node.modifiers, ts.SyntaxKind.PrivateKeyword, ts.SyntaxKind.ProtectedKeyword); -} -function nameIsIdentifier(node: ts.Node): node is ts.Identifier { - return node.kind === ts.SyntaxKind.Identifier; -} diff --git a/packages/tslint-config/rules/walkers/async_suffix.ts b/packages/tslint-config/rules/walkers/async_suffix.ts deleted file mode 100644 index 0218517611..0000000000 --- a/packages/tslint-config/rules/walkers/async_suffix.ts +++ /dev/null @@ -1,34 +0,0 @@ -import * as Lint from 'tslint'; -import * as ts from 'typescript'; - -export class AsyncSuffixWalker extends Lint.RuleWalker { - public static FAILURE_STRING = 'async functions/methods must have an Async suffix'; - public visitFunctionDeclaration(node: ts.FunctionDeclaration): void { - this._visitFunctionOrMethodDeclaration(node); - super.visitFunctionDeclaration(node); - } - public visitMethodDeclaration(node: ts.MethodDeclaration): void { - this._visitFunctionOrMethodDeclaration(node); - super.visitMethodDeclaration(node); - } - private _visitFunctionOrMethodDeclaration(node: ts.MethodDeclaration | ts.FunctionDeclaration): void { - const nameNode = node.name; - if (nameNode !== undefined) { - const name = nameNode.getText(); - if (node.type !== undefined) { - if (node.type.kind === ts.SyntaxKind.TypeReference) { - // tslint:disable-next-line:no-unnecessary-type-assertion - const returnTypeName = (node.type as ts.TypeReferenceNode).typeName.getText(); - if (returnTypeName === 'Promise' && !name.endsWith('Async')) { - const failure = this.createFailure( - nameNode.getStart(), - nameNode.getWidth(), - AsyncSuffixWalker.FAILURE_STRING, - ); - this.addFailure(failure); - } - } - } - } - } -} diff --git a/packages/tslint-config/test/enumNamingSpec.spec.ts b/packages/tslint-config/test/enumNamingSpec.spec.ts deleted file mode 100644 index d5b864eba2..0000000000 --- a/packages/tslint-config/test/enumNamingSpec.spec.ts +++ /dev/null @@ -1,88 +0,0 @@ -import * as assert from 'assert'; - -import { Rule } from '../rules/enumNamingRule'; - -import { getFixedResult, helper } from './lintrunner'; -const rule = 'enum-naming'; - -describe('enumNamingRule', () => { - it(`should not fail PascalCase`, () => { - const src = `enum test { MemberOne, MemberTwo }`; - const result = helper(src, rule); - assert.equal(result.errorCount, 0); - }); - it(`should not fail PascalCase keys with uncased values`, () => { - const src = `enum test { MemberOne = 'member_one', MemberTwo = 'member two' }`; - const result = helper(src, rule); - assert.equal(result.errorCount, 0); - }); - it(`should not fail PascalCase keys with numbers`, () => { - const src = `enum test { Member1 = 'member_one', MemberTwo = 'member two' }`; - const result = helper(src, rule); - assert.equal(result.errorCount, 0); - }); - it(`should fail with camelCase`, () => { - const src = `enum test { memberOne, memberTwo }`; - const result = helper(src, rule); - assert.equal(result.errorCount, 2); - }); - it(`should fail with snake case`, () => { - const src = `enum test { member_one, member_two }`; - const result = helper(src, rule); - assert.equal(result.errorCount, 2); - }); - it(`should fail with all caps`, () => { - const src = `enum test { MEMBERONE, MEMBER_TWO }`; - const result = helper(src, rule); - assert.equal(result.errorCount, 2); - }); - it(`should fail with mixed case`, () => { - const src = `enum test { member_one, MemberTwo }`; - const result = helper(src, rule); - assert.equal(result.errorCount, 1); - }); - - it(`should fail with the right position`, () => { - const src = `enum test { MemberOne, member_two }`; - const startPosition = src.indexOf('member_two'); - const endPosition = startPosition + 'member_two'.length; - const failure = helper(src, rule).failures[0]; - - assert.equal(failure.getStartPosition().getPosition(), startPosition); - assert.equal(failure.getEndPosition().getPosition(), endPosition); - assert.equal(failure.getFailure(), Rule.FAILURE_STRING); - }); - - it(`should fail with the right message`, () => { - const src = `enum test { memberOne, memberTwo }`; - const failure = helper(src, rule).failures[0]; - - assert.equal(failure.getFailure(), Rule.FAILURE_STRING); - }); -}); -describe('enumNaming fixer', () => { - it('should fix keys', () => { - const src = `enum test { MemberOne, memberTwo, member_three, MEMBER_FOUR, MEMBERFIVE }`; - const expected = `enum test { MemberOne, MemberTwo, MemberThree, MemberFour, Memberfive }`; - const actual = getFixedResult(src, rule); - const result = helper(src, rule); - assert.equal(result.errorCount, 4); // tslint:disable-line:custom-no-magic-numbers - assert.equal(actual, expected); - }); - it('should not fix values', () => { - const src = `enum test { MemberOne = 'MemberOne', memberTwo = 'memberTwo', member_three = 'member_three', MEMBER_FOUR = 'MEMBER_FOUR' }`; - const expected = `enum test { MemberOne = 'MemberOne', MemberTwo = 'memberTwo', MemberThree = 'member_three', MemberFour = 'MEMBER_FOUR' }`; - const actual = getFixedResult(src, rule); - const result = helper(src, rule); - assert.equal(result.errorCount, 3); // tslint:disable-line:custom-no-magic-numbers - assert.equal(actual, expected); - }); - it('should preserve values with equals sign', () => { - const src = `enum Operators { assign = '=', EQUALS = '==', Triple_Equals = '===' }`; - const expected = `enum Operators { Assign = '=', Equals = '==', TripleEquals = '===' }`; - const actual = getFixedResult(src, rule); - const result = helper(src, rule); - assert.equal(result.errorCount, 3); // tslint:disable-line:custom-no-magic-numbers - assert.equal(actual, expected); - }); -}); diff --git a/packages/tslint-config/test/lintrunner.ts b/packages/tslint-config/test/lintrunner.ts deleted file mode 100644 index fcd1b68444..0000000000 --- a/packages/tslint-config/test/lintrunner.ts +++ /dev/null @@ -1,23 +0,0 @@ -import * as path from 'path'; -import { Configuration, Linter, Replacement } from 'tslint'; - -export const helper = (src: string, rule: string) => { - const linter = new Linter({ fix: false }); - linter.lint( - '', - src, - Configuration.parseConfigFile({ - rules: { - [rule]: true, - }, - rulesDirectory: path.join(__dirname, '../rules'), - }), - ); - return linter.getResult(); -}; - -export const getFixedResult = (src: string, rule: string) => { - const result = helper(src, rule); - const fixes = [].concat.apply(result.failures.map(x => x.getFix())); - return Replacement.applyFixes(src, fixes); -}; diff --git a/packages/tslint-config/test/noLodashIsundefined.spec.ts b/packages/tslint-config/test/noLodashIsundefined.spec.ts deleted file mode 100644 index 5234166451..0000000000 --- a/packages/tslint-config/test/noLodashIsundefined.spec.ts +++ /dev/null @@ -1,96 +0,0 @@ -import * as assert from 'assert'; - -import { Rule } from '../rules/noLodashIsundefinedRule'; - -import { getFixedResult, helper } from './lintrunner'; -const rule = 'no-lodash-isundefined'; - -describe('noLodashIsundefinedRule', () => { - it(`should not fail built-in`, () => { - const src = `if (someObj === undefined) { // do stuff }`; - const result = helper(src, rule); - assert.equal(result.errorCount, 0); - }); - it(`should not fail custom isUndefined`, () => { - const src = `if (isUndefined(someObj)) { // do stuff }`; - const result = helper(src, rule); - assert.equal(result.errorCount, 0); - }); - it(`should fail _.isUndefined with simple identifier`, () => { - const src = `if (_.isUndefined(obj)) { // do stuff }`; - const result = helper(src, rule); - assert.equal(result.errorCount, 1); - }); - it(`should fail _.isUndefined with property access expression`, () => { - const src = `if (_.isUndefined(this.property)) { // do stuff }`; - const result = helper(src, rule); - assert.equal(result.errorCount, 1); - }); - it(`should fail _.isUndefined with element access expression`, () => { - const src = `if (_.isUndefined(someArray[nested])) { // do stuff }`; - const result = helper(src, rule); - assert.equal(result.errorCount, 1); - }); - it(`should fail _.isUndefined with property and element access expression`, () => { - const src = `if (_.isUndefined(someObj.someArray[nested])) { // do stuff }`; - const result = helper(src, rule); - assert.equal(result.errorCount, 1); - }); - - it(`should fail with the right message`, () => { - const src = `if (_.isUndefined(obj)) { // do stuff }`; - const failure = helper(src, rule).failures[0]; - - assert.equal(failure.getFailure(), Rule.FAILURE_STRING); - }); -}); -describe('noLodashIsundefined fixer', () => { - it('should fix simple identifier', () => { - const src = `if (_.isUndefined(obj)) { // do stuff }`; - const expected = `if (obj === undefined) { // do stuff }`; - const actual = getFixedResult(src, rule); - const result = helper(src, rule); - assert.equal(result.errorCount, 1); - assert.equal(actual, expected); - }); - it('should fix property access expression', () => { - const src = `if (_.isUndefined(this.property)) { // do stuff }`; - const expected = `if (this.property === undefined) { // do stuff }`; - const actual = getFixedResult(src, rule); - const result = helper(src, rule); - assert.equal(result.errorCount, 1); - assert.equal(actual, expected); - }); - it('should fix element access expression', () => { - const src = `if (_.isUndefined(someArray[nested])) { // do stuff }`; - const expected = `if (someArray[nested] === undefined) { // do stuff }`; - const actual = getFixedResult(src, rule); - const result = helper(src, rule); - assert.equal(result.errorCount, 1); - assert.equal(actual, expected); - }); - it('should fix property and element access expression', () => { - const src = `if (_.isUndefined(someObj.someArray[nested])) { // do stuff }`; - const expected = `if (someObj.someArray[nested] === undefined) { // do stuff }`; - const actual = getFixedResult(src, rule); - const result = helper(src, rule); - assert.equal(result.errorCount, 1); - assert.equal(actual, expected); - }); - it('should fix negation', () => { - const src = `if (!_.isUndefined(someObj)) { // do stuff }`; - const expected = `if (someObj !== undefined) { // do stuff }`; - const actual = getFixedResult(src, rule); - const result = helper(src, rule); - assert.equal(result.errorCount, 1); - assert.equal(actual, expected); - }); - it('should fix negation with property and element access expression', () => { - const src = `if (!_.isUndefined(someObj.someArray[nested])) { // do stuff }`; - const expected = `if (someObj.someArray[nested] !== undefined) { // do stuff }`; - const actual = getFixedResult(src, rule); - const result = helper(src, rule); - assert.equal(result.errorCount, 1); - assert.equal(actual, expected); - }); -}); diff --git a/packages/tslint-config/tsconfig.json b/packages/tslint-config/tsconfig.json deleted file mode 100644 index b9a4dd03ef..0000000000 --- a/packages/tslint-config/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../tsconfig", - "compilerOptions": { - "outDir": "lib", - "rootDir": "." - }, - "include": ["./rules/**/*", "test/**/*"] -} diff --git a/packages/tslint-config/tslint.json b/packages/tslint-config/tslint.json deleted file mode 100644 index f761c04ba7..0000000000 --- a/packages/tslint-config/tslint.json +++ /dev/null @@ -1,132 +0,0 @@ -{ - "extends": ["tslint:latest", "tslint-react", "tslint-eslint-rules"], - "rules": { - "adjacent-overload-signatures": true, - "arrow-parens": [true, "ban-single-arg-parens"], - "arrow-return-shorthand": true, - "async-suffix": true, - "await-promise": true, - "binary-expression-operand-order": true, - "boolean-naming": true, - "callable-types": true, - "class-name": true, - "completed-docs": [ - true, - { - "functions": { - "visibilities": ["exported"] - }, - "methods": { - "locations": "instance", - "privacies": ["public", "protected"] - } - } - ], - "curly": true, - "custom-no-magic-numbers": [true, 0, 1, 2, 3, -1], - "encoding": true, - "enum-naming": true, - "eofline": true, - "import-spacing": true, - "indent": [true, "spaces", 4], - "interface-name": false, - "interface-over-type-literal": true, - "jsx-alignment": true, - "jsx-boolean-value": true, - "jsx-curly-spacing": [true, "never"], - "jsx-no-bind": false, - "jsx-no-lambda": true, - "jsx-no-multiline-js": false, - "jsx-no-string-ref": true, - "jsx-self-close": true, - "jsx-wrap-multiline": false, - "linebreak-style": [true, "LF"], - "max-classes-per-file": [true, 1], - "max-file-line-count": [true, 500], - "max-line-length": false, - "member-access": true, - "member-ordering": [true, "public-before-private", "static-before-instance", "variables-before-functions"], - "new-parens": true, - "newline-before-return": false, - "no-angle-bracket-type-assertion": true, - "no-boolean-literal-compare": true, - "no-debugger": true, - "no-default-export": true, - "no-duplicate-super": true, - "no-duplicate-switch-case": true, - "no-duplicate-variable": true, - "no-empty-interface": false, - "no-eval": true, - "no-floating-promises": true, - "no-implicit-dependencies": [true, "dev"], - "no-inferred-empty-object-type": true, - "no-invalid-template-strings": true, - "no-invalid-this": true, - "no-lodash-isnull": true, - "no-lodash-isundefined": true, - "no-misused-new": true, - "no-non-null-assertion": false, - "no-parameter-reassignment": true, - "no-redundant-jsdoc": true, - "no-return-await": true, - "no-shadowed-variable": true, - "no-sparse-arrays": true, - "no-string-literal": true, - "no-string-throw": true, - "no-submodule-imports": false, - "no-switch-case-fall-through": true, - "no-this-assignment": false, - "no-unbound-method": true, - "no-unnecessary-class": true, - "no-unnecessary-type-assertion": true, - "no-unused-variable": true, - "no-unsafe-finally": true, - "number-literal-format": true, - "object-literal-key-quotes": false, - "object-literal-sort-keys": false, - "ordered-imports": [ - true, - { - "grouped-imports": true - } - ], - "prefer-const": true, - "prefer-for-of": true, - "prefer-function-over-method": true, - "prefer-object-spread": true, - "prefer-readonly": true, - "prefer-template": true, - "promise-function-async": true, - "quotemark": [true, "single", "avoid-escape", "jsx-double"], - "restrict-plus-operands": true, - "semicolon": [true, "always"], - "space-before-function-paren": [ - true, - { - "anonymous": "never", - "asyncArrow": "always", - "constructor": "never", - "method": "never", - "named": "never" - } - ], - "space-within-parens": false, - "switch-default": true, - "type-literal-delimiter": true, - "typedef": [true, "call-signature", "parameter", "property-declaration"], - "underscore-private-and-protected": true, - "variable-name": [true, "ban-keywords", "allow-pascal-case"], - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-separator", - "check-rest-spread", - "check-type", - "check-typecast", - "check-preblock" - ] - }, - "rulesDirectory": "lib/rules" -} diff --git a/packages/types/.npmignore b/packages/types/.npmignore deleted file mode 100644 index ea588d4859..0000000000 --- a/packages/types/.npmignore +++ /dev/null @@ -1,9 +0,0 @@ -# Blacklist all files -.* -* -# Whitelist lib -!lib/**/* -# Blacklist tests and publish scripts -/lib/test/* -/lib/monorepo_scripts/ -# Package specific ignore diff --git a/packages/types/CHANGELOG.json b/packages/types/CHANGELOG.json deleted file mode 100644 index 0e2c53a2e5..0000000000 --- a/packages/types/CHANGELOG.json +++ /dev/null @@ -1,737 +0,0 @@ -[ - { - "version": "3.2.0", - "changes": [ - { - "note": "Add `ExchangeProxyMetaTransaction` and `SignedExchangeProxyMetaTransaction`", - "pr": 2610 - } - ], - "timestamp": 1594788383 - }, - { - "timestamp": 1592969527, - "version": "3.1.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1581204851, - "version": "3.1.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.1.1", - "changes": [ - { - "note": "Added `DydxBridgeOnlyCallableByErc20BridgeProxy` and `DydxBridgeUnrecognizedBridgeAction`", - "pr": 2378 - } - ], - "timestamp": 1576540892 - }, - { - "version": "3.1.0", - "changes": [ - { - "note": "Add `ERC20BridgeAssetData`", - "pr": 2373 - } - ], - "timestamp": 1575931811 - }, - { - "version": "3.0.0", - "changes": [ - { - "note": "Remove `SendTransactionOpts` and `AwaitTransactionSuccessOpts` types and move them to @0x/base-contracts", - "pr": 2325 - }, - { - "note": "Add `SendTransactionOpts` and `AwaitTransactionSuccessOpts` types for contract wrappers", - "pr": 2243 - }, - { - "note": "All references to network ID have been removed, and references to chain ID have been introduced instead", - "pr": 2313 - }, - { - "note": "Add `OrderStatus` type", - "pr": 1761 - }, - { - "note": "Add `OrderInfo`, `FillResults`, `MatchedFillResults`, `BatchMatchedFillResults` types", - "pr": 2031 - }, - { - "note": "Add status types for Staking contracts", - "pr": 1910 - }, - { - "note": "Add `ERC20Bridge` to `AssetProxyId`", - "pr": 2220 - } - ], - "timestamp": 1575296764 - }, - { - "version": "2.5.0-beta.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1575290197 - }, - { - "version": "2.5.0-beta.2", - "changes": [ - { - "note": "Remove `SendTransactionOpts` and `AwaitTransactionSuccessOpts` types and move them to @0x/base-contracts", - "pr": 2325 - } - ], - "timestamp": 1574030254 - }, - { - "version": "2.5.0-beta.1", - "changes": [ - { - "note": "Add `SendTransactionOpts` and `AwaitTransactionSuccessOpts` types for contract wrappers", - "pr": 2243 - }, - { - "note": "All references to network ID have been removed, and references to chain ID have been introduced instead", - "pr": 2313 - } - ], - "timestamp": 1573159180 - }, - { - "version": "2.5.0-beta.0", - "changes": [ - { - "note": "Add `OrderStatus` type", - "pr": 1761 - }, - { - "note": "Add `OrderInfo`, `FillResults`, `MatchedFillResults`, `BatchMatchedFillResults` types", - "pr": 2031 - }, - { - "note": "Add status types for Staking contracts", - "pr": 1910 - }, - { - "note": "Add `ERC20Bridge` to `AssetProxyId`", - "pr": 2220 - } - ], - "timestamp": 1570135330 - }, - { - "timestamp": 1568744790, - "version": "2.4.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1567521715, - "version": "2.4.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563957393, - "version": "2.4.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.4.0", - "changes": [ - { - "note": "Add MarketOperation type", - "pr": 1914 - } - ], - "timestamp": 1563006338 - }, - { - "version": "2.3.0", - "changes": [ - { - "note": "Add StaticCallProxy types", - "pr": 1863 - }, - { - "note": "Add `InvalidStaticCallDataOffset`, `TargetNotEven`, `UnexpectedStaticCallResult`, and `InvalidAssetDataEnd` to `RevertReason` enum", - "pr": 1863 - }, - { - "note": "Add `domain` field to `Order`, `ZeroExTransaction`", - "pr": 1742 - }, - { - "note": "Rename OrderWithoutExchangeAddress to OrderWithoutDomain", - "pr": 1742 - }, - { - "note": "Add `chainId` field to `EIP712DomainWithDefaultSchema`", - "pr": 1742 - }, - { - "note": "Add `OrderStatus` type", - "pr": 1761 - }, - { - "note": "Add `SignatureType.OrderValidator` and `SignatureType.WalletOrderValidator`", - "pr": 1774 - }, - { - "note": "Update `Order` type for arbitrary fee tokens (ZEIP-28).", - "pr": 1819 - }, - { - "note": "Add `expirationTimeSeconds` to `ZeroExTransaction` type", - "pr": 1832 - }, - { - "note": "Add `TransfersSuccessful` revert reason and `OrderTransferResults` enum", - "pr": 1868 - }, - { - "note": "Consolidate all Validator `SignatureType`s to just `Validator`", - "pr": 1885 - }, - { - "note": "Add `EIP1271Wallet` to `SignatureType`", - "pr": 1885 - } - ] - }, - { - "version": "2.2.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1554997931 - }, - { - "timestamp": 1553183790, - "version": "2.2.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.2.0", - "changes": [ - { - "note": "Added ERC1155 revert reasons", - "pr": 1657 - }, - { - "note": "Added `ERC1155AssetData`, `ERC1155AssetDataNoProxyId`, and `ERC1155AssetDataAbi`", - "pr": 1661 - }, - { - "note": "Add `InvalidOrigin` revert reason", - "pr": 1668 - }, - { - "note": "Add `RevertReason.SignatureInvalid` thrown by Coordinator", - "pr": 1705 - }, - { - "note": "Add `RevertReason.InvalidFreeMemoryPtr` thrown by LibAddressArray", - "pr": 1712 - } - ], - "timestamp": 1553091633 - }, - { - "timestamp": 1551220833, - "version": "2.1.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.1.0", - "changes": [ - { - "note": "Add `FromLessThanToRequired` and `ToLessThanLengthRequired` revert reasons", - "pr": 1604 - } - ], - "timestamp": 1551130135 - }, - { - "version": "2.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1549547375 - }, - { - "timestamp": 1549452781, - "version": "2.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.0", - "changes": [ - { - "note": "Upgrade the bignumber.js to v8.0.2", - "pr": 1517 - }, - { - "note": "Update `ZeroExTransaction` type and add `SignedZeroExTransaction` type", - "pr": 1576 - }, - { - "note": "Add `EIP712DomainWithDefaultSchema` type", - "pr": 1576 - } - ], - "timestamp": 1549373905 - }, - { - "timestamp": 1547561734, - "version": "1.5.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547225310, - "version": "1.5.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.5.0", - "changes": [ - { - "note": "Added types for Dutch Auction contract", - "pr": 1465 - } - ], - "timestamp": 1547040760 - }, - { - "version": "1.4.1", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544739608 - }, - { - "version": "1.4.0", - "changes": [ - { - "note": "Add `LengthMismatch` and `LengthGreaterThan3Required` revert reasons", - "pr": 1224 - }, - { - "note": "Add RevertReasons for DutchAuction contract", - "pr": 1225 - }, - { - "note": "Add MultiAsset types", - "pr": 1363 - } - ], - "timestamp": 1544570656 - }, - { - "version": "1.3.0", - "changes": [ - { - "note": "Add the `SimpleContractArtifact` type, which describes the artifact format published in the `@0x/contract-artifacts` package", - "pr": 1298 - } - ], - "timestamp": 1542821676 - }, - { - "version": "1.2.1", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1541740904 - }, - { - "version": "1.2.0", - "changes": [ - { - "note": "Added `EIP712Parameter` `EIP712Types` `EIP712TypedData` for EIP712 signing", - "pr": 1102 - }, - { - "note": "Added `ZeroExTransaction` type for Exchange executeTransaction", - "pr": 1102 - }, - { - "note": "Add `AssetData` union type (`type AssetData = ERC20AssetData | ERC721AssetData`)", - "pr": 1131 - } - ], - "timestamp": 1539871071 - }, - { - "timestamp": 1538693146, - "version": "1.1.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1538475601, - "version": "1.1.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1538157789, - "version": "1.1.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537907159, - "version": "1.1.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.1.0", - "changes": [ - { - "note": "Add ObjectMap type", - "pr": 1037 - }, - { - "note": "Add SRA types from connect", - "pr": 1085 - } - ], - "timestamp": 1537875740 - }, - { - "timestamp": 1537541580, - "version": "1.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.1", - "changes": [ - { - "note": "Add AssetProxyOwner revert reasons", - "pr": 1041 - }, - { - "note": "Add MultiSigWalletWithTimeLock revert reasons", - "pr": 1050 - } - ], - "timestamp": 1536142250 - }, - { - "version": "1.0.1-rc.6", - "changes": [ - { - "note": "Add WalletError and ValidatorError revert reasons", - "pr": 1012 - }, - { - "note": "Remove Caller and Trezor SignatureTypes", - "pr": 1015 - } - ], - "timestamp": 1535377027 - }, - { - "version": "1.0.1-rc.5", - "changes": [ - { - "note": "Add revert reasons for ERC721Token", - "pr": 933 - } - ], - "timestamp": 1535133899 - }, - { - "version": "1.0.1-rc.4", - "changes": [ - { - "pr": 914, - "note": "Added SignerType to handle different signing prefix scenarios" - } - ], - "timestamp": 1534210131 - }, - { - "version": "1.0.1-rc.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1532619515 - }, - { - "version": "1.0.1-rc.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1532614997 - }, - { - "version": "1.0.1-rc.1", - "changes": [ - { - "note": "Remove `ECSignatureBuffer`" - } - ], - "timestamp": 1532605697 - }, - { - "timestamp": 1532357734, - "version": "1.0.0", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532043000, - "version": "1.0.0-rc.1", - "changes": [ - { - "note": "Updated types for V2 of 0x protocol" - }, - { - "note": "Add `ECSignatureBuffer`" - }, - { - "note": "Add Forwarder contract revert reasons" - } - ] - }, - { - "timestamp": 1531149657, - "version": "0.8.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1529397769, - "version": "0.8.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1527009133, - "version": "0.8.0", - "changes": [ - { - "note": "Change the order type to v2 format", - "pr": 618 - } - ] - }, - { - "version": "0.7.0", - "changes": [ - { - "note": "Make OpCode type an enum", - "pr": 589 - }, - { - "note": "Moved ExchangeContractErrs, DoneCallback, Token, OrderRelevantState, OrderStateValid, OrderStateInvalid, OrderState, OrderAddresses and OrderValues types from 0x.js", - "pr": 579 - } - ], - "timestamp": 1527009133 - }, - { - "timestamp": 1525477860, - "version": "0.6.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1525428773, - "version": "0.6.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1524044013, - "version": "0.6.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.6.0", - "changes": [ - { - "note": "Add Provider type", - "pr": 501 - } - ], - "timestamp": 1523462196 - }, - { - "version": "0.5.0", - "changes": [ - { - "note": "Make `DataItem.components` optional", - "pr": 485 - } - ], - "timestamp": 1522673609 - }, - { - "timestamp": 1522658513, - "version": "0.4.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.4.0", - "changes": [ - { - "note": "Remove `JSONRPCPayload`", - "pr": 426 - }, - { - "note": "Consolidate `Order`, `SignedOrder`, and `ECSignature` into the `@0xproject/types` package", - "pr": 456 - } - ], - "timestamp": 1521298800 - }, - { - "version": "0.3.1", - "changes": [ - { - "note": "Added `RawLogEntry` type." - } - ], - "timestamp": 1520434800 - }, - { - "version": "0.3.0", - "changes": [ - { - "note": "Add `data` to `TxData`", - "pr": 413 - }, - { - "note": "Add `number` as an option to `ContractEventArg`", - "pr": 413 - }, - { - "note": "Move web3 types from devDep to dep since required when using this package", - "pr": 429 - } - ], - "timestamp": 1520089200 - }, - { - "version": "0.2.1", - "changes": [ - { - "note": "Fix publishing issue where .npmignore was not properly excluding undesired content", - "pr": 389 - } - ], - "timestamp": 1518102000 - }, - { - "version": "0.2.0", - "changes": [ - { - "note": "Added BlockLiteralParam and BlockParam, refactored out of 0x.js types.", - "pr": 355 - } - ], - "timestamp": 1517929200 - } -] diff --git a/packages/types/CHANGELOG.md b/packages/types/CHANGELOG.md deleted file mode 100644 index 3507f2090e..0000000000 --- a/packages/types/CHANGELOG.md +++ /dev/null @@ -1,290 +0,0 @@ - - -CHANGELOG - -## v3.2.0 - _July 15, 2020_ - - * Add `ExchangeProxyMetaTransaction` and `SignedExchangeProxyMetaTransaction` (#2610) - -## v3.1.3 - _June 24, 2020_ - - * Dependencies updated - -## v3.1.2 - _February 8, 2020_ - - * Dependencies updated - -## v3.1.1 - _December 17, 2019_ - - * Added `DydxBridgeOnlyCallableByErc20BridgeProxy` and `DydxBridgeUnrecognizedBridgeAction` (#2378) - -## v3.1.0 - _December 9, 2019_ - - * Add `ERC20BridgeAssetData` (#2373) - -## v3.0.0 - _December 2, 2019_ - - * Remove `SendTransactionOpts` and `AwaitTransactionSuccessOpts` types and move them to @0x/base-contracts (#2325) - * Add `SendTransactionOpts` and `AwaitTransactionSuccessOpts` types for contract wrappers (#2243) - * All references to network ID have been removed, and references to chain ID have been introduced instead (#2313) - * Add `OrderStatus` type (#1761) - * Add `OrderInfo`, `FillResults`, `MatchedFillResults`, `BatchMatchedFillResults` types (#2031) - * Add status types for Staking contracts (#1910) - * Add `ERC20Bridge` to `AssetProxyId` (#2220) - -## v2.5.0-beta.3 - _December 2, 2019_ - - * Dependencies updated - -## v2.5.0-beta.2 - _November 17, 2019_ - - * Remove `SendTransactionOpts` and `AwaitTransactionSuccessOpts` types and move them to @0x/base-contracts (#2325) - -## v2.5.0-beta.1 - _November 7, 2019_ - - * Add `SendTransactionOpts` and `AwaitTransactionSuccessOpts` types for contract wrappers (#2243) - * All references to network ID have been removed, and references to chain ID have been introduced instead (#2313) - -## v2.5.0-beta.0 - _October 3, 2019_ - - * Add `OrderStatus` type (#1761) - * Add `OrderInfo`, `FillResults`, `MatchedFillResults`, `BatchMatchedFillResults` types (#2031) - * Add status types for Staking contracts (#1910) - * Add `ERC20Bridge` to `AssetProxyId` (#2220) - -## v2.4.3 - _September 17, 2019_ - - * Dependencies updated - -## v2.4.2 - _September 3, 2019_ - - * Dependencies updated - -## v2.4.1 - _July 24, 2019_ - - * Dependencies updated - -## v2.4.0 - _July 13, 2019_ - - * Add MarketOperation type (#1914) - -## v2.3.0 - _Invalid date_ - - * Add StaticCallProxy types (#1863) - * Add `InvalidStaticCallDataOffset`, `TargetNotEven`, `UnexpectedStaticCallResult`, and `InvalidAssetDataEnd` to `RevertReason` enum (#1863) - * Add `domain` field to `Order`, `ZeroExTransaction` (#1742) - * Rename OrderWithoutExchangeAddress to OrderWithoutDomain (#1742) - * Add `chainId` field to `EIP712DomainWithDefaultSchema` (#1742) - * Add `OrderStatus` type (#1761) - * Add `SignatureType.OrderValidator` and `SignatureType.WalletOrderValidator` (#1774) - * Update `Order` type for arbitrary fee tokens (ZEIP-28). (#1819) - * Add `expirationTimeSeconds` to `ZeroExTransaction` type (#1832) - * Add `TransfersSuccessful` revert reason and `OrderTransferResults` enum (#1868) - * Consolidate all Validator `SignatureType`s to just `Validator` (#1885) - * Add `EIP1271Wallet` to `SignatureType` (#1885) - -## v2.2.2 - _April 11, 2019_ - - * Dependencies updated - -## v2.2.1 - _March 21, 2019_ - - * Dependencies updated - -## v2.2.0 - _March 20, 2019_ - - * Added ERC1155 revert reasons (#1657) - * Added `ERC1155AssetData`, `ERC1155AssetDataNoProxyId`, and `ERC1155AssetDataAbi` (#1661) - * Add `InvalidOrigin` revert reason (#1668) - * Add `RevertReason.SignatureInvalid` thrown by Coordinator (#1705) - * Add `RevertReason.InvalidFreeMemoryPtr` thrown by LibAddressArray (#1712) - -## v2.1.1 - _February 26, 2019_ - - * Dependencies updated - -## v2.1.0 - _February 25, 2019_ - - * Add `FromLessThanToRequired` and `ToLessThanLengthRequired` revert reasons (#1604) - -## v2.0.2 - _February 7, 2019_ - - * Dependencies updated - -## v2.0.1 - _February 6, 2019_ - - * Dependencies updated - -## v2.0.0 - _February 5, 2019_ - - * Upgrade the bignumber.js to v8.0.2 (#1517) - * Update `ZeroExTransaction` type and add `SignedZeroExTransaction` type (#1576) - * Add `EIP712DomainWithDefaultSchema` type (#1576) - -## v1.5.2 - _January 15, 2019_ - - * Dependencies updated - -## v1.5.1 - _January 11, 2019_ - - * Dependencies updated - -## v1.5.0 - _January 9, 2019_ - - * Added types for Dutch Auction contract (#1465) - -## v1.4.1 - _December 13, 2018_ - - * Dependencies updated - -## v1.4.0 - _December 11, 2018_ - - * Add `LengthMismatch` and `LengthGreaterThan3Required` revert reasons (#1224) - * Add RevertReasons for DutchAuction contract (#1225) - * Add MultiAsset types (#1363) - -## v1.3.0 - _November 21, 2018_ - - * Add the `SimpleContractArtifact` type, which describes the artifact format published in the `@0x/contract-artifacts` package (#1298) - -## v1.2.1 - _November 9, 2018_ - - * Dependencies updated - -## v1.2.0 - _October 18, 2018_ - - * Added `EIP712Parameter` `EIP712Types` `EIP712TypedData` for EIP712 signing (#1102) - * Added `ZeroExTransaction` type for Exchange executeTransaction (#1102) - * Add `AssetData` union type (`type AssetData = ERC20AssetData | ERC721AssetData`) (#1131) - -## v1.1.4 - _October 4, 2018_ - - * Dependencies updated - -## v1.1.3 - _October 2, 2018_ - - * Dependencies updated - -## v1.1.2 - _September 28, 2018_ - - * Dependencies updated - -## v1.1.1 - _September 25, 2018_ - - * Dependencies updated - -## v1.1.0 - _September 25, 2018_ - - * Add ObjectMap type (#1037) - * Add SRA types from connect (#1085) - -## v1.0.2 - _September 21, 2018_ - - * Dependencies updated - -## v1.0.1 - _September 5, 2018_ - - * Add AssetProxyOwner revert reasons (#1041) - * Add MultiSigWalletWithTimeLock revert reasons (#1050) - -## v1.0.1-rc.6 - _August 27, 2018_ - - * Add WalletError and ValidatorError revert reasons (#1012) - * Remove Caller and Trezor SignatureTypes (#1015) - -## v1.0.1-rc.5 - _August 24, 2018_ - - * Add revert reasons for ERC721Token (#933) - -## v1.0.1-rc.4 - _August 14, 2018_ - - * Added SignerType to handle different signing prefix scenarios (#914) - -## v1.0.1-rc.3 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.1-rc.2 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.1-rc.1 - _July 26, 2018_ - - * Remove `ECSignatureBuffer` - -## v1.0.0 - _July 23, 2018_ - - * Dependencies updated - -## v1.0.0-rc.1 - _July 19, 2018_ - - * Updated types for V2 of 0x protocol - * Add `ECSignatureBuffer` - * Add Forwarder contract revert reasons - -## v0.8.2 - _July 9, 2018_ - - * Dependencies updated - -## v0.8.1 - _June 19, 2018_ - - * Dependencies updated - -## v0.8.0 - _May 22, 2018_ - - * Change the order type to v2 format (#618) - -## v0.7.0 - _May 22, 2018_ - - * Make OpCode type an enum (#589) - * Moved ExchangeContractErrs, DoneCallback, Token, OrderRelevantState, OrderStateValid, OrderStateInvalid, OrderState, OrderAddresses and OrderValues types from 0x.js (#579) - -## v0.6.3 - _May 4, 2018_ - - * Dependencies updated - -## v0.6.2 - _May 4, 2018_ - - * Dependencies updated - -## v0.6.1 - _April 18, 2018_ - - * Dependencies updated - -## v0.6.0 - _April 11, 2018_ - - * Add Provider type (#501) - -## v0.5.0 - _April 2, 2018_ - - * Make `DataItem.components` optional (#485) - -## v0.4.2 - _April 2, 2018_ - - * Dependencies updated - -## v0.4.0 - _March 17, 2018_ - - * Remove `JSONRPCPayload` (#426) - * Consolidate `Order`, `SignedOrder`, and `ECSignature` into the `@0xproject/types` package (#456) - -## v0.3.1 - _March 7, 2018_ - - * Added `RawLogEntry` type. - -## v0.3.0 - _March 3, 2018_ - - * Add `data` to `TxData` (#413) - * Add `number` as an option to `ContractEventArg` (#413) - * Move web3 types from devDep to dep since required when using this package (#429) - -## v0.2.1 - _February 8, 2018_ - - * Fix publishing issue where .npmignore was not properly excluding undesired content (#389) - -## v0.2.0 - _February 6, 2018_ - - * Added BlockLiteralParam and BlockParam, refactored out of 0x.js types. (#355) diff --git a/packages/types/README.md b/packages/types/README.md deleted file mode 100644 index fcaf5aaa04..0000000000 --- a/packages/types/README.md +++ /dev/null @@ -1,69 +0,0 @@ -## @0x/types - -TypeScript types shared across 0x projects and packages - -## Installation - -```bash -yarn add -D @0x/types -``` - -If your project is in [TypeScript](https://www.typescriptlang.org/), add the following to your `tsconfig.json`: - -```json -"compilerOptions": { - "typeRoots": ["node_modules/@0x/typescript-typings/types", "node_modules/@types"], -} -``` - -## Usage - -```javascript -import { TransactionReceipt, TxData, TxDataPayable } from '@0x/types'; -``` - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install dependencies - -If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: - -```bash -yarn config set workspaces-experimental true -``` - -Then install dependencies - -```bash -yarn install -``` - -### Build - -To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory: - -```bash -PKG=@0x/types yarn build -``` - -Or continuously rebuild on change: - -```bash -PKG=@0x/types yarn watch -``` - -### Clean - -```bash -yarn clean -``` - -### Lint - -```bash -yarn lint -``` diff --git a/packages/types/package.json b/packages/types/package.json deleted file mode 100644 index 6a06115fc7..0000000000 --- a/packages/types/package.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "name": "@0x/types", - "version": "3.2.0", - "engines": { - "node": ">=6.12" - }, - "description": "0x types", - "main": "lib/index.js", - "types": "lib/index.d.ts", - "scripts": { - "build": "tsc -b", - "build:ci": "yarn build", - "clean": "shx rm -rf lib", - "lint": "tslint --format stylish --project ." - }, - "license": "Apache-2.0", - "repository": { - "type": "git", - "url": "https://github.com/0xProject/0x-monorepo.git" - }, - "bugs": { - "url": "https://github.com/0xProject/0x-monorepo/issues" - }, - "homepage": "https://github.com/0xProject/0x-monorepo/packages/types/README.md", - "devDependencies": { - "@0x/tslint-config": "^4.1.0", - "make-promises-safe": "^1.1.0", - "shx": "^0.2.2", - "tslint": "5.11.0", - "typescript": "3.0.1" - }, - "dependencies": { - "@types/node": "12.12.54", - "bignumber.js": "~9.0.0", - "ethereum-types": "^3.2.0" - }, - "publishConfig": { - "access": "public" - }, - "gitHead": "4f91bfd907996b2f4dd383778b50c479c2602b56" -} diff --git a/packages/types/src/globals.d.ts b/packages/types/src/globals.d.ts deleted file mode 100644 index 94e63a32de..0000000000 --- a/packages/types/src/globals.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -declare module '*.json' { - const json: any; - /* tslint:disable */ - export default json; - /* tslint:enable */ -} diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts deleted file mode 100644 index e5583f8a00..0000000000 --- a/packages/types/src/index.ts +++ /dev/null @@ -1,904 +0,0 @@ -// tslint:disable:max-file-line-count - -import { BigNumber } from 'bignumber.js'; -import { - ContractAbi, - ContractChains, - ContractEventArg, - DecodedLogArgs, - DevdocOutput, - LogWithDecodedArgs, -} from 'ethereum-types'; - -export interface Order { - chainId: number; - exchangeAddress: string; - makerAddress: string; - takerAddress: string; - feeRecipientAddress: string; - senderAddress: string; - makerAssetAmount: BigNumber; - takerAssetAmount: BigNumber; - makerFee: BigNumber; - takerFee: BigNumber; - expirationTimeSeconds: BigNumber; - salt: BigNumber; - makerAssetData: string; - takerAssetData: string; - makerFeeAssetData: string; - takerFeeAssetData: string; -} - -export interface SignedOrder extends Order { - signature: string; -} - -export enum MarketOperation { - Sell = 'Sell', - Buy = 'Buy', -} - -/** - * ZeroExTransaction for use with 0x Exchange executeTransaction - */ -export interface ZeroExTransaction { - salt: BigNumber; - expirationTimeSeconds: BigNumber; - gasPrice: BigNumber; - signerAddress: string; - data: string; - domain: EIP712DomainWithDefaultSchema; -} - -export interface SignedZeroExTransaction extends ZeroExTransaction { - signature: string; -} - -/** - * Exchange Proxy meta transaction struct. - */ -export interface ExchangeProxyMetaTransaction { - signer: string; - sender: string; - minGasPrice: BigNumber; - maxGasPrice: BigNumber; - expirationTimeSeconds: BigNumber; - salt: BigNumber; - callData: string; - value: BigNumber; - feeToken: string; - feeAmount: BigNumber; - domain: EIP712DomainWithDefaultSchema; -} - -/** - * `ExchangeProxyMetaTransaction` with `signature` field. - */ -export interface SignedExchangeProxyMetaTransaction extends ExchangeProxyMetaTransaction { - signature: string; -} - -/** - * Elliptic Curve signature - */ -export interface ECSignature { - v: number; - r: string; - s: string; -} - -/** - * Validator signature components - */ -export interface ValidatorSignature { - validatorAddress: string; - signature: string; -} - -/** - * Errors originating from the 0x exchange contract - */ -export enum ExchangeContractErrs { - OrderFillExpired = 'ORDER_FILL_EXPIRED', - OrderCancelExpired = 'ORDER_CANCEL_EXPIRED', - OrderCancelled = 'ORDER_CANCELLED', - OrderFillAmountZero = 'ORDER_FILL_AMOUNT_ZERO', - OrderRemainingFillAmountZero = 'ORDER_REMAINING_FILL_AMOUNT_ZERO', - OrderFillRoundingError = 'ORDER_FILL_ROUNDING_ERROR', - FillBalanceAllowanceError = 'FILL_BALANCE_ALLOWANCE_ERROR', - InsufficientTakerBalance = 'INSUFFICIENT_TAKER_BALANCE', - InsufficientTakerAllowance = 'INSUFFICIENT_TAKER_ALLOWANCE', - InsufficientMakerBalance = 'INSUFFICIENT_MAKER_BALANCE', - InsufficientMakerAllowance = 'INSUFFICIENT_MAKER_ALLOWANCE', - InsufficientTakerFeeBalance = 'INSUFFICIENT_TAKER_FEE_BALANCE', - InsufficientTakerFeeAllowance = 'INSUFFICIENT_TAKER_FEE_ALLOWANCE', - InsufficientMakerFeeBalance = 'INSUFFICIENT_MAKER_FEE_BALANCE', - InsufficientMakerFeeAllowance = 'INSUFFICIENT_MAKER_FEE_ALLOWANCE', - TransactionSenderIsNotFillOrderTaker = 'TRANSACTION_SENDER_IS_NOT_FILL_ORDER_TAKER', - MultipleMakersInSingleCancelBatchDisallowed = 'MULTIPLE_MAKERS_IN_SINGLE_CANCEL_BATCH_DISALLOWED', - InsufficientRemainingFillAmount = 'INSUFFICIENT_REMAINING_FILL_AMOUNT', - MultipleTakerTokensInFillUpToDisallowed = 'MULTIPLE_TAKER_TOKENS_IN_FILL_UP_TO_DISALLOWED', - BatchOrdersMustHaveSameExchangeAddress = 'BATCH_ORDERS_MUST_HAVE_SAME_EXCHANGE_ADDRESS', - BatchOrdersMustHaveAtLeastOneItem = 'BATCH_ORDERS_MUST_HAVE_AT_LEAST_ONE_ITEM', -} - -export type ArtifactContractName = 'ZRX' | 'TokenTransferProxy' | 'TokenRegistry' | 'Token' | 'Exchange' | 'EtherToken'; - -export interface Artifact { - contract_name: ArtifactContractName; - abi: ContractAbi; - chains: { - [chainId: number]: { - address: string; - }; - }; -} - -export type DoneCallback = (err?: Error) => void; - -export interface OrderRelevantState { - makerBalance: BigNumber; - makerIndividualBalances: ObjectMap; - makerProxyAllowance: BigNumber; - makerIndividualProxyAllowances: ObjectMap; - makerFeeBalance: BigNumber; - makerFeeProxyAllowance: BigNumber; - filledTakerAssetAmount: BigNumber; - remainingFillableMakerAssetAmount: BigNumber; - remainingFillableTakerAssetAmount: BigNumber; -} - -export interface OrderStateValid { - isValid: true; - orderHash: string; - orderRelevantState: OrderRelevantState; - transactionHash?: string; -} - -export interface OrderStateInvalid { - isValid: false; - orderHash: string; - error: ExchangeContractErrs; - transactionHash?: string; -} - -export type OrderState = OrderStateValid | OrderStateInvalid; - -export interface Token { - name: string; - address: string; - symbol: string; - decimals: number; -} - -export enum SignatureType { - Illegal, - Invalid, - EIP712, - EthSign, - Wallet, - Validator, - PreSigned, - EIP1271Wallet, - NSignatureTypes, -} - -export enum AssetProxyId { - ERC20 = '0xf47261b0', - ERC721 = '0x02571792', - MultiAsset = '0x94cfcdd7', - ERC1155 = '0xa7cb5fb7', - StaticCall = '0xc339d10a', - ERC20Bridge = '0xdc1600f3', -} - -export interface ERC20AssetData { - assetProxyId: string; - tokenAddress: string; -} - -export interface ERC20BridgeAssetData { - assetProxyId: string; - tokenAddress: string; - bridgeAddress: string; - bridgeData: string; -} - -export interface ERC721AssetData { - assetProxyId: string; - tokenAddress: string; - tokenId: BigNumber; -} - -export interface ERC1155AssetData { - assetProxyId: string; - tokenAddress: string; - tokenIds: BigNumber[]; - tokenValues: BigNumber[]; - callbackData: string; -} - -export interface StaticCallAssetData { - assetProxyId: string; - callTarget: string; - staticCallData: string; - callResultHash: string; -} - -export interface ERC1155AssetDataNoProxyId { - tokenAddress: string; - tokenValues: BigNumber[]; - tokenIds: BigNumber[]; - callbackData: string; -} - -export type SingleAssetData = - | ERC20AssetData - | ERC20BridgeAssetData - | ERC721AssetData - | ERC1155AssetData - | StaticCallAssetData; - -export interface MultiAssetData { - assetProxyId: string; - amounts: BigNumber[]; - nestedAssetData: string[]; -} - -export interface MultiAssetDataWithRecursiveDecoding { - assetProxyId: string; - amounts: BigNumber[]; - nestedAssetData: SingleAssetData[]; -} - -export interface DutchAuctionData { - assetData: AssetData; - beginTimeSeconds: BigNumber; - beginAmount: BigNumber; -} - -export type AssetData = SingleAssetData | MultiAssetData | MultiAssetDataWithRecursiveDecoding; - -// TODO: DRY. These should be extracted from contract code. -export enum RevertReason { - OrderUnfillable = 'ORDER_UNFILLABLE', - InvalidMaker = 'INVALID_MAKER', - InvalidTaker = 'INVALID_TAKER', - InvalidSender = 'INVALID_SENDER', - InvalidOrderSignature = 'INVALID_ORDER_SIGNATURE', - InvalidTakerAmount = 'INVALID_TAKER_AMOUNT', - DivisionByZero = 'DIVISION_BY_ZERO', - RoundingError = 'ROUNDING_ERROR', - InvalidSignature = 'INVALID_SIGNATURE', - SignatureIllegal = 'SIGNATURE_ILLEGAL', - SignatureInvalid = 'SIGNATURE_INVALID', - SignatureUnsupported = 'SIGNATURE_UNSUPPORTED', - TakerOverpay = 'TAKER_OVERPAY', - OrderOverfill = 'ORDER_OVERFILL', - InvalidFillPrice = 'INVALID_FILL_PRICE', - InvalidNewOrderEpoch = 'INVALID_NEW_ORDER_EPOCH', - CompleteFillFailed = 'COMPLETE_FILL_FAILED', - NegativeSpreadRequired = 'NEGATIVE_SPREAD_REQUIRED', - ReentrancyIllegal = 'REENTRANCY_ILLEGAL', - InvalidTxHash = 'INVALID_TX_HASH', - InvalidTxSignature = 'INVALID_TX_SIGNATURE', - FailedExecution = 'FAILED_EXECUTION', - AssetProxyAlreadyExists = 'ASSET_PROXY_ALREADY_EXISTS', - LengthGreaterThan0Required = 'LENGTH_GREATER_THAN_0_REQUIRED', - LengthGreaterThan3Required = 'LENGTH_GREATER_THAN_3_REQUIRED', - LengthGreaterThan131Required = 'LENGTH_GREATER_THAN_131_REQUIRED', - Length0Required = 'LENGTH_0_REQUIRED', - Length65Required = 'LENGTH_65_REQUIRED', - InvalidAmount = 'INVALID_AMOUNT', - TransferFailed = 'TRANSFER_FAILED', - SenderNotAuthorized = 'SENDER_NOT_AUTHORIZED', - TargetNotAuthorized = 'TARGET_NOT_AUTHORIZED', - TargetAlreadyAuthorized = 'TARGET_ALREADY_AUTHORIZED', - IndexOutOfBounds = 'INDEX_OUT_OF_BOUNDS', - AuthorizedAddressMismatch = 'AUTHORIZED_ADDRESS_MISMATCH', - OnlyContractOwner = 'ONLY_CONTRACT_OWNER', - MakerNotWhitelisted = 'MAKER_NOT_WHITELISTED', - TakerNotWhitelisted = 'TAKER_NOT_WHITELISTED', - AssetProxyDoesNotExist = 'ASSET_PROXY_DOES_NOT_EXIST', - LengthMismatch = 'LENGTH_MISMATCH', - LibBytesGreaterThanZeroLengthRequired = 'GREATER_THAN_ZERO_LENGTH_REQUIRED', - LibBytesGreaterOrEqualTo4LengthRequired = 'GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED', - LibBytesGreaterOrEqualTo20LengthRequired = 'GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED', - LibBytesGreaterOrEqualTo32LengthRequired = 'GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED', - LibBytesGreaterOrEqualToNestedBytesLengthRequired = 'GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED', - LibBytesGreaterOrEqualToSourceBytesLengthRequired = 'GREATER_OR_EQUAL_TO_SOURCE_BYTES_LENGTH_REQUIRED', - Erc20InsufficientBalance = 'ERC20_INSUFFICIENT_BALANCE', - Erc20InsufficientAllowance = 'ERC20_INSUFFICIENT_ALLOWANCE', - FeePercentageTooLarge = 'FEE_PERCENTAGE_TOO_LARGE', - ValueGreaterThanZero = 'VALUE_GREATER_THAN_ZERO', - InvalidMsgValue = 'INVALID_MSG_VALUE', - InsufficientEthRemaining = 'INSUFFICIENT_ETH_REMAINING', - Uint256Overflow = 'UINT256_OVERFLOW', - Erc721ZeroToAddress = 'ERC721_ZERO_TO_ADDRESS', - Erc721OwnerMismatch = 'ERC721_OWNER_MISMATCH', - Erc721InvalidSpender = 'ERC721_INVALID_SPENDER', - Erc721ZeroOwner = 'ERC721_ZERO_OWNER', - Erc721InvalidSelector = 'ERC721_INVALID_SELECTOR', - WalletError = 'WALLET_ERROR', - ValidatorError = 'VALIDATOR_ERROR', - InvalidFunctionSelector = 'INVALID_FUNCTION_SELECTOR', - InvalidAssetData = 'INVALID_ASSET_DATA', - InvalidAssetProxy = 'INVALID_ASSET_PROXY', - UnregisteredAssetProxy = 'UNREGISTERED_ASSET_PROXY', - TxFullyConfirmed = 'TX_FULLY_CONFIRMED', - TxNotFullyConfirmed = 'TX_NOT_FULLY_CONFIRMED', - TimeLockIncomplete = 'TIME_LOCK_INCOMPLETE', - // LibAddressArray - InvalidFreeMemoryPtr = 'INVALID_FREE_MEMORY_PTR', - // DutchAuction - AuctionInvalidAmount = 'INVALID_AMOUNT', - AuctionExpired = 'AUCTION_EXPIRED', - AuctionNotStarted = 'AUCTION_NOT_STARTED', - AuctionInvalidBeginTime = 'INVALID_BEGIN_TIME', - InvalidAssetDataEnd = 'INVALID_ASSET_DATA_END', - // Balance Threshold Filter - InvalidOrBlockedExchangeSelector = 'INVALID_OR_BLOCKED_EXCHANGE_SELECTOR', - BalanceQueryFailed = 'BALANCE_QUERY_FAILED', - AtLeastOneAddressDoesNotMeetBalanceThreshold = 'AT_LEAST_ONE_ADDRESS_DOES_NOT_MEET_BALANCE_THRESHOLD', - FromLessThanToRequired = 'FROM_LESS_THAN_TO_REQUIRED', - ToLessThanLengthRequired = 'TO_LESS_THAN_LENGTH_REQUIRED', - InvalidApprovalSignature = 'INVALID_APPROVAL_SIGNATURE', - ApprovalExpired = 'APPROVAL_EXPIRED', - InvalidOrigin = 'INVALID_ORIGIN', - // ERC1155 - AmountEqualToOneRequired = 'AMOUNT_EQUAL_TO_ONE_REQUIRED', - BadReceiverReturnValue = 'BAD_RECEIVER_RETURN_VALUE', - CannotTransferToAddressZero = 'CANNOT_TRANSFER_TO_ADDRESS_ZERO', - InsufficientAllowance = 'INSUFFICIENT_ALLOWANCE', - NFTNotOwnedByFromAddress = 'NFT_NOT_OWNED_BY_FROM_ADDRESS', - OwnersAndIdsMustHaveSameLength = 'OWNERS_AND_IDS_MUST_HAVE_SAME_LENGTH', - TokenAndValuesLengthMismatch = 'TOKEN_AND_VALUES_LENGTH_MISMATCH', - TriedToMintFungibleForNonFungibleToken = 'TRIED_TO_MINT_FUNGIBLE_FOR_NON_FUNGIBLE_TOKEN', - TriedToMintNonFungibleForFungibleToken = 'TRIED_TO_MINT_NON_FUNGIBLE_FOR_FUNGIBLE_TOKEN', - TransferRejected = 'TRANSFER_REJECTED', - Uint256Underflow = 'UINT256_UNDERFLOW', - InvalidIdsOffset = 'INVALID_IDS_OFFSET', - InvalidValuesOffset = 'INVALID_VALUES_OFFSET', - InvalidDataOffset = 'INVALID_DATA_OFFSET', - InvalidAssetDataLength = 'INVALID_ASSET_DATA_LENGTH', - // StaticCall - InvalidStaticCallDataOffset = 'INVALID_STATIC_CALL_DATA_OFFSET', - TargetNotEven = 'TARGET_NOT_EVEN', - UnexpectedStaticCallResult = 'UNEXPECTED_STATIC_CALL_RESULT', - TransfersSuccessful = 'TRANSFERS_SUCCESSFUL', - // Staking - InsufficientFunds = 'INSUFFICIENT_FUNDS', - // AssetProxyOwner - TxAlreadyExecuted = 'TX_ALREADY_EXECUTED', - DefaultTimeLockIncomplete = 'DEFAULT_TIME_LOCK_INCOMPLETE', - CustomTimeLockIncomplete = 'CUSTOM_TIME_LOCK_INCOMPLETE', - EqualLengthsRequired = 'EQUAL_LENGTHS_REQUIRED', - OnlyCallableByWallet = 'ONLY_CALLABLE_BY_WALLET', - ChaiBridgeOnlyCallableByErc20BridgeProxy = 'ChaiBridge/ONLY_CALLABLE_BY_ERC20_BRIDGE_PROXY', - ChaiBridgeDrawDaiFailed = 'ChaiBridge/DRAW_DAI_FAILED', - DydxBridgeOnlyCallableByErc20BridgeProxy = 'DydxBridge/ONLY_CALLABLE_BY_ERC20_BRIDGE_PROXY', - DydxBridgeUnrecognizedBridgeAction = 'DydxBridge/UNRECOGNIZED_BRIDGE_ACTION', -} - -export enum StatusCodes { - Success = 200, - NotFound = 404, - InternalError = 500, - MethodNotAllowed = 405, - GatewayTimeout = 504, -} - -export interface ObjectMap { - [key: string]: T; -} - -/** - * makerAssetData: Subscribes to new orders with the specified `makerAssetData` - * takerAssetData: subscribes to new orders with the specified `takerAssetData` - * traderAssetData: subscribes to new orders where either `makerAssetData` or `takerAssetData` has the value specified - * makerAssetProxyId: returns orders where the maker asset is of certain asset proxy id (example: `0xf47261b0` for ERC20, `0x02571792` for ERC721) - * takerAssetProxyId: returns orders where the taker asset is of certain asset proxy id(example: `0xf47261b0` for ERC20, `0x02571792` for ERC721) - * makerAssetAddress: subscribes to new orders where the contract address for the maker asset matches the value specified - * takerAssetAddress: subscribes to new orders where the contract address for the taker asset matches the value specified - */ -export interface OrdersChannelSubscriptionOpts { - makerAssetData?: string; - takerAssetData?: string; - traderAssetData?: string; - makerAssetProxyId?: string; - takerAssetProxyId?: string; - makerAssetAddress?: string; - takerAssetAddress?: string; -} - -export type OrdersChannelMessage = UpdateOrdersChannelMessage | UnknownOrdersChannelMessage; - -export enum OrdersChannelMessageTypes { - Update = 'update', - Unknown = 'unknown', -} - -export interface UpdateOrdersChannelMessage { - type: OrdersChannelMessageTypes.Update; - requestId: string; - payload: APIOrder[]; -} - -export interface UnknownOrdersChannelMessage { - type: OrdersChannelMessageTypes.Unknown; - requestId: string; - payload: undefined; -} - -export enum WebsocketConnectionEventType { - Close = 'close', - Error = 'error', - Message = 'message', -} - -export enum WebsocketClientEventType { - Connect = 'connect', - ConnectFailed = 'connectFailed', -} - -export type OrdersResponse = PaginatedCollection; - -export interface APIOrder { - order: SignedOrder; - metaData: object; -} - -export interface AssetPairsRequestOpts { - assetDataA?: string; - assetDataB?: string; -} - -export type AssetPairsResponse = PaginatedCollection; - -export interface AssetPairsItem { - assetDataA: Asset; - assetDataB: Asset; -} - -export interface Asset { - assetData: string; - minAmount: BigNumber; - maxAmount: BigNumber; - precision: number; -} - -export interface OrdersRequestOpts { - makerAssetProxyId?: string; - takerAssetProxyId?: string; - makerAssetAddress?: string; - takerAssetAddress?: string; - exchangeAddress?: string; - senderAddress?: string; - makerAssetData?: string; - takerAssetData?: string; - makerFeeAssetData?: string; - takerFeeAssetData?: string; - makerAddress?: string; - takerAddress?: string; - traderAddress?: string; - feeRecipientAddress?: string; -} - -export interface OrderbookRequest { - baseAssetData: string; - quoteAssetData: string; -} - -export interface OrderbookResponse { - bids: PaginatedCollection; - asks: PaginatedCollection; -} - -export interface PaginatedCollection { - total: number; - page: number; - perPage: number; - records: T[]; -} - -export interface OrderConfigRequest { - makerAddress: string; - takerAddress: string; - makerAssetAmount: BigNumber; - takerAssetAmount: BigNumber; - makerAssetData: string; - takerAssetData: string; - exchangeAddress: string; - expirationTimeSeconds: BigNumber; -} - -export interface OrderConfigResponse { - makerFee: BigNumber; - takerFee: BigNumber; - feeRecipientAddress: string; - senderAddress: string; - makerFeeAssetData: string; - takerFeeAssetData: string; -} - -export type FeeRecipientsResponse = PaginatedCollection; - -export interface RequestOpts { - chainId?: number; -} - -export interface PagedRequestOpts { - page?: number; - perPage?: number; -} - -export interface TypeDocType { - type: TypeDocTypes; - value: string; - name: string; - types: TypeDocType[]; - typeArguments?: TypeDocType[]; - declaration: TypeDocNode; - elementType?: TypeDocType; - indexSignature?: TypeDocNode; - elements?: TupleElement[]; -} - -export interface TupleElement { - type: string; - name: string; -} - -export interface TypeDocNode { - id?: number; - name?: string; - kind?: string; - defaultValue?: string; - kindString?: string; - type?: TypeDocType; - fileName?: string; - line?: number; - comment?: TypeDocNode; - text?: string; - shortText?: string; - returns?: string; - declaration: TypeDocNode; - flags?: TypeDocFlags; - indexSignature?: TypeDocNode; - signatures?: TypeDocNode[]; - parameters?: TypeDocNode[]; - typeParameter?: TypeDocNode[]; - sources?: TypeDocNode[]; - children?: TypeDocNode[]; - groups?: TypeDocGroup[]; -} - -export interface TypeDocFlags { - isStatic?: boolean; - isOptional?: boolean; - isPublic?: boolean; - isExported?: boolean; -} - -export interface TypeDocGroup { - title: string; - children: number[]; -} - -export enum TypeDocTypes { - Intrinsic = 'intrinsic', - Reference = 'reference', - Array = 'array', - StringLiteral = 'stringLiteral', - Reflection = 'reflection', - Union = 'union', - TypeParameter = 'typeParameter', - Intersection = 'intersection', - Tuple = 'tuple', - Unknown = 'unknown', -} - -export interface CustomTypeChild { - name: string; - type?: Type; - defaultValue?: string; -} - -export interface Event { - name: string; - eventArgs: EventArg[]; -} - -export interface EventArg { - isIndexed: boolean; - name: string; - type: Type; -} - -export interface Property { - name: string; - type: Type; - source?: Source; - comment?: string; - callPath?: string; -} - -export interface BaseMethod { - isConstructor: boolean; - name: string; - returnComment?: string | undefined; - callPath: string; - parameters: Parameter[]; - returnType: Type; - comment?: string; -} - -export interface BaseFunction { - name: string; - returnComment?: string | undefined; - parameters: Parameter[]; - returnType: Type; - comment?: string; -} - -export interface TypeDefinitionByName { - [typeName: string]: CustomType; -} - -export interface DocAgnosticFormat { - [sectionName: string]: DocSection; -} - -export interface DocSection { - comment: string; - constructors: Array; - methods: Array; - properties: Property[]; - types: CustomType[]; - functions: TypescriptFunction[]; - events?: Event[]; - externalExportToLink?: ExternalExportToLink; -} - -export interface TypescriptMethod extends BaseMethod { - source?: Source; - isStatic?: boolean; - typeParameter?: TypeParameter; -} - -export interface TypescriptFunction extends BaseFunction { - source?: Source; - typeParameter?: TypeParameter; - callPath: string; -} - -export interface SolidityMethod extends BaseMethod { - isConstant?: boolean; - isPayable?: boolean; - isFallback?: boolean; -} - -export interface Source { - fileName: string; - line: number; -} - -export interface Parameter { - name: string; - comment: string; - isOptional: boolean; - type: Type; - defaultValue?: string; -} - -export interface TypeParameter { - name: string; - type: Type; -} - -export interface Type { - name: string; - typeDocType: TypeDocTypes; - value?: string; - isExportedClassReference?: boolean; - typeArguments?: Type[]; - elementType?: ElementType; - types?: Type[]; - method?: TypescriptMethod; - indexSignature?: IndexSignature; - externalLink?: string; - tupleElements?: Type[]; -} - -export interface ElementType { - name: string; - typeDocType: TypeDocTypes; -} - -export interface IndexSignature { - keyName: string; - keyType: Type; - valueName: string; -} - -export interface CustomType { - name: string; - kindString: string; - type?: Type; - method?: TypescriptMethod; - indexSignature?: IndexSignature; - defaultValue?: string; - comment?: string; - children?: CustomTypeChild[]; -} -export interface GeneratedDocJson { - version: string; - metadata: Metadata; - typedocJson: TypeDocNode; -} - -export interface ExportNameToTypedocNames { - [exportName: string]: string[]; -} - -export interface ExternalTypeToLink { - [externalTypeName: string]: string; -} - -export interface ExternalExportToLink { - [externalExport: string]: string; -} - -export interface Metadata { - exportPathToTypedocNames: ExportNameToTypedocNames; - exportPathOrder: string[]; - externalTypeToLink: ExternalTypeToLink; - externalExportToLink: ExternalExportToLink; -} - -export interface EIP712Parameter { - name: string; - type: string; -} - -export interface EIP712Types { - [key: string]: EIP712Parameter[]; -} - -export type EIP712ObjectValue = string | number | EIP712Object; - -export interface EIP712Object { - [key: string]: EIP712ObjectValue; -} - -export interface EIP712TypedData { - types: EIP712Types; - domain: EIP712Object; - message: EIP712Object; - primaryType: string; -} - -export interface Stats { - orderCount: number; -} - -export interface DutchAuctionDetails { - beginTimeSeconds: BigNumber; - endTimeSeconds: BigNumber; - beginAmount: BigNumber; - endAmount: BigNumber; - currentAmount: BigNumber; - currentTimeSeconds: BigNumber; -} - -export interface PackageJSONConfig { - postpublish?: { - assets?: string[]; - docOmitExports?: string[]; - dockerHubRepo?: string; - }; - 'abis:comment'?: string; - abis?: string; - ignoreDependencyVersions?: string; - ignoreDependencyVersionsForPackage?: string; -} - -export interface PackageJSON { - private?: boolean; - version: string; - name: string; - main?: string; - scripts?: { [command: string]: string }; - config?: PackageJSONConfig; - dependencies?: { [dependencyName: string]: string }; - devDependencies?: { [dependencyName: string]: string }; - workspaces?: string[]; -} - -export interface EIP712DomainWithDefaultSchema { - name?: string; - version?: string; - chainId: number; - verifyingContract: string; -} - -export enum OrderStatus { - Invalid, - InvalidMakerAssetAmount, - InvalidTakerAssetAmount, - Fillable, - Expired, - FullyFilled, - Cancelled, -} - -export enum OrderTransferResults { - TakerAssetDataFailed, - MakerAssetDataFailed, - TakerFeeAssetDataFailed, - MakerFeeAssetDataFailed, - TransfersSuccessful, -} - -export interface FillResults { - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: BigNumber; -} - -export interface MatchedFillResults { - left: FillResults; - right: FillResults; - profitInLeftMakerAsset: BigNumber; - profitInRightMakerAsset: BigNumber; -} - -export interface BatchMatchedFillResults { - left: FillResults[]; - right: FillResults[]; - profitInLeftMakerAsset: BigNumber; - profitInRightMakerAsset: BigNumber; -} - -export interface OrderInfo { - orderStatus: number; - orderHash: string; - orderTakerAssetFilledAmount: BigNumber; -} - -export interface DecodedLogEvent { - isRemoved: boolean; - log: LogWithDecodedArgs; -} - -export type EventCallback = ( - err: null | Error, - log?: DecodedLogEvent, -) => void; - -export interface IndexedFilterValues { - [index: string]: ContractEventArg; -} - -export interface SimpleContractArtifact { - schemaVersion: string; - contractName: string; - compilerOutput: SimpleStandardContractOutput; - chains: ContractChains; -} - -export interface SimpleStandardContractOutput { - abi: ContractAbi; - evm: SimpleEvmOutput; - devdoc?: DevdocOutput; -} - -export interface SimpleEvmOutput { - bytecode: SimpleEvmBytecodeOutput; -} - -export interface SimpleEvmBytecodeOutput { - object: string; -} diff --git a/packages/types/tsconfig.json b/packages/types/tsconfig.json deleted file mode 100644 index 56689eaa34..0000000000 --- a/packages/types/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../tsconfig", - "compilerOptions": { - "outDir": "lib", - "rootDir": "src" - }, - "include": ["src/**/*"] -} diff --git a/packages/types/tslint.json b/packages/types/tslint.json deleted file mode 100644 index dd9053357e..0000000000 --- a/packages/types/tslint.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": ["@0x/tslint-config"] -} diff --git a/packages/typescript-typings/.npmignore b/packages/typescript-typings/.npmignore deleted file mode 100644 index 6c14be1f7e..0000000000 --- a/packages/typescript-typings/.npmignore +++ /dev/null @@ -1,11 +0,0 @@ -# Blacklist all files -.* -* -# Whitelist lib -!lib/**/* -# Blacklist tests and publish scripts -/lib/test/* -/lib/monorepo_scripts/ -# Package specific ignore -!types/**/* - diff --git a/packages/typescript-typings/CHANGELOG.json b/packages/typescript-typings/CHANGELOG.json deleted file mode 100644 index cb4a34e929..0000000000 --- a/packages/typescript-typings/CHANGELOG.json +++ /dev/null @@ -1,440 +0,0 @@ -[ - { - "timestamp": 1594788383, - "version": "5.1.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "5.1.0", - "changes": [ - { - "note": "Add `version()` to `SolcInstance`", - "pr": 2532 - } - ], - "timestamp": 1592969527 - }, - { - "timestamp": 1581204851, - "version": "5.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1576540892, - "version": "5.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "5.0.0", - "changes": [ - { - "note": "Add types for `@0x/dev-utils` chai helpers in `types/@0x`", - "pr": 1761 - } - ], - "timestamp": 1575296764 - }, - { - "version": "4.4.0-beta.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1574030254 - }, - { - "version": "4.4.0-beta.1", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1573159180 - }, - { - "version": "4.4.0-beta.0", - "changes": [ - { - "note": "Add types for `@0x/dev-utils` chai helpers in `types/@0x`", - "pr": 1761 - } - ], - "timestamp": 1570135330 - }, - { - "version": "4.3.0", - "changes": [ - { - "note": "Add declaration for `ethereumjs-vm`", - "pr": 2108 - } - ], - "timestamp": 1568744790 - }, - { - "timestamp": 1567521715, - "version": "4.2.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563957393, - "version": "4.2.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563006338, - "version": "4.2.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "4.2.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1554997931 - }, - { - "timestamp": 1553183790, - "version": "4.2.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "4.2.0", - "changes": [ - { - "note": "Add optional types to optimizer settings", - "pr": 1682 - } - ], - "timestamp": 1553091633 - }, - { - "version": "4.1.0", - "changes": [ - { - "note": "Add back custom web3-provider-engine type definitions", - "pr": 1627 - } - ], - "timestamp": 1551130135 - }, - { - "version": "4.0.0", - "changes": [ - { - "note": "Upgrade the bignumber.js to v8.0.2", - "pr": 1517 - } - ], - "timestamp": 1549373905 - }, - { - "timestamp": 1547561734, - "version": "3.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547225310, - "version": "3.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544739608 - }, - { - "version": "3.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544570656 - }, - { - "version": "3.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1541740904 - }, - { - "timestamp": 1539871071, - "version": "3.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1538693146, - "version": "3.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1538475601, - "version": "3.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.0.0", - "changes": [ - { - "note": "Remove types for ethers.js", - "pr": "1069" - } - ], - "timestamp": 1538157789 - }, - { - "timestamp": 1537907159, - "version": "2.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537541580, - "version": "2.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.0", - "changes": [ - { - "note": "Remove types for web3-provider-engine, newman, ganache-core, detect-node, eth-lightwallet", - "pr": "1052" - } - ], - "timestamp": 1536142250 - }, - { - "timestamp": 1535133899, - "version": "1.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1534210131, - "version": "1.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532614997, - "version": "1.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532605697, - "version": "1.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532357734, - "version": "1.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532043000, - "version": "1.0.0", - "changes": [ - { - "note": "Add types for `eth-lightwallet`", - "pr": 775 - }, - { - "note": "Improve 'web3-provider-engine' typings", - "pr": 768 - }, - { - "note": "Additional error type for `ethers.js`", - "pr": 763 - }, - { - "note": "Add @ledgerhq typings", - "pr": 770 - } - ] - }, - { - "version": "0.4.3", - "changes": [ - { - "note": "Add back ethers-contracts types for Aquaduct which relies on it", - "pr": 885 - } - ], - "timestamp": 1531919263 - }, - { - "timestamp": 1529397769, - "version": "0.4.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1529397769, - "version": "0.4.0", - "changes": [ - { - "note": "Add types for `react-joyride`" - }, - { - "note": "Add types for `react-popper`, remove types for `react-joyride`" - }, - { - "note": "Remove types for blockies, bn.js, compare-versions, ethereumjs-abi, ethereumjs-tx, find-versions, hdkey, is-mobile, solidity-parser-antlr, xml-js as they were moved to DefinitelyTyped", - "pr": 641 - } - ] - }, - { - "timestamp": 1527009133, - "version": "0.3.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1525477860, - "version": "0.3.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.3.0", - "changes": [ - { - "note": "Add types for `ethers.js`, removing `ethers-contracts`", - "pr": 540 - } - ], - "timestamp": 1525428773 - }, - { - "version": "0.2.0", - "changes": [ - { - "note": "Add types for `solc.compileStandardWrapper`", - "pr": 509 - } - ], - "timestamp": 1524044013 - }, - { - "version": "0.1.0", - "changes": [ - { - "note": "Add types for more packages", - "pr": 501 - }, - { - "note": "Add types for HDKey", - "pr": 507 - } - ], - "timestamp": 1523462196 - }, - { - "timestamp": 1522673609, - "version": "0.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.0.2", - "changes": [], - "timestamp": 1522658513 - } -] diff --git a/packages/typescript-typings/CHANGELOG.md b/packages/typescript-typings/CHANGELOG.md deleted file mode 100644 index 1765c2ff72..0000000000 --- a/packages/typescript-typings/CHANGELOG.md +++ /dev/null @@ -1,190 +0,0 @@ - - -CHANGELOG - -## v5.1.1 - _July 15, 2020_ - - * Dependencies updated - -## v5.1.0 - _June 24, 2020_ - - * Add `version()` to `SolcInstance` (#2532) - -## v5.0.2 - _February 8, 2020_ - - * Dependencies updated - -## v5.0.1 - _December 17, 2019_ - - * Dependencies updated - -## v5.0.0 - _December 2, 2019_ - - * Add types for `@0x/dev-utils` chai helpers in `types/@0x` (#1761) - -## v4.4.0-beta.2 - _November 17, 2019_ - - * Dependencies updated - -## v4.4.0-beta.1 - _November 7, 2019_ - - * Dependencies updated - -## v4.4.0-beta.0 - _October 3, 2019_ - - * Add types for `@0x/dev-utils` chai helpers in `types/@0x` (#1761) - -## v4.3.0 - _September 17, 2019_ - - * Add declaration for `ethereumjs-vm` (#2108) - -## v4.2.5 - _September 3, 2019_ - - * Dependencies updated - -## v4.2.4 - _July 24, 2019_ - - * Dependencies updated - -## v4.2.3 - _July 13, 2019_ - - * Dependencies updated - -## v4.2.2 - _April 11, 2019_ - - * Dependencies updated - -## v4.2.1 - _March 21, 2019_ - - * Dependencies updated - -## v4.2.0 - _March 20, 2019_ - - * Add optional types to optimizer settings (#1682) - -## v4.1.0 - _February 25, 2019_ - - * Add back custom web3-provider-engine type definitions (#1627) - -## v4.0.0 - _February 5, 2019_ - - * Upgrade the bignumber.js to v8.0.2 (#1517) - -## v3.0.8 - _January 15, 2019_ - - * Dependencies updated - -## v3.0.7 - _January 11, 2019_ - - * Dependencies updated - -## v3.0.6 - _December 13, 2018_ - - * Dependencies updated - -## v3.0.5 - _December 11, 2018_ - - * Dependencies updated - -## v3.0.4 - _November 9, 2018_ - - * Dependencies updated - -## v3.0.3 - _October 18, 2018_ - - * Dependencies updated - -## v3.0.2 - _October 4, 2018_ - - * Dependencies updated - -## v3.0.1 - _October 2, 2018_ - - * Dependencies updated - -## v3.0.0 - _September 28, 2018_ - - * Remove types for ethers.js (#1069) - -## v2.0.2 - _September 25, 2018_ - - * Dependencies updated - -## v2.0.1 - _September 21, 2018_ - - * Dependencies updated - -## v2.0.0 - _September 5, 2018_ - - * Remove types for web3-provider-engine, newman, ganache-core, detect-node, eth-lightwallet (#1052) - -## v1.0.5 - _August 24, 2018_ - - * Dependencies updated - -## v1.0.4 - _August 14, 2018_ - - * Dependencies updated - -## v1.0.3 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.2 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.1 - _July 23, 2018_ - - * Dependencies updated - -## v1.0.0 - _July 19, 2018_ - - * Add types for `eth-lightwallet` (#775) - * Improve 'web3-provider-engine' typings (#768) - * Additional error type for `ethers.js` (#763) - * Add @ledgerhq typings (#770) - -## v0.4.3 - _July 18, 2018_ - - * Add back ethers-contracts types for Aquaduct which relies on it (#885) - -## v0.4.1 - _June 19, 2018_ - - * Dependencies updated - -## v0.4.0 - _June 19, 2018_ - - * Add types for `react-joyride` - * Add types for `react-popper`, remove types for `react-joyride` - * Remove types for blockies, bn.js, compare-versions, ethereumjs-abi, ethereumjs-tx, find-versions, hdkey, is-mobile, solidity-parser-antlr, xml-js as they were moved to DefinitelyTyped (#641) - -## v0.3.2 - _May 22, 2018_ - - * Dependencies updated - -## v0.3.1 - _May 4, 2018_ - - * Dependencies updated - -## v0.3.0 - _May 4, 2018_ - - * Add types for `ethers.js`, removing `ethers-contracts` (#540) - -## v0.2.0 - _April 18, 2018_ - - * Add types for `solc.compileStandardWrapper` (#509) - -## v0.1.0 - _April 11, 2018_ - - * Add types for more packages (#501) - * Add types for HDKey (#507) - -## v0.0.3 - _April 2, 2018_ - - * Dependencies updated - -## v0.0.2 - _April 2, 2018_ diff --git a/packages/typescript-typings/README.md b/packages/typescript-typings/README.md deleted file mode 100644 index e3b4c044ff..0000000000 --- a/packages/typescript-typings/README.md +++ /dev/null @@ -1,65 +0,0 @@ -## @0x/typescript-typings - -Type repository for external packages used by 0x. This is like our small version of [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) - -## Installation - -```bash -yarn add -D @0x/typescript-typings -``` - -## Usage - -Add the following line within an `compilerOptions` section of your `tsconfig.json` - -```json -"typeRoots": ["node_modules/@0x/typescript-typings/types", "node_modules/@types"] -``` - -This will allow the TS compiler to first look into that repo and then fallback to DT types. - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install dependencies - -If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: - -```bash -yarn config set workspaces-experimental true -``` - -Then install dependencies - -```bash -yarn install -``` - -### Build - -To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory: - -```bash -PKG=@0x/typescript-typings yarn build -``` - -Or continuously rebuild on change: - -```bash -PKG=@0x/typescript-typings yarn watch -``` - -### Clean - -```bash -yarn clean -``` - -### Lint - -```bash -yarn lint -``` diff --git a/packages/typescript-typings/package.json b/packages/typescript-typings/package.json deleted file mode 100644 index c3e6d7dcba..0000000000 --- a/packages/typescript-typings/package.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "name": "@0x/typescript-typings", - "version": "5.1.1", - "engines": { - "node": ">=6.12" - }, - "description": "0x project typescript type definitions", - "scripts": { - "build": "tsc -b", - "build:ci": "yarn build", - "clean": "shx rm -rf lib" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/0xProject/0x-monorepo.git" - }, - "author": "Fabio Berger", - "contributors": [ - "Leonid Logvinov " - ], - "license": "Apache-2.0", - "bugs": { - "url": "https://github.com/0xProject/0x-monorepo/issues" - }, - "homepage": "https://github.com/0xProject/0x-monorepo/packages/typescript-typings#readme", - "dependencies": { - "@types/bn.js": "^4.11.0", - "@types/react": "*", - "bignumber.js": "~9.0.0", - "ethereum-types": "^3.2.0", - "popper.js": "1.14.3" - }, - "devDependencies": { - "shx": "^0.2.2", - "typescript": "3.0.1" - }, - "publishConfig": { - "access": "public" - }, - "gitHead": "4f91bfd907996b2f4dd383778b50c479c2602b56" -} diff --git a/packages/typescript-typings/tsconfig.json b/packages/typescript-typings/tsconfig.json deleted file mode 100644 index 8ea3bfb0c3..0000000000 --- a/packages/typescript-typings/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../tsconfig", - "compilerOptions": { - "outDir": "lib", - "rootDir": "." - }, - "include": ["types"] -} diff --git a/packages/typescript-typings/tslint.json b/packages/typescript-typings/tslint.json deleted file mode 100644 index 9a93a1f744..0000000000 --- a/packages/typescript-typings/tslint.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": ["tslint-config-0xproject"] -} diff --git a/packages/typescript-typings/types/@ledgerhq/index.d.ts b/packages/typescript-typings/types/@ledgerhq/index.d.ts deleted file mode 100644 index 724dacb767..0000000000 --- a/packages/typescript-typings/types/@ledgerhq/index.d.ts +++ /dev/null @@ -1,45 +0,0 @@ -// Ledgerco declarations -interface ECSignatureString { - v: string; - r: string; - s: string; -} -interface ECSignature { - v: number; - r: string; - s: string; -} - -interface LedgerTransport { - close(): Promise; -} - -declare module '@ledgerhq/hw-app-eth' { - class Eth { - public transport: LedgerTransport; - constructor(transport: LedgerTransport); - public getAddress( - path: string, - boolDisplay?: boolean, - boolChaincode?: boolean, - ): Promise<{ publicKey: string; address: string; chainCode: string }>; - public signTransaction(path: string, rawTxHex: string): Promise; - public getAppConfiguration(): Promise<{ arbitraryDataEnabled: number; version: string }>; - public signPersonalMessage(path: string, messageHex: string): Promise; - } - export default Eth; -} - -declare module '@ledgerhq/hw-transport-u2f' { - export default class TransportU2F implements LedgerTransport { - public static create(): Promise; - public close(): Promise; - } -} - -declare module '@ledgerhq/hw-transport-node-hid' { - export default class TransportNodeHid implements LedgerTransport { - public static create(): Promise; - public close(): Promise; - } -} diff --git a/packages/typescript-typings/types/async-child-process/index.d.ts b/packages/typescript-typings/types/async-child-process/index.d.ts deleted file mode 100644 index f8ed463782..0000000000 --- a/packages/typescript-typings/types/async-child-process/index.d.ts +++ /dev/null @@ -1 +0,0 @@ -declare module 'async-child-process'; diff --git a/packages/typescript-typings/types/chai-as-promised/index.d.ts b/packages/typescript-typings/types/chai-as-promised/index.d.ts deleted file mode 100644 index 6d53457551..0000000000 --- a/packages/typescript-typings/types/chai-as-promised/index.d.ts +++ /dev/null @@ -1,266 +0,0 @@ -// Type definitions for chai-as-promised -// Project: https://github.com/domenic/chai-as-promised/ -// Definitions by: jt000 , Yuki Kokubun -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module 'chai-as-promised' { - function chaiAsPromised(chai: any, utils: any): void; - namespace chaiAsPromised {} - export = chaiAsPromised; -} - -// tslint:disable:no-namespace ban-types member-ordering -declare namespace Chai { - // For BDD API - interface Assertion extends LanguageChains, NumericComparison, TypeComparison { - eventually: PromisedAssertion; - fulfilled: PromisedAssertion; - become(expected: any): PromisedAssertion; - rejected(): PromisedAssertion; - rejectedWith(expected: any, message?: string | RegExp): PromisedAssertion; - notify(fn: Function): PromisedAssertion; - } - - // Eventually does not have .then(), but PromisedAssertion have. - interface Eventually extends PromisedLanguageChains, PromisedNumericComparison, PromisedTypeComparison { - // From chai-as-promised - become(expected: PromiseLike): PromisedAssertion; - fulfilled: PromisedAssertion; - rejected: () => PromisedAssertion; - rejectedWith(expected: any, message?: string | RegExp): PromisedAssertion; - notify(fn: Function): PromisedAssertion; - - // From chai - not: PromisedAssertion; - deep: PromisedDeep; - all: PromisedKeyFilter; - a: PromisedTypeComparison; - an: PromisedTypeComparison; - include: PromisedInclude; - contain: PromisedInclude; - ok: PromisedAssertion; - true: () => PromisedAssertion; - false: () => PromisedAssertion; - null: PromisedAssertion; - undefined: PromisedAssertion; - exist: PromisedAssertion; - empty: PromisedAssertion; - arguments: PromisedAssertion; - Arguments: PromisedAssertion; - equal: PromisedEqual; - equals: PromisedEqual; - eq: PromisedEqual; - eql: PromisedEqual; - eqls: PromisedEqual; - property: PromisedProperty; - ownProperty: PromisedOwnProperty; - haveOwnProperty: PromisedOwnProperty; - length: PromisedLength; - lengthOf: PromisedLength; - match(regexp: RegExp | string, message?: string): PromisedAssertion; - string(string: string, message?: string): PromisedAssertion; - keys: PromisedKeys; - key(string: string): PromisedAssertion; - throw: PromisedThrow; - throws: PromisedThrow; - Throw: PromisedThrow; - respondTo(method: string, message?: string): PromisedAssertion; - itself: PromisedAssertion; - satisfy(matcher: Function, message?: string): PromisedAssertion; - closeTo(expected: number, delta: number, message?: string): PromisedAssertion; - members: PromisedMembers; - } - - interface PromisedAssertion extends Eventually, PromiseLike {} - - interface PromisedLanguageChains { - eventually: Eventually; - - // From chai - to: PromisedAssertion; - be: PromisedAssertion; - been: PromisedAssertion; - is: PromisedAssertion; - that: PromisedAssertion; - which: PromisedAssertion; - and: PromisedAssertion; - has: PromisedAssertion; - have: PromisedAssertion; - with: PromisedAssertion; - at: PromisedAssertion; - of: PromisedAssertion; - same: PromisedAssertion; - } - - interface PromisedNumericComparison { - above: PromisedNumberComparer; - gt: PromisedNumberComparer; - greaterThan: PromisedNumberComparer; - least: PromisedNumberComparer; - gte: PromisedNumberComparer; - below: PromisedNumberComparer; - lt: PromisedNumberComparer; - lessThan: PromisedNumberComparer; - most: PromisedNumberComparer; - lte: PromisedNumberComparer; - within(start: number, finish: number, message?: string): PromisedAssertion; - } - - type PromisedNumberComparer = (value: number, message?: string) => PromisedAssertion; - - interface PromisedTypeComparison { - (type: string, message?: string): PromisedAssertion; - instanceof: PromisedInstanceOf; - instanceOf: PromisedInstanceOf; - } - - type PromisedInstanceOf = (constructor: Object, message?: string) => PromisedAssertion; - - interface PromisedDeep { - equal: PromisedEqual; - include: PromisedInclude; - property: PromisedProperty; - } - - interface PromisedKeyFilter { - keys: PromisedKeys; - } - - type PromisedEqual = (value: any, message?: string) => PromisedAssertion; - - type PromisedProperty = (name: string, value?: any, message?: string) => PromisedAssertion; - - type PromisedOwnProperty = (name: string, message?: string) => PromisedAssertion; - - interface PromisedLength extends PromisedLanguageChains, PromisedNumericComparison { - (length: number, message?: string): PromisedAssertion; - } - - interface PromisedInclude { - (value: Object | string | number, message?: string): PromisedAssertion; - keys: PromisedKeys; - members: PromisedMembers; - all: PromisedKeyFilter; - } - - interface PromisedKeys { - (...keys: string[]): PromisedAssertion; - (keys: any[]): PromisedAssertion; - } - - interface PromisedThrow { - (): PromisedAssertion; - (expected: string | RegExp, message?: string): PromisedAssertion; - (constructor: Error | Function, expected?: string | RegExp, message?: string): PromisedAssertion; - } - - type PromisedMembers = (set: any[], message?: string) => PromisedAssertion; - - // For Assert API - interface Assert { - eventually: PromisedAssert; - isFulfilled(promise: PromiseLike, message?: string): PromiseLike; - becomes(promise: PromiseLike, expected: any, message?: string): PromiseLike; - doesNotBecome(promise: PromiseLike, expected: any, message?: string): PromiseLike; - isRejected(promise: PromiseLike, message?: string): PromiseLike; - isRejected(promise: PromiseLike, expected: any | RegExp, message?: string): PromiseLike; - notify(fn: Function): PromiseLike; - } - - export interface PromisedAssert { - fail(actual?: any, expected?: any, msg?: string, operator?: string): PromiseLike; - - ok(val: any, msg?: string): PromiseLike; - notOk(val: any, msg?: string): PromiseLike; - - equal(act: any, exp: any, msg?: string): PromiseLike; - notEqual(act: any, exp: any, msg?: string): PromiseLike; - - strictEqual(act: any, exp: any, msg?: string): PromiseLike; - notStrictEqual(act: any, exp: any, msg?: string): PromiseLike; - - deepEqual(act: any, exp: any, msg?: string): PromiseLike; - notDeepEqual(act: any, exp: any, msg?: string): PromiseLike; - - isTrue(val: any, msg?: string): PromiseLike; - isFalse(val: any, msg?: string): PromiseLike; - - isNull(val: any, msg?: string): PromiseLike; - isNotNull(val: any, msg?: string): PromiseLike; - - isUndefined(val: any, msg?: string): PromiseLike; - isDefined(val: any, msg?: string): PromiseLike; - - isFunction(val: any, msg?: string): PromiseLike; - isNotFunction(val: any, msg?: string): PromiseLike; - - isObject(val: any, msg?: string): PromiseLike; - isNotObject(val: any, msg?: string): PromiseLike; - - isArray(val: any, msg?: string): PromiseLike; - isNotArray(val: any, msg?: string): PromiseLike; - - isString(val: any, msg?: string): PromiseLike; - isNotString(val: any, msg?: string): PromiseLike; - - isNumber(val: any, msg?: string): PromiseLike; - isNotNumber(val: any, msg?: string): PromiseLike; - - isBoolean(val: any, msg?: string): PromiseLike; - isNotBoolean(val: any, msg?: string): PromiseLike; - - typeOf(val: any, type: string, msg?: string): PromiseLike; - notTypeOf(val: any, type: string, msg?: string): PromiseLike; - - instanceOf(val: any, type: Function, msg?: string): PromiseLike; - notInstanceOf(val: any, type: Function, msg?: string): PromiseLike; - - include(exp: string | any[], inc: any, msg?: string): PromiseLike; - - notInclude(exp: string | any[], inc: any, msg?: string): PromiseLike; - - match(exp: any, re: RegExp, msg?: string): PromiseLike; - notMatch(exp: any, re: RegExp, msg?: string): PromiseLike; - - property(obj: Object, prop: string, msg?: string): PromiseLike; - notProperty(obj: Object, prop: string, msg?: string): PromiseLike; - deepProperty(obj: Object, prop: string, msg?: string): PromiseLike; - notDeepProperty(obj: Object, prop: string, msg?: string): PromiseLike; - - propertyVal(obj: Object, prop: string, val: any, msg?: string): PromiseLike; - propertyNotVal(obj: Object, prop: string, val: any, msg?: string): PromiseLike; - - deepPropertyVal(obj: Object, prop: string, val: any, msg?: string): PromiseLike; - deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string): PromiseLike; - - lengthOf(exp: any, len: number, msg?: string): PromiseLike; - // alias frenzy - throw(fn: Function, msg?: string): PromiseLike; - throw(fn: Function, regExp: RegExp): PromiseLike; - throw(fn: Function, errType: Function, msg?: string): PromiseLike; - throw(fn: Function, errType: Function, regExp: RegExp): PromiseLike; - - throws(fn: Function, msg?: string): PromiseLike; - throws(fn: Function, regExp: RegExp): PromiseLike; - throws(fn: Function, errType: Function, msg?: string): PromiseLike; - throws(fn: Function, errType: Function, regExp: RegExp): PromiseLike; - - Throw(fn: Function, msg?: string): PromiseLike; - Throw(fn: Function, regExp: RegExp): PromiseLike; - Throw(fn: Function, errType: Function, msg?: string): PromiseLike; - Throw(fn: Function, errType: Function, regExp: RegExp): PromiseLike; - - doesNotThrow(fn: Function, msg?: string): PromiseLike; - doesNotThrow(fn: Function, regExp: RegExp): PromiseLike; - doesNotThrow(fn: Function, errType: Function, msg?: string): PromiseLike; - doesNotThrow(fn: Function, errType: Function, regExp: RegExp): PromiseLike; - - operator(val: any, operator: string, val2: any, msg?: string): PromiseLike; - closeTo(act: number, exp: number, delta: number, msg?: string): PromiseLike; - - sameMembers(set1: any[], set2: any[], msg?: string): PromiseLike; - includeMembers(set1: any[], set2: any[], msg?: string): PromiseLike; - - ifError(val: any, msg?: string): PromiseLike; - } -} diff --git a/packages/typescript-typings/types/chai-bignumber/index.d.ts b/packages/typescript-typings/types/chai-bignumber/index.d.ts deleted file mode 100644 index 802b69795c..0000000000 --- a/packages/typescript-typings/types/chai-bignumber/index.d.ts +++ /dev/null @@ -1 +0,0 @@ -declare module 'chai-bignumber'; diff --git a/packages/typescript-typings/types/chai/index.d.ts b/packages/typescript-typings/types/chai/index.d.ts deleted file mode 100644 index 3bde1f27c8..0000000000 --- a/packages/typescript-typings/types/chai/index.d.ts +++ /dev/null @@ -1,1257 +0,0 @@ -// Type definitions for chai 4.0.0 -// Project: http://chaijs.com/ -// Definitions by: Jed Mao , -// Bart van der Schoor , -// Andrew Brown , -// Olivier Chevet , -// Matt Wistrand , -// Josh Goldberg -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -// - -// tslint:disable:no-namespace member-ordering ban-types unified-signatures variable-name callable-types -declare namespace Chai { - interface ChaiStatic { - expect: ExpectStatic; - should(): Should; - /** - * Provides a way to extend the internals of Chai - */ - use(fn: (chai: any, utils: any) => void): ChaiStatic; - assert: AssertStatic; - config: Config; - AssertionError: typeof AssertionError; - version: string; - } - - export interface ExpectStatic extends AssertionStatic { - fail(actual?: any, expected?: any, message?: string, operator?: Operator): void; - } - - export interface AssertStatic extends Assert {} - - type AssertionStatic = (target: any, message?: string) => Assertion; - - export type Operator = string; // "==" | "===" | ">" | ">=" | "<" | "<=" | "!=" | "!=="; - - export type OperatorComparable = boolean | null | number | string | undefined | Date; - - interface ShouldAssertion { - equal(value1: any, value2: any, message?: string): void; - Throw: ShouldThrow; - throw: ShouldThrow; - exist(value: any, message?: string): void; - } - - interface Should extends ShouldAssertion { - not: ShouldAssertion; - fail(actual: any, expected: any, message?: string, operator?: Operator): void; - } - - interface ShouldThrow { - (actual: Function): void; - (actual: Function, expected: string | RegExp, message?: string): void; - (actual: Function, constructor: Error | Function, expected?: string | RegExp, message?: string): void; - } - - interface Assertion extends LanguageChains, NumericComparison, TypeComparison { - not: Assertion; - deep: Deep; - nested: Nested; - any: KeyFilter; - all: KeyFilter; - a: TypeComparison; - an: TypeComparison; - include: Include; - includes: Include; - contain: Include; - contains: Include; - ok: Assertion; - true: () => Assertion; - false: () => Assertion; - null: () => Assertion; - undefined: () => Assertion; - NaN: Assertion; - exist: Assertion; - empty: Assertion; - arguments: Assertion; - Arguments: Assertion; - equal: Equal; - equals: Equal; - eq: Equal; - eql: Equal; - eqls: Equal; - property: Property; - ownProperty: OwnProperty; - haveOwnProperty: OwnProperty; - ownPropertyDescriptor: OwnPropertyDescriptor; - haveOwnPropertyDescriptor: OwnPropertyDescriptor; - length: Length; - lengthOf: Length; - match: Match; - matches: Match; - string(string: string, message?: string): Assertion; - keys: Keys; - key(string: string): Assertion; - throw: (message?: string) => Assertion; - throws: Throw; - Throw: Throw; - respondTo: RespondTo; - respondsTo: RespondTo; - itself: Assertion; - satisfy: Satisfy; - satisfies: Satisfy; - closeTo: CloseTo; - approximately: CloseTo; - members: Members; - increase: PropertyChange; - increases: PropertyChange; - decrease: PropertyChange; - decreases: PropertyChange; - change: PropertyChange; - changes: PropertyChange; - extensible: Assertion; - sealed: Assertion; - frozen: Assertion; - bignumber: Assertion; - // HACK: In order to comply with chai-as-promised we make eventually a `PromisedAssertion` not an `Assertion` - eventually: PromisedAssertion; - oneOf(list: any[], message?: string): Assertion; - } - - interface LanguageChains { - to: Assertion; - be: Assertion; - been: Assertion; - is: Assertion; - that: Assertion; - which: Assertion; - and: Assertion; - has: Assertion; - have: Assertion; - with: Assertion; - at: Assertion; - of: Assertion; - same: Assertion; - } - - interface NumericComparison { - above: NumberComparer; - gt: NumberComparer; - greaterThan: NumberComparer; - least: NumberComparer; - gte: NumberComparer; - below: NumberComparer; - lt: NumberComparer; - lessThan: NumberComparer; - most: NumberComparer; - lte: NumberComparer; - within(start: number, finish: number, message?: string): Assertion; - } - - interface NumberComparer { - (value: number | object, message?: string): Assertion; - } - - interface TypeComparison { - (type: string, message?: string): Assertion; - instanceof: InstanceOf; - instanceOf: InstanceOf; - } - - interface InstanceOf { - (constructor: Object, message?: string): Assertion; - } - - interface CloseTo { - (expected: number, delta: number, message?: string): Assertion; - } - - interface Nested { - include: Include; - property: Property; - members: Members; - } - - interface Deep { - equal: Equal; - equals: Equal; - eq: Equal; - include: Include; - property: Property; - members: Members; - } - - interface KeyFilter { - keys: Keys; - } - - interface Equal { - (value: any, message?: string): Assertion; - } - - interface Property { - (name: string, value?: any, message?: string): Assertion; - } - - interface OwnProperty { - (name: string, message?: string): Assertion; - } - - interface OwnPropertyDescriptor { - (name: string, descriptor: PropertyDescriptor, message?: string): Assertion; - (name: string, message?: string): Assertion; - } - - interface Length extends LanguageChains, NumericComparison { - (length: number, message?: string): Assertion; - } - - interface Include { - (value: Object | string | number, message?: string): Assertion; - keys: Keys; - members: Members; - any: KeyFilter; - all: KeyFilter; - } - - interface Match { - (regexp: RegExp | string, message?: string): Assertion; - } - - interface Keys { - (...keys: string[]): Assertion; - (keys: any[]): Assertion; - (keys: Object): Assertion; - } - - interface Throw { - (): Assertion; - (expected: string, message?: string): Assertion; - (expected: RegExp, message?: string): Assertion; - (constructor: Error, expected?: string, message?: string): Assertion; - (constructor: Error, expected?: RegExp, message?: string): Assertion; - (constructor: Function, expected?: string, message?: string): Assertion; - (constructor: Function, expected?: RegExp, message?: string): Assertion; - } - - interface RespondTo { - (method: string, message?: string): Assertion; - } - - interface Satisfy { - (matcher: Function, message?: string): Assertion; - } - - interface Members { - (set: any[], message?: string): Assertion; - } - - interface PropertyChange { - (object: Object, property: string, message?: string): Assertion; - } - - export interface Assert { - /** - * @param expression Expression to test for truthiness. - * @param message Message to display on error. - */ - (expression: any, message?: string): void; - - /** - * Throws a failure. - * - * @type T Type of the objects. - * @param actual Actual value. - * @param expected Potential expected value. - * @param message Message to display on error. - * @param operator Comparison operator, if not strict equality. - * @remarks Node.js assert module-compatible. - */ - fail(actual?: T, expected?: T, message?: string, operator?: Operator): void; - - /** - * Asserts that object is truthy. - * - * @type T Type of object. - * @param object Object to test. - * @param message Message to display on error. - */ - isOk(value: T, message?: string): void; - - /** - * Asserts that object is truthy. - * - * @type T Type of object. - * @param object Object to test. - * @param message Message to display on error. - */ - ok(value: T, message?: string): void; - - /** - * Asserts that object is falsy. - * - * @type T Type of object. - * @param object Object to test. - * @param message Message to display on error. - */ - isNotOk(value: T, message?: string): void; - - /** - * Asserts that object is falsy. - * - * @type T Type of object. - * @param object Object to test. - * @param message Message to display on error. - */ - notOk(value: T, message?: string): void; - - /** - * Asserts non-strict equality (==) of actual and expected. - * - * @type T Type of the objects. - * @param actual Actual value. - * @param expected Potential expected value. - * @param message Message to display on error. - */ - equal(actual: T, expected: T, message?: string): void; - - /** - * Asserts non-strict inequality (==) of actual and expected. - * - * @type T Type of the objects. - * @param actual Actual value. - * @param expected Potential expected value. - * @param message Message to display on error. - */ - notEqual(actual: T, expected: T, message?: string): void; - - /** - * Asserts strict equality (===) of actual and expected. - * - * @type T Type of the objects. - * @param actual Actual value. - * @param expected Potential expected value. - * @param message Message to display on error. - */ - strictEqual(actual: T, expected: T, message?: string): void; - - /** - * Asserts strict inequality (==) of actual and expected. - * - * @type T Type of the objects. - * @param actual Actual value. - * @param expected Potential expected value. - * @param message Message to display on error. - */ - notStrictEqual(actual: T, expected: T, message?: string): void; - - /** - * Asserts that actual is deeply equal to expected. - * - * @type T Type of the objects. - * @param actual Actual value. - * @param expected Potential expected value. - * @param message Message to display on error. - */ - deepEqual(actual: T, expected: T, message?: string): void; - - /** - * Asserts that actual is not deeply equal to expected. - * - * @type T Type of the objects. - * @param actual Actual value. - * @param expected Potential expected value. - * @param message Message to display on error. - */ - notDeepEqual(actual: T, expected: T, message?: string): void; - - /** - * Asserts valueToCheck is strictly greater than (>) valueToBeAbove. - * - * @param valueToCheck Actual value. - * @param valueToBeAbove Minimum Potential expected value. - * @param message Message to display on error. - */ - isAbove(valueToCheck: number, valueToBeAbove: number, message?: string): void; - - /** - * Asserts valueToCheck is greater than or equal to (>=) valueToBeAtLeast. - * - * @param valueToCheck Actual value. - * @param valueToBeAtLeast Minimum Potential expected value. - * @param message Message to display on error. - */ - isAtLeast(valueToCheck: number, valueToBeAtLeast: number, message?: string): void; - - /** - * Asserts valueToCheck is strictly less than (<) valueToBeBelow. - * - * @param valueToCheck Actual value. - * @param valueToBeBelow Minimum Potential expected value. - * @param message Message to display on error. - */ - isBelow(valueToCheck: number, valueToBeBelow: number, message?: string): void; - - /** - * Asserts valueToCheck is greater than or equal to (>=) valueToBeAtMost. - * - * @param valueToCheck Actual value. - * @param valueToBeAtMost Minimum Potential expected value. - * @param message Message to display on error. - */ - isAtMost(valueToCheck: number, valueToBeAtMost: number, message?: string): void; - - /** - * Asserts that value is true. - * - * @type T Type of value. - * @param value Actual value. - * @param message Message to display on error. - */ - isTrue(value: T, message?: string): void; - - /** - * Asserts that value is false. - * - * @type T Type of value. - * @param value Actual value. - * @param message Message to display on error. - */ - isFalse(value: T, message?: string): void; - - /** - * Asserts that value is not true. - * - * @type T Type of value. - * @param value Actual value. - * @param message Message to display on error. - */ - isNotTrue(value: T, message?: string): void; - - /** - * Asserts that value is not false. - * - * @type T Type of value. - * @param value Actual value. - * @param message Message to display on error. - */ - isNotFalse(value: T, message?: string): void; - - /** - * Asserts that value is null. - * - * @type T Type of value. - * @param value Actual value. - * @param message Message to display on error. - */ - isNull(value: T, message?: string): void; - - /** - * Asserts that value is not null. - * - * @type T Type of value. - * @param value Actual value. - * @param message Message to display on error. - */ - isNotNull(value: T, message?: string): void; - - /** - * Asserts that value is not null. - * - * @type T Type of value. - * @param value Actual value. - * @param message Message to display on error. - */ - isNaN(value: T, message?: string): void; - - /** - * Asserts that value is not null. - * - * @type T Type of value. - * @param value Actual value. - * @param message Message to display on error. - */ - isNotNaN(value: T, message?: string): void; - - /** - * Asserts that value is undefined. - * - * @type T Type of value. - * @param value Actual value. - * @param message Message to display on error. - */ - isUndefined(value: T, message?: string): void; - - /** - * Asserts that value is not undefined. - * - * @type T Type of value. - * @param value Actual value. - * @param message Message to display on error. - */ - isDefined(value: T, message?: string): void; - - /** - * Asserts that value is a function. - * - * @type T Type of value. - * @param value Actual value. - * @param message Message to display on error. - */ - isFunction(value: T, message?: string): void; - - /** - * Asserts that value is not a function. - * - * @type T Type of value. - * @param value Actual value. - * @param message Message to display on error. - */ - isNotFunction(value: T, message?: string): void; - - /** - * Asserts that value is an object of type 'Object' - * (as revealed by Object.prototype.toString). - * - * @type T Type of value. - * @param value Actual value. - * @param message Message to display on error. - * @remarks The assertion does not match subclassed objects. - */ - isObject(value: T, message?: string): void; - - /** - * Asserts that value is not an object of type 'Object' - * (as revealed by Object.prototype.toString). - * - * @type T Type of value. - * @param value Actual value. - * @param message Message to display on error. - */ - isNotObject(value: T, message?: string): void; - - /** - * Asserts that value is an array. - * - * @type T Type of value. - * @param value Actual value. - * @param message Message to display on error. - */ - isArray(value: T, message?: string): void; - - /** - * Asserts that value is not an array. - * - * @type T Type of value. - * @param value Actual value. - * @param message Message to display on error. - */ - isNotArray(value: T, message?: string): void; - - /** - * Asserts that value is a string. - * - * @type T Type of value. - * @param value Actual value. - * @param message Message to display on error. - */ - isString(value: T, message?: string): void; - - /** - * Asserts that value is not a string. - * - * @type T Type of value. - * @param value Actual value. - * @param message Message to display on error. - */ - isNotString(value: T, message?: string): void; - - /** - * Asserts that value is a number. - * - * @type T Type of value. - * @param value Actual value. - * @param message Message to display on error. - */ - isNumber(value: T, message?: string): void; - - /** - * Asserts that value is not a number. - * - * @type T Type of value. - * @param value Actual value. - * @param message Message to display on error. - */ - isNotNumber(value: T, message?: string): void; - - /** - * Asserts that value is a boolean. - * - * @type T Type of value. - * @param value Actual value. - * @param message Message to display on error. - */ - isBoolean(value: T, message?: string): void; - - /** - * Asserts that value is not a boolean. - * - * @type T Type of value. - * @param value Actual value. - * @param message Message to display on error. - */ - isNotBoolean(value: T, message?: string): void; - - /** - * Asserts that value's type is name, as determined by Object.prototype.toString. - * - * @type T Type of value. - * @param value Actual value. - * @param name Potential expected type name of value. - * @param message Message to display on error. - */ - typeOf(value: T, name: string, message?: string): void; - - /** - * Asserts that value's type is not name, as determined by Object.prototype.toString. - * - * @type T Type of value. - * @param value Actual value. - * @param name Potential expected type name of value. - * @param message Message to display on error. - */ - notTypeOf(value: T, name: string, message?: string): void; - - /** - * Asserts that value is an instance of constructor. - * - * @type T Type of value. - * @param value Actual value. - * @param constructor Potential expected contructor of value. - * @param message Message to display on error. - */ - instanceOf(value: T, constructor: Function, message?: string): void; - - /** - * Asserts that value is not an instance of constructor. - * - * @type T Type of value. - * @param value Actual value. - * @param constructor Potential expected contructor of value. - * @param message Message to display on error. - */ - notInstanceOf(value: T, type: Function, message?: string): void; - - /** - * Asserts that haystack includes needle. - * - * @param haystack Container string. - * @param needle Potential expected substring of haystack. - * @param message Message to display on error. - */ - include(haystack: string, needle: string, message?: string): void; - - /** - * Asserts that haystack includes needle. - * - * @type T Type of values in haystack. - * @param haystack Container array. - * @param needle Potential value contained in haystack. - * @param message Message to display on error. - */ - include(haystack: T[], needle: T, message?: string): void; - - /** - * Asserts that haystack does not include needle. - * - * @param haystack Container string. - * @param needle Potential expected substring of haystack. - * @param message Message to display on error. - */ - notInclude(haystack: string, needle: any, message?: string): void; - - /** - * Asserts that haystack does not include needle. - * - * @type T Type of values in haystack. - * @param haystack Container array. - * @param needle Potential value contained in haystack. - * @param message Message to display on error. - */ - notInclude(haystack: any[], needle: any, message?: string): void; - - /** - * Asserts that value matches the regular expression regexp. - * - * @param value Actual value. - * @param regexp Potential match of value. - * @param message Message to display on error. - */ - match(value: string, regexp: RegExp, message?: string): void; - - /** - * Asserts that value does not match the regular expression regexp. - * - * @param value Actual value. - * @param regexp Potential match of value. - * @param message Message to display on error. - */ - notMatch(expected: any, regexp: RegExp, message?: string): void; - - /** - * Asserts that object has a property named by property. - * - * @type T Type of object. - * @param object Container object. - * @param property Potential contained property of object. - * @param message Message to display on error. - */ - property(object: T, property: string /* keyof T */, message?: string): void; - - /** - * Asserts that object has a property named by property. - * - * @type T Type of object. - * @param object Container object. - * @param property Potential contained property of object. - * @param message Message to display on error. - */ - notProperty(object: T, property: string /* keyof T */, message?: string): void; - - /** - * Asserts that object has a property named by property, which can be a string - * using dot- and bracket-notation for deep reference. - * - * @type T Type of object. - * @param object Container object. - * @param property Potential contained property of object. - * @param message Message to display on error. - */ - deepProperty(object: T, property: string, message?: string): void; - - /** - * Asserts that object does not have a property named by property, which can be a - * string using dot- and bracket-notation for deep reference. - * - * @type T Type of object. - * @param object Container object. - * @param property Potential contained property of object. - * @param message Message to display on error. - */ - notDeepProperty(object: T, property: string, message?: string): void; - - /** - * Asserts that object has a property named by property with value given by value. - * - * @type T Type of object. - * @type V Type of value. - * @param object Container object. - * @param property Potential contained property of object. - * @param value Potential expected property value. - * @param message Message to display on error. - */ - propertyVal(object: T, property: string /* keyof T */, value: V, message?: string): void; - - /** - * Asserts that object has a property named by property with value given by value. - * - * @type T Type of object. - * @type V Type of value. - * @param object Container object. - * @param property Potential contained property of object. - * @param value Potential expected property value. - * @param message Message to display on error. - */ - propertyNotVal(object: T, property: string /* keyof T */, value: V, message?: string): void; - - /** - * Asserts that object has a property named by property, which can be a string - * using dot- and bracket-notation for deep reference. - * - * @type T Type of object. - * @type V Type of value. - * @param object Container object. - * @param property Potential contained property of object. - * @param value Potential expected property value. - * @param message Message to display on error. - */ - deepPropertyVal(object: T, property: string, value: V, message?: string): void; - - /** - * Asserts that object does not have a property named by property, which can be a - * string using dot- and bracket-notation for deep reference. - * - * @type T Type of object. - * @type V Type of value. - * @param object Container object. - * @param property Potential contained property of object. - * @param value Potential expected property value. - * @param message Message to display on error. - */ - deepPropertyNotVal(object: T, property: string, value: V, message?: string): void; - - /** - * Asserts that object has a length property with the expected value. - * - * @type T Type of object. - * @param object Container object. - * @param length Potential expected length of object. - * @param message Message to display on error. - */ - lengthOf(object: T, length: number, message?: string): void; - - /** - * Asserts that fn will throw an error. - * - * @param fn Function that may throw. - * @param message Message to display on error. - */ - throw(fn: Function, message?: string): void; - - /** - * Asserts that function will throw an error with message matching regexp. - * - * @param fn Function that may throw. - * @param regExp Potential expected message match. - * @param message Message to display on error. - */ - throw(fn: Function, regExp: RegExp): void; - - /** - * Asserts that function will throw an error that is an instance of constructor. - * - * @param fn Function that may throw. - * @param constructor Potential expected error constructor. - * @param message Message to display on error. - */ - throw(fn: Function, constructor: Function, message?: string): void; - - /** - * Asserts that function will throw an error that is an instance of constructor - * and an error with message matching regexp. - * - * @param fn Function that may throw. - * @param constructor Potential expected error constructor. - * @param message Message to display on error. - */ - throw(fn: Function, constructor: Function, regExp: RegExp): void; - - /** - * Asserts that fn will throw an error. - * - * @param fn Function that may throw. - * @param message Message to display on error. - */ - throws(fn: Function, message?: string): void; - - /** - * Asserts that function will throw an error with message matching regexp. - * - * @param fn Function that may throw. - * @param regExp Potential expected message match. - * @param message Message to display on error. - */ - throws(fn: Function, regExp: RegExp, message?: string): void; - - /** - * Asserts that function will throw an error that is an instance of constructor. - * - * @param fn Function that may throw. - * @param constructor Potential expected error constructor. - * @param message Message to display on error. - */ - throws(fn: Function, errType: Function, message?: string): void; - - /** - * Asserts that function will throw an error that is an instance of constructor - * and an error with message matching regexp. - * - * @param fn Function that may throw. - * @param constructor Potential expected error constructor. - * @param message Message to display on error. - */ - throws(fn: Function, errType: Function, regExp: RegExp): void; - - /** - * Asserts that fn will throw an error. - * - * @param fn Function that may throw. - * @param message Message to display on error. - */ - Throw(fn: Function, message?: string): void; - - /** - * Asserts that function will throw an error with message matching regexp. - * - * @param fn Function that may throw. - * @param regExp Potential expected message match. - * @param message Message to display on error. - */ - Throw(fn: Function, regExp: RegExp): void; - - /** - * Asserts that function will throw an error that is an instance of constructor. - * - * @param fn Function that may throw. - * @param constructor Potential expected error constructor. - * @param message Message to display on error. - */ - Throw(fn: Function, errType: Function, message?: string): void; - - /** - * Asserts that function will throw an error that is an instance of constructor - * and an error with message matching regexp. - * - * @param fn Function that may throw. - * @param constructor Potential expected error constructor. - * @param message Message to display on error. - */ - Throw(fn: Function, errType: Function, regExp: RegExp): void; - - /** - * Asserts that fn will not throw an error. - * - * @param fn Function that may throw. - * @param message Message to display on error. - */ - doesNotThrow(fn: Function, message?: string): void; - - /** - * Asserts that function will throw an error with message matching regexp. - * - * @param fn Function that may throw. - * @param regExp Potential expected message match. - * @param message Message to display on error. - */ - doesNotThrow(fn: Function, regExp: RegExp): void; - - /** - * Asserts that function will throw an error that is an instance of constructor. - * - * @param fn Function that may throw. - * @param constructor Potential expected error constructor. - * @param message Message to display on error. - */ - doesNotThrow(fn: Function, errType: Function, message?: string): void; - - /** - * Asserts that function will throw an error that is an instance of constructor - * and an error with message matching regexp. - * - * @param fn Function that may throw. - * @param constructor Potential expected error constructor. - * @param message Message to display on error. - */ - doesNotThrow(fn: Function, errType: Function, regExp: RegExp): void; - - /** - * Compares two values using operator. - * - * @param val1 Left value during comparison. - * @param operator Comparison operator. - * @param val2 Right value during comparison. - * @param message Message to display on error. - */ - operator(val1: OperatorComparable, operator: Operator, val2: OperatorComparable, message?: string): void; - - /** - * Asserts that the target is equal to expected, to within a +/- delta range. - * - * @param actual Actual value - * @param expected Potential expected value. - * @param delta Maximum differenced between values. - * @param message Message to display on error. - */ - closeTo(actual: number, expected: number, delta: number, message?: string): void; - - /** - * Asserts that the target is equal to expected, to within a +/- delta range. - * - * @param actual Actual value - * @param expected Potential expected value. - * @param delta Maximum differenced between values. - * @param message Message to display on error. - */ - approximately(act: number, exp: number, delta: number, message?: string): void; - - /** - * Asserts that set1 and set2 have the same members. Order is not take into account. - * - * @type T Type of set values. - * @param set1 Actual set of values. - * @param set2 Potential expected set of values. - * @param message Message to display on error. - */ - sameMembers(set1: T[], set2: T[], message?: string): void; - - /** - * Asserts that set1 and set2 have the same members using deep equality checking. - * Order is not take into account. - * - * @type T Type of set values. - * @param set1 Actual set of values. - * @param set2 Potential expected set of values. - * @param message Message to display on error. - */ - sameDeepMembers(set1: T[], set2: T[], message?: string): void; - - /** - * Asserts that subset is included in superset. Order is not take into account. - * - * @type T Type of set values. - * @param superset Actual set of values. - * @param subset Potential contained set of values. - * @param message Message to display on error. - */ - includeMembers(superset: T[], subset: T[], message?: string): void; - - /** - * Asserts that subset is included in superset using deep equality checking. - * Order is not take into account. - * - * @type T Type of set values. - * @param superset Actual set of values. - * @param subset Potential contained set of values. - * @param message Message to display on error. - */ - includeDeepMembers(superset: T[], subset: T[], message?: string): void; - - /** - * Asserts that non-object, non-array value inList appears in the flat array list. - * - * @type T Type of list values. - * @param inList Value expected to be in the list. - * @param list List of values. - * @param message Message to display on error. - */ - oneOf(inList: T, list: T[], message?: string): void; - - /** - * Asserts that a function changes the value of a property. - * - * @type T Type of object. - * @param modifier Function to run. - * @param object Container object. - * @param property Property of object expected to be modified. - * @param message Message to display on error. - */ - changes(modifier: Function, object: T, property: string /* keyof T */, message?: string): void; - - /** - * Asserts that a function does not change the value of a property. - * - * @type T Type of object. - * @param modifier Function to run. - * @param object Container object. - * @param property Property of object expected not to be modified. - * @param message Message to display on error. - */ - doesNotChange(modifier: Function, object: T, property: string /* keyof T */, message?: string): void; - - /** - * Asserts that a function increases an object property. - * - * @type T Type of object. - * @param modifier Function to run. - * @param object Container object. - * @param property Property of object expected to be increased. - * @param message Message to display on error. - */ - increases(modifier: Function, object: T, property: string /* keyof T */, message?: string): void; - - /** - * Asserts that a function does not increase an object property. - * - * @type T Type of object. - * @param modifier Function to run. - * @param object Container object. - * @param property Property of object expected not to be increased. - * @param message Message to display on error. - */ - doesNotIncrease(modifier: Function, object: T, property: string /* keyof T */, message?: string): void; - - /** - * Asserts that a function decreases an object property. - * - * @type T Type of object. - * @param modifier Function to run. - * @param object Container object. - * @param property Property of object expected to be decreased. - * @param message Message to display on error. - */ - decreases(modifier: Function, object: T, property: string /* keyof T */, message?: string): void; - - /** - * Asserts that a function does not decrease an object property. - * - * @type T Type of object. - * @param modifier Function to run. - * @param object Container object. - * @param property Property of object expected not to be decreased. - * @param message Message to display on error. - */ - doesNotDecrease(modifier: Function, object: T, property: string /* keyof T */, message?: string): void; - - /** - * Asserts if value is not a false value, and throws if it is a true value. - * - * @type T Type of object. - * @param object Actual value. - * @param message Message to display on error. - * @remarks This is added to allow for chai to be a drop-in replacement for - * Node’s assert class. - */ - ifError(object: T, message?: string): void; - - /** - * Asserts that object is extensible (can have new properties added to it). - * - * @type T Type of object - * @param object Actual value. - * @param message Message to display on error. - */ - isExtensible(object: T, message?: string): void; - - /** - * Asserts that object is extensible (can have new properties added to it). - * - * @type T Type of object - * @param object Actual value. - * @param message Message to display on error. - */ - extensible(object: T, message?: string): void; - - /** - * Asserts that object is not extensible. - * - * @type T Type of object - * @param object Actual value. - * @param message Message to display on error. - */ - isNotExtensible(object: T, message?: string): void; - - /** - * Asserts that object is not extensible. - * - * @type T Type of object - * @param object Actual value. - * @param message Message to display on error. - */ - notExtensible(object: T, message?: string): void; - - /** - * Asserts that object is sealed (can have new properties added to it - * and its existing properties cannot be removed). - * - * @type T Type of object - * @param object Actual value. - * @param message Message to display on error. - */ - isSealed(object: T, message?: string): void; - - /** - * Asserts that object is sealed (can have new properties added to it - * and its existing properties cannot be removed). - * - * @type T Type of object - * @param object Actual value. - * @param message Message to display on error. - */ - sealed(object: T, message?: string): void; - - /** - * Asserts that object is not sealed. - * - * @type T Type of object - * @param object Actual value. - * @param message Message to display on error. - */ - isNotSealed(object: T, message?: string): void; - - /** - * Asserts that object is not sealed. - * - * @type T Type of object - * @param object Actual value. - * @param message Message to display on error. - */ - notSealed(object: T, message?: string): void; - - /** - * Asserts that object is frozen (cannot have new properties added to it - * and its existing properties cannot be removed). - * - * @type T Type of object - * @param object Actual value. - * @param message Message to display on error. - */ - isFrozen(object: T, message?: string): void; - - /** - * Asserts that object is frozen (cannot have new properties added to it - * and its existing properties cannot be removed). - * - * @type T Type of object - * @param object Actual value. - * @param message Message to display on error. - */ - frozen(object: T, message?: string): void; - - /** - * Asserts that object is not frozen (cannot have new properties added to it - * and its existing properties cannot be removed). - * - * @type T Type of object - * @param object Actual value. - * @param message Message to display on error. - */ - isNotFrozen(object: T, message?: string): void; - - /** - * Asserts that object is not frozen (cannot have new properties added to it - * and its existing properties cannot be removed). - * - * @type T Type of object - * @param object Actual value. - * @param message Message to display on error. - */ - notFrozen(object: T, message?: string): void; - } - - export interface Config { - /** - * Default: false - */ - includeStack: boolean; - - /** - * Default: true - */ - showDiff: boolean; - - /** - * Default: 40 - */ - truncateThreshold: number; - } - - export class AssertionError { - constructor(message: string, _props?: any, ssf?: Function); - public name: string; - public message: string; - public showDiff: boolean; - public stack: string; - } -} - -declare const chai: Chai.ChaiStatic; - -declare module 'chai' { - export = chai; -} - -interface Object { - should: Chai.Assertion; -} diff --git a/packages/typescript-typings/types/cli-format/index.d.ts b/packages/typescript-typings/types/cli-format/index.d.ts deleted file mode 100644 index 5590df022a..0000000000 --- a/packages/typescript-typings/types/cli-format/index.d.ts +++ /dev/null @@ -1 +0,0 @@ -declare module 'cli-format'; diff --git a/packages/typescript-typings/types/dirty-chai/index.d.ts b/packages/typescript-typings/types/dirty-chai/index.d.ts deleted file mode 100644 index 91ed2021ef..0000000000 --- a/packages/typescript-typings/types/dirty-chai/index.d.ts +++ /dev/null @@ -1 +0,0 @@ -declare module 'dirty-chai'; diff --git a/packages/typescript-typings/types/es6-promisify/index.d.ts b/packages/typescript-typings/types/es6-promisify/index.d.ts deleted file mode 100644 index f9c202fb0e..0000000000 --- a/packages/typescript-typings/types/es6-promisify/index.d.ts +++ /dev/null @@ -1 +0,0 @@ -declare module 'es6-promisify'; diff --git a/packages/typescript-typings/types/ethereumjs-abi/index.d.ts b/packages/typescript-typings/types/ethereumjs-abi/index.d.ts deleted file mode 100644 index 2d9fc9fcd8..0000000000 --- a/packages/typescript-typings/types/ethereumjs-abi/index.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -declare module 'ethereumjs-abi' { - export function soliditySHA3(argTypes: string[], args: any[]): Buffer; - export function soliditySHA256(argTypes: string[], args: any[]): Buffer; - export function methodID(name: string, types: string[]): Buffer; - export function simpleEncode(signature: string, ...args: any[]): Buffer; - export function rawDecode(signature: string[], data: Buffer): any[]; -} diff --git a/packages/typescript-typings/types/ethereumjs-util/index.d.ts b/packages/typescript-typings/types/ethereumjs-util/index.d.ts deleted file mode 100644 index 01353f03e1..0000000000 --- a/packages/typescript-typings/types/ethereumjs-util/index.d.ts +++ /dev/null @@ -1,100 +0,0 @@ -declare module 'ethereumjs-util' { - import BN = require('bn.js'); - - interface Signature { - v: number; - r: Buffer; - s: Buffer; - } - - export const MAX_INTEGER: BN; - - export const TWO_POW256: BN; - - export const SHA3_NULL_S: string; - - export const SHA3_NULL: Buffer; - - export const SHA3_RLP_ARRAY_S: string; - - export const SHA3_RLP_ARRAY: Buffer; - - export const SHA3_RLP_S: string; - - export const SHA3_RLP: Buffer; - - export function zeros(bytes: number): Buffer; - - export function setLength(msg: Buffer | string | number, length: number, right: boolean): Buffer; - export function setLength(msg: number[], length: number, right: boolean): number[]; - - export function setLengthLeft(msg: Buffer | string | number, length: number, right?: boolean): Buffer; - export function setLengthLeft(msg: number[], length: number, right?: boolean): number[]; - - export function setLengthRight(msg: Buffer | string | number, length: number): Buffer; - export function setLengthRight(msg: number[], length: number): number[]; - - export function unpad(a: Buffer): Buffer; - export function unpad(a: number[]): number[]; - export function unpad(a: string): string; - - export function toBuffer(v: any): Buffer; - - export function bufferToInt(buf: Buffer): number; - - export function bufferToHex(buf: Buffer): string; - - export function fromSigned(num: Buffer): BN; - - export function toUnsigned(num: BN): Buffer; - - export function sha3(a: Buffer | string | number | number[], bits?: number): Buffer; - - export function sha256(a: Buffer | string | number | number[]): Buffer; - - export function ripemd160(a: Buffer | string | number | number[], padded?: boolean): Buffer; - - export function rlphash(a: Buffer | string | number | number[]): Buffer; - - export function isValidPrivate(privateKey: Buffer): boolean; - - export function isValidPublic(publicKey: Buffer, sanitize?: boolean): boolean; - - export function pubToAddress(publicKey: Buffer, sanitize?: boolean): Buffer; - export function publicToAddress(publicKey: Buffer, sanitize?: boolean): Buffer; - - export function privateToPublic(privateKey: Buffer): Buffer; - - export function importPublic(publicKey: Buffer): Buffer; - - export function ecsign(message: Buffer, privateKey: Buffer): Signature; - - export function hashPersonalMessage(message: Buffer | string): Buffer; - - export function ecrecover(msgHash: Buffer, v: number, r: Buffer, s: Buffer): Buffer; - - export function toRpcSig(v: number, r: Buffer, s: Buffer): string; - - export function fromRpcSig(sig: string): Signature; - - export function privateToAddress(privateKey: Buffer): Buffer; - - export function isValidAddress(address: string): boolean; - - export function toChecksumAddress(address: string): string; - - export function isValidChecksumAddress(address: string): boolean; - - export function generateAddress(from: Buffer | string, nonce: number | string | number[] | Buffer): Buffer; - - export function isPrecompiled(address: Buffer | string): boolean; - - export function addHexPrefix(str: string): string; - - export function stripHexPrefix(str: string): string; - - export function isValidSignature(v: number, r: Buffer | string, s: Buffer | string, homestead?: boolean): boolean; - - export function baToJSON(ba: Buffer): string; - export function baToJSON(ba: any[]): string[]; -} diff --git a/packages/typescript-typings/types/ethereumjs-vm/index.d.ts b/packages/typescript-typings/types/ethereumjs-vm/index.d.ts deleted file mode 100644 index b5cd6ffa37..0000000000 --- a/packages/typescript-typings/types/ethereumjs-vm/index.d.ts +++ /dev/null @@ -1,334 +0,0 @@ -declare module 'ethereumjs-vm' { - import BN = require('bn.js'); - type Common = any; // from ethereumjs-common - type Account = any; // from ethereumjs-account - type Blockchain = any; // from ethereumjs-blockchain - - export default class VM { - opts: VmOpts; - stateManager: StateManager; - constructor(opts: VmOpts); - runCall(opts: RunCallOpts): Promise; - } - - interface VmOpts { - chain?: string; - hardfork?: string; - stateManager?: StateManager; - state?: any; - blockchain?: Blockchain; - activatePrecompiles?: boolean; - allowUnlimitedContractSize?: boolean; - common?: Common; - } - - interface RunCallOpts { - block?: any; - gasPrice?: Buffer; - origin?: Buffer; - caller?: Buffer; - gasLimit?: Buffer; - to?: Buffer; - value?: Buffer; - data?: Buffer; - code?: Buffer; - depth?: number; - compiled?: boolean; - static?: boolean; - salt?: Buffer; - selfdestruct?: { [k: string]: boolean }; - delegatecall?: boolean; - } - - interface EVMResult { - gasUsed: BN; - createdAddress?: Buffer; - execResult: ExecResult; - } - - interface ExecResult { - runState?: RunState; - exceptionError?: VmError; - gas?: BN; - gasUsed: BN; - returnValue: Buffer; - logs?: any[]; - gasRefund?: BN; - selfdestruct?: { [k: string]: Buffer }; - } - interface RunState { - programCounter: number; - opCode: number; - memory: Memory; - memoryWordCount: BN; - highestMemCost: BN; - stack: Stack; - code: Buffer; - validJumps: number[]; - _common: Common; - stateManager: StateManager; - eei: EEI; - } - - class Memory { - _store: number[]; - constructor(); - extend(offset: number, size: number): void; - write(offset: number, size: number, value: Buffer): void; - read(offset: number, size: number): Buffer; - } - - class Stack { - _store: BN[]; - constructor(); - length(): number; - push(value: BN): void; - pop(): BN; - popN(num: number): BN[]; - swap(position: number): void; - dup(position: number): void; - } - - class StateManager { - _common: Common; - _trie: any; - _storageTries: any; - _cache: Cache; - _touched: Set; - _touchedStack: Set[]; - _checkpointCount: number; - _originalStorageCache: Map>; - - constructor(opts: StateManagerOpts); - copy(): StateManager; - getAccount(address: Buffer, cb: any): void; - putAccount(address: Buffer, account: Account, cb: any): void; - putContractCode(address: Buffer, value: Buffer, cb: any): void; - getContractCode(address: Buffer, cb: any): void; - _lookupStorageTrie(address: Buffer, cb: any): void; - _getStorageTrie(address: Buffer, cb: any): void; - getContractStorage(address: Buffer, key: Buffer, cb: any): void; - getOriginalContractStorage(address: Buffer, key: Buffer, cb: any): void; - _modifyContractStorage(address: Buffer, modifyTrie: any, cb: any): void; - putContractStorage(address: Buffer, key: Buffer, value: Buffer, cb: any): void; - clearContractStorage(address: Buffer, cb: any): void; - checkpoint(cb: any): void; - commit(cb: any): void; - revert(cb: any): void; - getStateRoot(cb: any): void; - setStateRoot(stateRoot: Buffer, cb: any): void; - dumpStorage(address: Buffer, cb: any): void; - hasGenesisState(cb: any): void; - generateCanonicalGenesis(cb: any): void; - generateGenesis(initState: any, cb: any): void; - accountIsEmpty(address: Buffer, cb: any): void; - cleanupTouchedAccounts(cb: any): void; - _clearOriginalStorageCache(): void; - } - - class Cache { - _cache: any; - _checkpoints: any[]; - _trie: any; - constructor(trie: any); - put(key: Buffer, val: Account, fromTrie: boolean): void; - get(key: Buffer): Account; - lookup(key: Buffer): Account | undefined; - _lookupAccount(address: Buffer, cb: any): void; - getOrLoad(key: Buffer, cb: any): void; - warm(addresses: string[], cb: any): void; - flush(cb: any): void; - checkpoint(): void; - revert(): void; - commit(): void; - clear(): void; - del(key: Buffer): void; - _update(key: Buffer, val: Account, modified: boolean, deleted: boolean): void; - } - - interface StateManagerOpts { - common?: Common; - trie?: any; - } - - class EEI { - _env: Env; - _result: RunResult; - _state: PStateManager; - _evm: EVM; - _lastReturned: Buffer; - _common: Common; - _gasLeft: BN; - constructor(env: Env, state: PStateManager, evm: EVM, common: Common, gasLeft: BN); - useGas(amount: BN): void; - refundGas(amount: BN): void; - getAddress(): Buffer; - getExternalBalance(address: Buffer): Promise; - getSelfBalance(): BN; - getCaller(): BN; - getCallValue(): BN; - getCallData(): Buffer; - getCallDataSize(): BN; - getCodeSize(): BN; - getCode(): Buffer; - isStatic(): boolean; - getExternalCodeSize(address: BN): Promise; - getExternalCode(address: BN | Buffer): Promise; - getReturnDataSize(): BN; - getReturnData(): Buffer; - getTxGasPrice(): BN; - getTxOrigin(): BN; - getBlockNumber(): BN; - getBlockCoinbase(): BN; - getBlockTimestamp(): BN; - getBlockDifficulty(): BN; - getBlockGasLimit(): BN; - getChainId(): BN; - getBlockHash(num: BN): Promise; - storageStore(key: Buffer, value: Buffer): Promise; - storageLoad(key: Buffer): Promise; - getGasLeft(): BN; - finish(returnData: Buffer): void; - revert(returnData: Buffer): void; - selfDestruct(toAddress: Buffer): Promise; - _selfDestruct(toAddress: Buffer): Promise; - log(data: Buffer, numberOfTopics: number, topics: Buffer[]): void; - call(gasLimit: BN, address: Buffer, value: BN, data: Buffer): Promise; - callCode(gasLimit: BN, address: Buffer, value: BN, data: Buffer): Promise; - callStatic(gasLimit: BN, address: Buffer, value: BN, data: Buffer): Promise; - callDelegate(gasLimit: BN, address: Buffer, value: BN, data: Buffer): Promise; - _baseCall(msg: Message): Promise; - create(gasLimit: BN, value: BN, data: Buffer, salt: Buffer | null): Promise; - create2(gasLimit: BN, value: BN, data: Buffer, salt: Buffer): Promise; - isAccountEmpty(address: Buffer): Promise; - private _getReturnCode(results: EVMResult): any; - } - - interface Env { - blockchain: Blockchain; - address: Buffer; - caller: Buffer; - callData: Buffer; - callValue: BN; - code: Buffer; - isStatic: boolean; - depth: number; - gasPrice: Buffer; - origin: Buffer; - block: any; - contract: Account; - } - - interface RunResult { - logs: any; - returnValue?: Buffer; - gasRefund: BN; - selfdestruct: { [k: string]: Buffer }; - } - - export class PStateManager { - _wrapped: StateManager; - constructor(wrapped: StateManager); - copy(): PStateManager; - getAccount(addr: Buffer): Promise; - putAccount(addr: Buffer, account: Account): Promise; - putContractCode(addr: Buffer, code: Buffer): Promise; - getContractCode(addr: Buffer): Promise; - getContractStorage(addr: Buffer, key: Buffer): Promise; - getOriginalContractStorage(addr: Buffer, key: Buffer): Promise; - putContractStorage(addr: Buffer, key: Buffer, value: Buffer): Promise; - clearContractStorage(addr: Buffer): Promise; - checkpoint(): Promise; - commit(): Promise; - revert(): Promise; - getStateRoot(): Promise; - setStateRoot(root: Buffer): Promise; - dumpStorage(address: Buffer): Promise; - hasGenesisState(): Promise; - generateCanonicalGenesis(): Promise; - generateGenesis(initState: any): Promise; - accountIsEmpty(address: Buffer): Promise; - cleanupTouchedAccounts(): Promise; - } - - interface StorageDump { - [key: string]: string; - } - - class EVM { - _vm: any; - _state: PStateManager; - _tx: TxContext; - _block: any; - constructor(vm: any, txContext: TxContext, block: any); - executeMessage(message: Message): Promise; - _executeCall(message: Message): Promise; - _executeCreate(message: Message): Promise; - runInterpreter(message: Message, opts: InterpreterOpts): Promise; - getPrecompile(address: Buffer): PrecompileFunc; - runPrecompile(code: PrecompileFunc, data: Buffer, gasLimit: BN): ExecResult; - _loadCode(message: Message): Promise; - _generateAddress(message: Message): Promise; - _reduceSenderBalance(account: Account, message: Message): Promise; - _addToBalance(toAccount: Account, message: Message): Promise; - _touchAccount(address: Buffer): Promise; - } - - class TxContext { - gasPrice: Buffer; - origin: Buffer; - constructor(gasPrice: Buffer, origin: Buffer); - } - - class Message { - to: Buffer; - value: BN; - caller: Buffer; - gasLimit: BN; - data: Buffer; - depth: number; - code: Buffer | PrecompileFunc; - _codeAddress: Buffer; - isStatic: boolean; - isCompiled: boolean; - salt: Buffer; - selfdestruct: any; - delegatecall: boolean; - constructor(opts: any); - codeAddress(): Buffer; - } - - interface InterpreterOpts { - pc?: number; - } - - interface PrecompileFunc { - (opts: PrecompileInput): ExecResult; - } - - interface PrecompileInput { - data: Buffer; - gasLimit: BN; - _common: Common; - } - - class VmError { - error: ERROR; - errorType: string; - constructor(error: ERROR); - } - - enum ERROR { - OUT_OF_GAS = 'out of gas', - STACK_UNDERFLOW = 'stack underflow', - STACK_OVERFLOW = 'stack overflow', - INVALID_JUMP = 'invalid JUMP', - INVALID_OPCODE = 'invalid opcode', - OUT_OF_RANGE = 'value out of range', - REVERT = 'revert', - STATIC_STATE_CHANGE = 'static state change', - INTERNAL_ERROR = 'internal error', - CREATE_COLLISION = 'create collision', - STOP = 'stop', - } -} diff --git a/packages/typescript-typings/types/ganache-core/index.d.ts b/packages/typescript-typings/types/ganache-core/index.d.ts deleted file mode 100644 index 0681ef813a..0000000000 --- a/packages/typescript-typings/types/ganache-core/index.d.ts +++ /dev/null @@ -1,21 +0,0 @@ -declare module 'ganache-core' { - import EthereumTypes = require('ethereum-types'); - export interface GanacheOpts { - verbose?: boolean; - logger?: { - log(msg: string): void; - }; - port?: number; - network_id?: number; - networkId?: number; - mnemonic?: string; - gasLimit?: number; - vmErrorsOnRPCResponse?: boolean; - db_path?: string; - total_accounts?: number; - fork?: string; - blockTime?: number; - unlocked_accounts?: string[]; - } - export function provider(opts: GanacheOpts): EthereumTypes.Provider; -} diff --git a/packages/typescript-typings/types/json-rpc-error/index.d.ts b/packages/typescript-typings/types/json-rpc-error/index.d.ts deleted file mode 100644 index dfaf921675..0000000000 --- a/packages/typescript-typings/types/json-rpc-error/index.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -declare module 'json-rpc-error' { - export class InternalError extends Error { - constructor(err: Error | string); - } - export class MethodNotFound extends Error { - constructor(); - } -} diff --git a/packages/typescript-typings/types/keccak/index.d.ts b/packages/typescript-typings/types/keccak/index.d.ts deleted file mode 100644 index 0465f8faf5..0000000000 --- a/packages/typescript-typings/types/keccak/index.d.ts +++ /dev/null @@ -1 +0,0 @@ -declare module 'keccak'; diff --git a/packages/typescript-typings/types/openapi-schema-validation/index.d.ts b/packages/typescript-typings/types/openapi-schema-validation/index.d.ts deleted file mode 100644 index 123a6bdb76..0000000000 --- a/packages/typescript-typings/types/openapi-schema-validation/index.d.ts +++ /dev/null @@ -1 +0,0 @@ -declare module 'openapi-schema-validation'; diff --git a/packages/typescript-typings/types/promisify-child-process/index.d.ts b/packages/typescript-typings/types/promisify-child-process/index.d.ts deleted file mode 100644 index 55c041735f..0000000000 --- a/packages/typescript-typings/types/promisify-child-process/index.d.ts +++ /dev/null @@ -1 +0,0 @@ -declare module 'promisify-child-process'; diff --git a/packages/typescript-typings/types/publish-release/index.d.ts b/packages/typescript-typings/types/publish-release/index.d.ts deleted file mode 100644 index 680cc45c9a..0000000000 --- a/packages/typescript-typings/types/publish-release/index.d.ts +++ /dev/null @@ -1 +0,0 @@ -declare module 'publish-release'; diff --git a/packages/typescript-typings/types/react-highlight/index.d.ts b/packages/typescript-typings/types/react-highlight/index.d.ts deleted file mode 100644 index 8757215338..0000000000 --- a/packages/typescript-typings/types/react-highlight/index.d.ts +++ /dev/null @@ -1 +0,0 @@ -declare module 'react-highlight'; diff --git a/packages/typescript-typings/types/react-popper/index.d.ts b/packages/typescript-typings/types/react-popper/index.d.ts deleted file mode 100644 index d7dbca17fa..0000000000 --- a/packages/typescript-typings/types/react-popper/index.d.ts +++ /dev/null @@ -1,49 +0,0 @@ -// Type definitions for react-popper 1.0.0-beta.6 -// Project: https://github.com/gilbarbara/react-joyride - -declare module 'react-popper' { - import * as React from 'react'; - import * as PopperJS from 'popper.js'; - - interface ManagerProps { - children: React.ReactNode; - } - export class Manager extends React.Component {} - - type RefHandler = (ref: HTMLElement | null) => void; - - export interface ReferenceChildrenProps { - ref: RefHandler; - } - - export interface ReferenceProps { - children: (props: ReferenceChildrenProps) => React.ReactNode; - } - export class Reference extends React.Component {} - - export interface PopperArrowProps { - ref: RefHandler; - style: React.CSSProperties; - } - - export type Placement = PopperJS.Placement; - - export interface PopperChildrenProps { - arrowProps: PopperArrowProps; - outOfBoundaries: boolean | null; - placement: PopperJS.Placement; - ref: RefHandler; - scheduleUpdate: () => void; - style: React.CSSProperties; - } - - export interface PopperProps { - children: (props: PopperChildrenProps) => React.ReactNode; - eventsEnabled?: boolean; - modifiers?: PopperJS.Modifiers; - placement?: PopperJS.Placement; - positionFixed?: boolean; - referenceElement?: Element; - } - export class Popper extends React.Component {} -} diff --git a/packages/typescript-typings/types/react-tooltip/index.d.ts b/packages/typescript-typings/types/react-tooltip/index.d.ts deleted file mode 100644 index 98cb6d592d..0000000000 --- a/packages/typescript-typings/types/react-tooltip/index.d.ts +++ /dev/null @@ -1 +0,0 @@ -declare module 'react-tooltip'; diff --git a/packages/typescript-typings/types/react-typist/index.d.ts b/packages/typescript-typings/types/react-typist/index.d.ts deleted file mode 100644 index 692c596a57..0000000000 --- a/packages/typescript-typings/types/react-typist/index.d.ts +++ /dev/null @@ -1 +0,0 @@ -declare module 'react-typist'; diff --git a/packages/typescript-typings/types/request-promise-native/index.d.ts b/packages/typescript-typings/types/request-promise-native/index.d.ts deleted file mode 100644 index a86e996246..0000000000 --- a/packages/typescript-typings/types/request-promise-native/index.d.ts +++ /dev/null @@ -1 +0,0 @@ -declare module 'request-promise-native'; diff --git a/packages/typescript-typings/types/rollbar/index.d.ts b/packages/typescript-typings/types/rollbar/index.d.ts deleted file mode 100644 index c9bec447df..0000000000 --- a/packages/typescript-typings/types/rollbar/index.d.ts +++ /dev/null @@ -1 +0,0 @@ -declare module 'rollbar'; diff --git a/packages/typescript-typings/types/semver-diff/index.d.ts b/packages/typescript-typings/types/semver-diff/index.d.ts deleted file mode 100644 index e4a14eeb28..0000000000 --- a/packages/typescript-typings/types/semver-diff/index.d.ts +++ /dev/null @@ -1 +0,0 @@ -declare module 'semver-diff'; diff --git a/packages/typescript-typings/types/semver-sort/index.d.ts b/packages/typescript-typings/types/semver-sort/index.d.ts deleted file mode 100644 index 47310756a7..0000000000 --- a/packages/typescript-typings/types/semver-sort/index.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -declare module 'semver-sort' { - const desc: (versions: string[]) => string[]; -} diff --git a/packages/typescript-typings/types/solc/index.d.ts b/packages/typescript-typings/types/solc/index.d.ts deleted file mode 100644 index 3b993d9e1c..0000000000 --- a/packages/typescript-typings/types/solc/index.d.ts +++ /dev/null @@ -1,115 +0,0 @@ -declare module 'solc' { - export { ErrorType, ErrorSeverity, SolcError, StandardContractOutput, StandardOutput } from 'ethereum-types'; - import { SolcError } from 'ethereum-types'; - export interface ContractCompilationResult { - srcmap: string; - srcmapRuntime: string; - bytecode: string; - runtimeBytecode: string; - interface: string; - } - export interface CompilationResult { - errors: string[]; - contracts: { - [contractIdentifier: string]: ContractCompilationResult; - }; - sources: { - [sourceName: string]: { - AST: any; - }; - }; - sourceList: string[]; - } - export interface ImportContents { - contents: string; - } - export interface InputSources { - sources: { - [fileName: string]: string; - }; - } - export interface BaseSource { - keccak256?: string; - } - export interface InMemorySource extends BaseSource { - content: string; - } - export interface UrlSource extends BaseSource { - urls: string[]; - } - export type Source = UrlSource | InMemorySource; - 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 CompilerSettings { - remappings?: string[]; - optimizer?: { - enabled: boolean; - runs?: number; - details?: { - peephole?: boolean; - jumpdestRemover?: boolean; - orderLiterals?: boolean; - deduplicate?: boolean; - cse?: boolean; - constantOptimizer?: boolean; - yul?: boolean; - }; - }; - evmVersion?: 'homestead' | 'tangerineWhistle' | 'spuriousDragon' | 'byzantium' | 'constantinople'; - metadata?: { - useLiteralContent: true; - }; - libraries?: { - [fileName: string]: { - [libName: string]: string; - }; - }; - outputSelection: { - [fileName: string]: { - [contractName: string]: OutputField[]; - }; - }; - } - export interface StandardInput { - language: 'Solidity' | 'serpent' | 'lll' | 'assembly'; - sources: { - [fileName: string]: Source; - }; - settings: CompilerSettings; - } - export interface SolcInstance { - compile( - sources: InputSources, - optimizerEnabled: number, - findImports: (importPath: string) => ImportContents, - ): CompilationResult; - compileStandardWrapper(input: string, findImports?: (importPath: string) => ImportContents): string; - version(): string; - } - export function loadRemoteVersion( - versionName: string, - cb: (err: SolcError | null, res?: SolcInstance) => void, - ): void; - export function setupMethods(solcBin: any): SolcInstance; -} diff --git a/packages/typescript-typings/types/to-snake-case/index.d.ts b/packages/typescript-typings/types/to-snake-case/index.d.ts deleted file mode 100644 index 39df3f8526..0000000000 --- a/packages/typescript-typings/types/to-snake-case/index.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -declare function toSnakeCase(str: string): string; -declare module 'to-snake-case' { - export = toSnakeCase; -} diff --git a/packages/typescript-typings/types/truffle-hdwalet-provider/index.d.ts b/packages/typescript-typings/types/truffle-hdwalet-provider/index.d.ts deleted file mode 100644 index 007df61e0e..0000000000 --- a/packages/typescript-typings/types/truffle-hdwalet-provider/index.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -declare module 'truffle-hdwallet-provider' { - import { JSONRPCRequestPayload, JSONRPCResponsePayload, Provider } from 'ethereum-types'; - class HDWalletProvider implements Provider { - constructor(mnemonic: string, rpcUrl: string); - public sendAsync( - payload: JSONRPCRequestPayload, - callback: (err: Error, result: JSONRPCResponsePayload) => void, - ): void; - } - export = HDWalletProvider; -} diff --git a/packages/typescript-typings/types/web3-eth-abi/index.d.ts b/packages/typescript-typings/types/web3-eth-abi/index.d.ts deleted file mode 100644 index 5d2f46e043..0000000000 --- a/packages/typescript-typings/types/web3-eth-abi/index.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -declare module 'web3-eth-abi' { - export function encodeParameters(typesArray: string[], parameters: any[]): string; -} diff --git a/packages/typescript-typings/types/web3/index.d.ts b/packages/typescript-typings/types/web3/index.d.ts deleted file mode 100644 index 4085c71a77..0000000000 --- a/packages/typescript-typings/types/web3/index.d.ts +++ /dev/null @@ -1,231 +0,0 @@ -declare module 'web3' { - import * as BigNumber from 'bignumber.js'; - import { - AbiDefinition, - BlockWithTransactionData, - BlockWithoutTransactionData, - BlockParam, - CallData, - Provider, - Unit, - TxData, - Transaction, - ContractAbi, - TransactionReceipt, - FilterObject, - LogEntryEvent, - JSONRPCRequestPayload, - JSONRPCResponsePayload, - } from 'ethereum-types'; - - type MixedData = string | number | object | any[] | BigNumber.BigNumber; - - class Web3 { - public static providers: typeof providers; - public currentProvider: Provider; - - public eth: Web3.EthApi; - public personal: Web3.PersonalApi | undefined; - public version: Web3.VersionApi; - public net: Web3.NetApi; - - public constructor(provider?: Provider); - - public isConnected(): boolean; - public setProvider(provider: Provider): void; - public reset(keepIsSyncing: boolean): void; - public toHex(data: MixedData): string; - public toAscii(hex: string): string; - public fromAscii(ascii: string, padding?: number): string; - public toDecimal(hex: string): number; - public fromDecimal(value: number | string): string; - public fromWei(value: number | string, unit: Unit): string; - public fromWei(value: BigNumber.BigNumber, unit: Unit): BigNumber.BigNumber; - public toWei(amount: number | string, unit: Unit): string; - public toWei(amount: BigNumber.BigNumber, unit: Unit): BigNumber.BigNumber; - public toBigNumber(value: number | string): BigNumber.BigNumber; - public isAddress(address: string): boolean; - public isChecksumAddress(address: string): boolean; - public sha3(value: string, options?: Web3.Sha3Options): string; - } - - namespace providers { - class HttpProvider implements Provider { - constructor(url?: string, timeout?: number, username?: string, password?: string); - public sendAsync( - payload: JSONRPCRequestPayload, - callback: (err: Error, result: JSONRPCResponsePayload) => void, - ): void; - } - } - - namespace Web3 { - interface ContractInstance { - address: string; - abi: ContractAbi; - [name: string]: any; - } - - interface Contract
{ - at(address: string): A; - getData(...args: any[]): string; - 'new'(...args: any[]): A; - } - - interface FilterResult { - get(callback: () => void): void; - watch(callback: (err: Error, result: LogEntryEvent) => void): void; - stopWatching(callback?: () => void): void; - } - - interface Sha3Options { - encoding: 'hex'; - } - - interface EthApi { - coinbase: string; - mining: boolean; - hashrate: number; - gasPrice: BigNumber.BigNumber; - accounts: string[]; - blockNumber: number; - defaultAccount?: string; - defaultBlock: BlockParam; - syncing: Web3.SyncingResult; - compile: { - solidity(sourceString: string, cb?: (err: Error, result: any) => void): object; - }; - getMining(cd: (err: Error, mining: boolean) => void): void; - getHashrate(cd: (err: Error, hashrate: number) => void): void; - getGasPrice(cd: (err: Error, gasPrice: BigNumber.BigNumber) => void): void; - getAccounts(cd: (err: Error, accounts: string[]) => void): void; - getBlockNumber(callback: (err: Error, blockNumber: number) => void): void; - getSyncing(cd: (err: Error, syncing: Web3.SyncingResult) => void): void; - isSyncing(cb: (err: Error, isSyncing: boolean, syncingState: Web3.SyncingState) => void): Web3.IsSyncing; - - getBlock(hashStringOrBlockNumber: string | BlockParam): BlockWithoutTransactionData; - getBlock( - hashStringOrBlockNumber: string | BlockParam, - callback: (err: Error, blockObj: BlockWithoutTransactionData) => void, - ): void; - getBlock( - hashStringOrBlockNumber: string | BlockParam, - returnTransactionObjects: true, - ): BlockWithTransactionData; - getBlock( - hashStringOrBlockNumber: string | BlockParam, - returnTransactionObjects: true, - callback: (err: Error, blockObj: BlockWithTransactionData) => void, - ): void; - - getBlockTransactionCount(hashStringOrBlockNumber: string | BlockParam): number; - getBlockTransactionCount( - hashStringOrBlockNumber: string | BlockParam, - callback: (err: Error, blockTransactionCount: number) => void, - ): void; - - // TODO returnTransactionObjects - getUncle(hashStringOrBlockNumber: string | BlockParam, uncleNumber: number): BlockWithoutTransactionData; - getUncle( - hashStringOrBlockNumber: string | BlockParam, - uncleNumber: number, - callback: (err: Error, uncle: BlockWithoutTransactionData) => void, - ): void; - - getTransaction(transactionHash: string): Transaction; - getTransaction(transactionHash: string, callback: (err: Error, transaction: Transaction) => void): void; - - getTransactionFromBlock(hashStringOrBlockNumber: string | BlockParam, indexNumber: number): Transaction; - getTransactionFromBlock( - hashStringOrBlockNumber: string | BlockParam, - indexNumber: number, - callback: (err: Error, transaction: Transaction) => void, - ): void; - - contract(abi: AbiDefinition[]): Web3.Contract; - - // TODO block param - getBalance(addressHexString: string): BigNumber.BigNumber; - getBalance(addressHexString: string, callback: (err: Error, result: BigNumber.BigNumber) => void): void; - - // TODO block param - getStorageAt(address: string, position: number): string; - getStorageAt(address: string, position: number, callback: (err: Error, storage: string) => void): void; - - // TODO block param - getCode(addressHexString: string): string; - getCode(addressHexString: string, callback: (err: Error, code: string) => void): void; - - filter(value: string | FilterObject): Web3.FilterResult; - - sendTransaction(txData: TxData): string; - sendTransaction(txData: TxData, callback: (err: Error, value: string) => void): void; - - sendRawTransaction(rawTxData: string): string; - sendRawTransaction(rawTxData: string, callback: (err: Error, value: string) => void): void; - - sign(address: string, data: string): string; - sign(address: string, data: string, callback: (err: Error, signature: string) => void): void; - - getTransactionReceipt(txHash: string): TransactionReceipt | null; - getTransactionReceipt( - txHash: string, - callback: (err: Error, receipt: TransactionReceipt | null) => void, - ): void; - - // TODO block param - call(callData: CallData): string; - call(callData: CallData, callback: (err: Error, result: string) => void): void; - - estimateGas(callData: CallData): number; - estimateGas(callData: CallData, callback: (err: Error, gas: number) => void): void; - - // TODO defaultBlock - getTransactionCount(address: string): number; - getTransactionCount(address: string, callback: (err: Error, count: number) => void): void; - } - - interface VersionApi { - api: string; - network: string; - node: string; - ethereum: string; - whisper: string; - getNetwork(cd: (err: Error, networkId: string) => void): void; - getNode(cd: (err: Error, nodeVersion: string) => void): void; - getEthereum(cd: (err: Error, ethereum: string) => void): void; - getWhisper(cd: (err: Error, whisper: string) => void): void; - } - - interface PersonalApi { - listAccounts: string[] | undefined; - newAccount(password?: string): string; - unlockAccount(address: string, password?: string, duration?: number): boolean; - lockAccount(address: string): boolean; - sign(message: string, account: string, password: string): string; - sign(hexMessage: string, account: string, callback: (error: Error, signature: string) => void): void; - } - - interface NetApi { - listening: boolean; - peerCount: number; - getListening(cd: (err: Error, listening: boolean) => void): void; - getPeerCount(cd: (err: Error, peerCount: number) => void): void; - } - - interface SyncingState { - startingBlock: number; - currentBlock: number; - highestBlock: number; - } - type SyncingResult = false | SyncingState; - - interface IsSyncing { - addCallback(cb: (err: Error, isSyncing: boolean, syncingState: SyncingState) => void): void; - stopWatching(): void; - } - } - /* tslint:disable */ - export = Web3; - /* tslint:enable */ -} diff --git a/packages/utils/.npmignore b/packages/utils/.npmignore deleted file mode 100644 index ea588d4859..0000000000 --- a/packages/utils/.npmignore +++ /dev/null @@ -1,9 +0,0 @@ -# Blacklist all files -.* -* -# Whitelist lib -!lib/**/* -# Blacklist tests and publish scripts -/lib/test/* -/lib/monorepo_scripts/ -# Package specific ignore diff --git a/packages/utils/CHANGELOG.json b/packages/utils/CHANGELOG.json deleted file mode 100644 index 945fd294fa..0000000000 --- a/packages/utils/CHANGELOG.json +++ /dev/null @@ -1,913 +0,0 @@ -[ - { - "version": "5.6.0", - "changes": [ - { - "note": "Added support for nested rich revert decoding", - "pr": 2668 - }, - { - "note": "Add EP flavor of `IllegalReentrancyError`.", - "pr": 2657 - }, - { - "note": "Added LiquidityProviderFeature errors", - "pr": 2691 - }, - { - "note": "Added abi encoder support for uint80 lol", - "pr": 2728 - } - ] - }, - { - "timestamp": 1594788383, - "version": "5.5.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "5.5.0", - "changes": [ - { - "note": "Add `ZeroExRevertErrors`", - "pr": 2540 - }, - { - "note": "Print full revert error in stack traces.", - "pr": 2540 - }, - { - "note": "`ZeroExRevertErrors.Migrate` -> `ZeroExRevertErrors.Ownable`", - "pr": 2564 - }, - { - "note": "`instanceof Array` => `Array.isArray`", - "pr": 2567 - }, - { - "note": "Add more `ZeroExRevertErrors`", - "pr": 2545 - }, - { - "note": "Add more `ZeroExRevertErrors`", - "pr": 2576 - }, - { - "note": "Update `ZeroExRevertErrors`", - "pr": 2597 - }, - { - "note": "Add more revert errors to `ZeroExRevertErrors`", - "pr": 2610 - } - ], - "timestamp": 1592969527 - }, - { - "version": "5.4.1", - "changes": [ - { - "note": "Fix extra space in `provider.send` signature", - "pr": 2428 - } - ], - "timestamp": 1582623685 - }, - { - "version": "5.4.0", - "changes": [ - { - "note": "Add `toTokenUnitAmount` and `fromTokenUnitAmount`", - "pr": 2462 - }, - { - "note": "Add `hexUtils.isHex`", - "pr": 2462 - }, - { - "note": "Accept `Buffer` type in `hexUtils.toHex()`", - "pr": 2462 - } - ], - "timestamp": 1581204851 - }, - { - "version": "5.3.0", - "changes": [ - { - "note": "Added Broker, MixinWethUtils revert errors", - "pr": 2455 - }, - { - "note": "Moved LibAssetDataTransfer revert errors into their own file", - "pr": 2455 - } - ], - "timestamp": 1580988106 - }, - { - "version": "5.2.0", - "changes": [ - { - "note": "Allow for strict decoding of return values.", - "pr": 2433 - } - ], - "timestamp": 1579682890 - }, - { - "timestamp": 1578272714, - "version": "5.1.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1576540892, - "version": "5.1.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "5.1.0", - "changes": [ - { - "note": "Added hex_utils", - "pr": 2373 - } - ], - "timestamp": 1575931811 - }, - { - "version": "5.0.0", - "changes": [ - { - "note": "Re-export all `RevertErrors`", - "pr": 2362 - }, - { - "note": "Removed exports AuthorizableRevertErrors, LibAddressArrayRevertErrors, LibBytesRevertErrors, OwnableRevertErrors, ReentrancyGuardRevertErrors and SafeMathRevertErrors", - "pr": 2321 - }, - { - "note": "Decode `Parity` revert errors", - "pr": 2341 - }, - { - "note": "Update BigNumber version to ~9.0.0", - "pr": 2342 - }, - { - "note": "Consolidated FixedMathRevertErrors", - "pr": 2255 - }, - { - "note": "Changed provider_utils.providerUtils.getChainIdAsync() to invoke RPC method eth_chainId rather than net_version", - "pr": 2270 - }, - { - "note": "Allow for array types in `RevertError`s.", - "pr": 2075 - }, - { - "note": "Have Ganache `Error` -> `RevertError` coercion fail if it can't look up the selector.", - "pr": 2109 - }, - { - "note": "Add `LibFixedMath` `RevertError` types.", - "pr": 2109 - }, - { - "note": "Add `RawRevertError` `RevertError` type.", - "pr": 2109 - }, - { - "note": "Make `RevertError.decode()` optionally return a `RawRevertError` if the selector is unknown.", - "pr": 2109 - }, - { - "note": "Rename `length` field of `AuthorizableRevertErrors.IndexOutOfBoundsError` type to `len`.", - "pr": 2109 - } - ], - "timestamp": 1575296764 - }, - { - "version": "4.6.0-beta.3", - "changes": [ - { - "note": "Re-export all `RevertErrors`", - "pr": 2362 - } - ], - "timestamp": 1575290197 - }, - { - "version": "4.6.0-beta.2", - "changes": [ - { - "note": "Removed exports AuthorizableRevertErrors, LibAddressArrayRevertErrors, LibBytesRevertErrors, OwnableRevertErrors, ReentrancyGuardRevertErrors and SafeMathRevertErrors", - "pr": 2321 - }, - { - "note": "Decode `Parity` revert errors", - "pr": 2341 - }, - { - "note": "Update BigNumber version to ~9.0.0", - "pr": 2342 - } - ], - "timestamp": 1574030254 - }, - { - "version": "4.6.0-beta.1", - "changes": [ - { - "note": "Consolidated FixedMathRevertErrors", - "pr": 2255 - }, - { - "note": "Changed provider_utils.providerUtils.getChainIdAsync() to invoke RPC method eth_chainId rather than net_version", - "pr": 2270 - } - ], - "timestamp": 1573159180 - }, - { - "version": "4.6.0-beta.0", - "changes": [ - { - "note": "Allow for array types in `RevertError`s.", - "pr": 2075 - }, - { - "note": "Have Ganache `Error` -> `RevertError` coercion fail if it can't look up the selector.", - "pr": 2109 - }, - { - "note": "Add `LibFixedMath` `RevertError` types.", - "pr": 2109 - }, - { - "note": "Add `RawRevertError` `RevertError` type.", - "pr": 2109 - }, - { - "note": "Make `RevertError.decode()` optionally return a `RawRevertError` if the selector is unknown.", - "pr": 2109 - }, - { - "note": "Rename `length` field of `AuthorizableRevertErrors.IndexOutOfBoundsError` type to `len`.", - "pr": 2109 - } - ], - "timestamp": 1570135330 - }, - { - "timestamp": 1568744790, - "version": "4.5.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1567521715, - "version": "4.5.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "4.5.0", - "changes": [ - { - "note": "Add `SafeMathRevertErrors.SafeMathErrorCodes.Uint256DivisionByZero`", - "pr": 2031 - }, - { - "note": "Updated to include `strictDecode` for decoding method arguments", - "pr": 2018 - }, - { - "note": "Throw exception when trying to decode beyond boundaries of calldata", - "pr": 2018 - } - ], - "timestamp": 1565296576 - }, - { - "timestamp": 1564604963, - "version": "4.4.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1563957393, - "version": "4.4.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "4.4.0", - "changes": [ - { - "note": "Add function deleteNestedProperty", - "pr": 1842 - }, - { - "note": "Add `getChainIdAsync()` to `providerUtils`", - "pr": 1742 - }, - { - "note": "More robust normalization of `uint256` types in `sign_typed_data_utils`", - "pr": 1742 - }, - { - "note": "Add `RevertError`, `StringRevertError`, `AnyRevertError` types and associated utilities", - "pr": 1761 - }, - { - "note": "Update `RevertError` construction to produce a readable `Error` message", - "pr": 1819 - }, - { - "note": "Add `Error` -> `RevertError` functions", - "pr": 1819 - }, - { - "note": "Add `toStringTag` symbol to `RevertError`", - "pr": 1885 - } - ], - "timestamp": 1563006338 - }, - { - "version": "4.3.3", - "changes": [ - { - "note": "Fixed spelling error in ABI Encoder error message", - "pr": 1808 - } - ], - "timestamp": 1557507213 - }, - { - "version": "4.3.2", - "changes": [ - { - "note": "Support for ABI encoding multibyte strings (fixes issue #1723)", - "pr": 1806 - } - ] - }, - { - "version": "4.3.1", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1554997931 - }, - { - "version": "4.3.0", - "changes": [ - { - "note": "Added `startProviderEngine` to `providerUtils`. Preventing excess block polling", - "pr": 1695 - } - ], - "timestamp": 1553183790 - }, - { - "timestamp": 1553091633, - "version": "4.2.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "4.2.2", - "changes": [ - { - "note": "Fix issue where process is not defined in browser context", - "pr": 1660 - } - ], - "timestamp": 1551479279 - }, - { - "timestamp": 1551220833, - "version": "4.2.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "4.2.0", - "changes": [ - { - "note": "Export providerUtils which helps standardize all supported provider interfaces into the ZeroExProvider interface", - "pr": 1627 - }, - { - "note": "Add `logUtils.table` and `logUtils.header`", - "pr": 1638 - } - ], - "timestamp": 1551130135 - }, - { - "version": "4.1.0", - "changes": [ - { - "note": "Added method decoding to AbiDecoder", - "pr": 1569 - } - ], - "timestamp": 1549733923 - }, - { - "version": "4.0.4", - "changes": [ - { - "note": "Cleaner signature parsing", - "pr": 1592 - } - ] - }, - { - "version": "4.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1549547375 - }, - { - "version": "4.0.2", - "changes": [ - { - "note": "ABI Decode NULL for all data types", - "pr": 1587 - } - ], - "timestamp": 1549452781 - }, - { - "version": "4.0.1", - "changes": [ - { - "note": "ABI Decode NULL as False", - "pr": 1582 - } - ], - "timestamp": 1549373905 - }, - { - "version": "4.0.0", - "changes": [ - { - "note": "Upgrade the bignumber.js to v8.0.2", - "pr": 1517 - } - ] - }, - { - "timestamp": 1547561734, - "version": "3.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.0.0", - "changes": [ - { - "note": "Make `promisify` resolve when the callback error is undefined.", - "pr": 1501 - } - ], - "timestamp": 1547225310 - }, - { - "version": "2.1.1", - "changes": [ - { - "note": "Add `should` prefix to names of properties in EncodingRules and DecodingRules", - "pr": 1363 - } - ], - "timestamp": 1547040760 - }, - { - "version": "2.1.0", - "changes": [ - { - "note": "Add `logWithTime` to `logUtils`", - "pr": 1461 - } - ] - }, - { - "version": "2.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544739608 - }, - { - "version": "2.0.7", - "changes": [ - { - "note": "Optimized ABI Encoder/Decoder. Generates compressed calldata to save gas. Generates human-readable calldata to aid development." - } - ], - "timestamp": 1544570656 - }, - { - "timestamp": 1542821676, - "version": "2.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542208198, - "version": "2.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1541740904 - }, - { - "timestamp": 1539871071, - "version": "2.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1538693146, - "version": "2.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1538475601, - "version": "2.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.0", - "changes": [ - { - "note": "Make abi_decoder compatible with ethers ^4.0.0", - "pr": 1069 - } - ], - "timestamp": 1538157789 - }, - { - "timestamp": 1537907159, - "version": "1.0.11", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537875740, - "version": "1.0.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537541580, - "version": "1.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1536142250, - "version": "1.0.8", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1535377027, - "version": "1.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1535133899, - "version": "1.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.5", - "changes": [ - { - "note": "Increased BigNumber decimal precision from 20 to 78", - "pr": 807 - }, - { - "note": "Store different ABIs for events with same function signature and different amount of indexed arguments", - "pr": 933 - } - ], - "timestamp": 1534210131 - }, - { - "timestamp": 1532619515, - "version": "1.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532614997, - "version": "1.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532605697, - "version": "1.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.0.1", - "changes": [ - { - "note": "Add `AbortController` polyfill to `fetchAsync`", - "pr": 903 - } - ], - "timestamp": 1532357734 - }, - { - "timestamp": 1532043000, - "version": "1.0.0", - "changes": [ - { - "note": "Add `fetchAsync` which adds a default timeout to all requests", - "pr": 874 - } - ] - }, - { - "timestamp": 1531919263, - "version": "0.7.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.7.2", - "changes": [ - { - "note": "Added errorUtils.spawnSwitchErr" - }, - { - "note": "Add logUtils.warn", - "pr": 589 - }, - { - "note": "Fixes uncaught Error in abi_decoder", - "pr": 763 - } - ], - "timestamp": 1531149657 - }, - { - "timestamp": 1529397769, - "version": "0.7.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.7.0", - "changes": [ - { - "note": "Incorrect publish that was unpublished" - } - ], - "timestamp": 1527810075 - }, - { - "timestamp": 1527009133, - "version": "0.6.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1525477860, - "version": "0.6.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.6.0", - "changes": [ - { - "note": "Update ethers-contracts to ethers.js", - "pr": 540 - } - ], - "timestamp": 1525428773 - }, - { - "version": "0.5.2", - "changes": [ - { - "note": "Export NULL_BYTES constant", - "pr": 500 - } - ], - "timestamp": 1524044013 - }, - { - "timestamp": 1523462196, - "version": "0.5.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.5.0", - "changes": [ - { - "note": "Make `AbiDecoder.addABI` public", - "pr": 485 - } - ], - "timestamp": 1522673609 - }, - { - "timestamp": 1522658513, - "version": "0.4.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.4.3", - "changes": [ - { - "note": "Add `@types/node` to dependencies since `intervalUtils` has the `NodeJS` type as part of its public interface." - } - ], - "timestamp": 1521298800 - }, - { - "version": "0.4.2", - "changes": [ - { - "note": "Consolidate all `console.log` calls into `logUtils` in the `@0xproject/utils` package", - "pr": 452 - } - ], - "timestamp": 1521298800 - }, - { - "version": "0.4.0", - "changes": [ - { - "note": "Use `ethers-contracts` as a backend to decode event args", - "pr": 413 - }, - { - "note": "Move web3 types from devDep to dep since required when using this package", - "pr": 429 - } - ], - "timestamp": 1520089200 - }, - { - "version": "0.3.2", - "changes": [ - { - "note": "Fix publishing issue where .npmignore was not properly excluding undesired content", - "pr": 389 - } - ], - "timestamp": 1518102000 - }, - { - "version": "0.3.0", - "changes": [ - { - "note": "Fix a bug related to event signature collisions (argument indexes aren't included in event signatures) in the abi_decoder. The decoder used to throw on unknown events with identical signatures as a known event (except indexes).", - "pr": 366 - } - ], - "timestamp": 1517756400 - }, - { - "version": "0.2.0", - "changes": [ - { - "note": "Add `onError` parameter to `intervalUtils.setAsyncExcludingInterval`", - "pr": 312 - }, - { - "note": "Add `intervalUtils.setInterval`", - "pr": 312 - } - ], - "timestamp": 1516114800 - } -] diff --git a/packages/utils/CHANGELOG.md b/packages/utils/CHANGELOG.md deleted file mode 100644 index ac6fdf8989..0000000000 --- a/packages/utils/CHANGELOG.md +++ /dev/null @@ -1,353 +0,0 @@ - - -CHANGELOG - -## v5.5.1 - _July 15, 2020_ - - * Dependencies updated - -## v5.5.0 - _June 24, 2020_ - - * Add `ZeroExRevertErrors` (#2540) - * Print full revert error in stack traces. (#2540) - * `ZeroExRevertErrors.Migrate` -> `ZeroExRevertErrors.Ownable` (#2564) - * `instanceof Array` => `Array.isArray` (#2567) - * Add more `ZeroExRevertErrors` (#2545) - * Add more `ZeroExRevertErrors` (#2576) - * Update `ZeroExRevertErrors` (#2597) - * Add more revert errors to `ZeroExRevertErrors` (#2610) - -## v5.4.1 - _February 25, 2020_ - - * Fix extra space in `provider.send` signature (#2428) - -## v5.4.0 - _February 8, 2020_ - - * Add `toTokenUnitAmount` and `fromTokenUnitAmount` (#2462) - * Add `hexUtils.isHex` (#2462) - * Accept `Buffer` type in `hexUtils.toHex()` (#2462) - -## v5.3.0 - _February 6, 2020_ - - * Added Broker, MixinWethUtils revert errors (#2455) - * Moved LibAssetDataTransfer revert errors into their own file (#2455) - -## v5.2.0 - _January 22, 2020_ - - * Allow for strict decoding of return values. (#2433) - -## v5.1.2 - _January 6, 2020_ - - * Dependencies updated - -## v5.1.1 - _December 17, 2019_ - - * Dependencies updated - -## v5.1.0 - _December 9, 2019_ - - * Added hex_utils (#2373) - -## v5.0.0 - _December 2, 2019_ - - * Re-export all `RevertErrors` (#2362) - * Removed exports AuthorizableRevertErrors, LibAddressArrayRevertErrors, LibBytesRevertErrors, OwnableRevertErrors, ReentrancyGuardRevertErrors and SafeMathRevertErrors (#2321) - * Decode `Parity` revert errors (#2341) - * Update BigNumber version to ~9.0.0 (#2342) - * Consolidated FixedMathRevertErrors (#2255) - * Changed provider_utils.providerUtils.getChainIdAsync() to invoke RPC method eth_chainId rather than net_version (#2270) - * Allow for array types in `RevertError`s. (#2075) - * Have Ganache `Error` -> `RevertError` coercion fail if it can't look up the selector. (#2109) - * Add `LibFixedMath` `RevertError` types. (#2109) - * Add `RawRevertError` `RevertError` type. (#2109) - * Make `RevertError.decode()` optionally return a `RawRevertError` if the selector is unknown. (#2109) - * Rename `length` field of `AuthorizableRevertErrors.IndexOutOfBoundsError` type to `len`. (#2109) - -## v4.6.0-beta.3 - _December 2, 2019_ - - * Re-export all `RevertErrors` (#2362) - -## v4.6.0-beta.2 - _November 17, 2019_ - - * Removed exports AuthorizableRevertErrors, LibAddressArrayRevertErrors, LibBytesRevertErrors, OwnableRevertErrors, ReentrancyGuardRevertErrors and SafeMathRevertErrors (#2321) - * Decode `Parity` revert errors (#2341) - * Update BigNumber version to ~9.0.0 (#2342) - -## v4.6.0-beta.1 - _November 7, 2019_ - - * Consolidated FixedMathRevertErrors (#2255) - * Changed provider_utils.providerUtils.getChainIdAsync() to invoke RPC method eth_chainId rather than net_version (#2270) - -## v4.6.0-beta.0 - _October 3, 2019_ - - * Allow for array types in `RevertError`s. (#2075) - * Have Ganache `Error` -> `RevertError` coercion fail if it can't look up the selector. (#2109) - * Add `LibFixedMath` `RevertError` types. (#2109) - * Add `RawRevertError` `RevertError` type. (#2109) - * Make `RevertError.decode()` optionally return a `RawRevertError` if the selector is unknown. (#2109) - * Rename `length` field of `AuthorizableRevertErrors.IndexOutOfBoundsError` type to `len`. (#2109) - -## v4.5.2 - _September 17, 2019_ - - * Dependencies updated - -## v4.5.1 - _September 3, 2019_ - - * Dependencies updated - -## v4.5.0 - _August 8, 2019_ - - * Add `SafeMathRevertErrors.SafeMathErrorCodes.Uint256DivisionByZero` (#2031) - * Updated to include `strictDecode` for decoding method arguments (#2018) - * Throw exception when trying to decode beyond boundaries of calldata (#2018) - -## v4.4.2 - _July 31, 2019_ - - * Dependencies updated - -## v4.4.1 - _July 24, 2019_ - - * Dependencies updated - -## v4.4.0 - _July 13, 2019_ - - * Add function deleteNestedProperty (#1842) - * Add `getChainIdAsync()` to `providerUtils` (#1742) - * More robust normalization of `uint256` types in `sign_typed_data_utils` (#1742) - * Add `RevertError`, `StringRevertError`, `AnyRevertError` types and associated utilities (#1761) - * Update `RevertError` construction to produce a readable `Error` message (#1819) - * Add `Error` -> `RevertError` functions (#1819) - * Add `toStringTag` symbol to `RevertError` (#1885) - -## v4.3.3 - _May 10, 2019_ - - * Fixed spelling error in ABI Encoder error message (#1808) - -## v4.3.2 - _Invalid date_ - - * Support for ABI encoding multibyte strings (fixes issue #1723) (#1806) - -## v4.3.1 - _April 11, 2019_ - - * Dependencies updated - -## v4.3.0 - _March 21, 2019_ - - * Added `startProviderEngine` to `providerUtils`. Preventing excess block polling (#1695) - -## v4.2.3 - _March 20, 2019_ - - * Dependencies updated - -## v4.2.2 - _March 1, 2019_ - - * Fix issue where process is not defined in browser context (#1660) - -## v4.2.1 - _February 26, 2019_ - - * Dependencies updated - -## v4.2.0 - _February 25, 2019_ - - * Export providerUtils which helps standardize all supported provider interfaces into the ZeroExProvider interface (#1627) - * Add `logUtils.table` and `logUtils.header` (#1638) - -## v4.1.0 - _February 9, 2019_ - - * Added method decoding to AbiDecoder (#1569) - -## v4.0.4 - _Invalid date_ - - * Cleaner signature parsing (#1592) - -## v4.0.3 - _February 7, 2019_ - - * Dependencies updated - -## v4.0.2 - _February 6, 2019_ - - * ABI Decode NULL for all data types (#1587) - -## v4.0.1 - _February 5, 2019_ - - * ABI Decode NULL as False (#1582) - -## v4.0.0 - _Invalid date_ - - * Upgrade the bignumber.js to v8.0.2 (#1517) - -## v3.0.1 - _January 15, 2019_ - - * Dependencies updated - -## v3.0.0 - _January 11, 2019_ - - * Make `promisify` resolve when the callback error is undefined. (#1501) - -## v2.1.1 - _January 9, 2019_ - - * Add `should` prefix to names of properties in EncodingRules and DecodingRules (#1363) - -## v2.1.0 - _Invalid date_ - - * Add `logWithTime` to `logUtils` (#1461) - -## v2.0.8 - _December 13, 2018_ - - * Dependencies updated - -## v2.0.7 - _December 11, 2018_ - - * Optimized ABI Encoder/Decoder. Generates compressed calldata to save gas. Generates human-readable calldata to aid development. - -## v2.0.6 - _November 21, 2018_ - - * Dependencies updated - -## v2.0.5 - _November 14, 2018_ - - * Dependencies updated - -## v2.0.4 - _November 9, 2018_ - - * Dependencies updated - -## v2.0.3 - _October 18, 2018_ - - * Dependencies updated - -## v2.0.2 - _October 4, 2018_ - - * Dependencies updated - -## v2.0.1 - _October 2, 2018_ - - * Dependencies updated - -## v2.0.0 - _September 28, 2018_ - - * Make abi_decoder compatible with ethers ^4.0.0 (#1069) - -## v1.0.11 - _September 25, 2018_ - - * Dependencies updated - -## v1.0.10 - _September 25, 2018_ - - * Dependencies updated - -## v1.0.9 - _September 21, 2018_ - - * Dependencies updated - -## v1.0.8 - _September 5, 2018_ - - * Dependencies updated - -## v1.0.7 - _August 27, 2018_ - - * Dependencies updated - -## v1.0.6 - _August 24, 2018_ - - * Dependencies updated - -## v1.0.5 - _August 14, 2018_ - - * Increased BigNumber decimal precision from 20 to 78 (#807) - * Store different ABIs for events with same function signature and different amount of indexed arguments (#933) - -## v1.0.4 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.3 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.2 - _July 26, 2018_ - - * Dependencies updated - -## v1.0.1 - _July 23, 2018_ - - * Add `AbortController` polyfill to `fetchAsync` (#903) - -## v1.0.0 - _July 19, 2018_ - - * Add `fetchAsync` which adds a default timeout to all requests (#874) - -## v0.7.3 - _July 18, 2018_ - - * Dependencies updated - -## v0.7.2 - _July 9, 2018_ - - * Added errorUtils.spawnSwitchErr - * Add logUtils.warn (#589) - * Fixes uncaught Error in abi_decoder (#763) - -## v0.7.1 - _June 19, 2018_ - - * Dependencies updated - -## v0.7.0 - _May 31, 2018_ - - * Incorrect publish that was unpublished - -## v0.6.2 - _May 22, 2018_ - - * Dependencies updated - -## v0.6.1 - _May 4, 2018_ - - * Dependencies updated - -## v0.6.0 - _May 4, 2018_ - - * Update ethers-contracts to ethers.js (#540) - -## v0.5.2 - _April 18, 2018_ - - * Export NULL_BYTES constant (#500) - -## v0.5.1 - _April 11, 2018_ - - * Dependencies updated - -## v0.5.0 - _April 2, 2018_ - - * Make `AbiDecoder.addABI` public (#485) - -## v0.4.4 - _April 2, 2018_ - - * Dependencies updated - -## v0.4.3 - _March 17, 2018_ - - * Add `@types/node` to dependencies since `intervalUtils` has the `NodeJS` type as part of its public interface. - -## v0.4.2 - _March 17, 2018_ - - * Consolidate all `console.log` calls into `logUtils` in the `@0xproject/utils` package (#452) - -## v0.4.0 - _March 3, 2018_ - - * Use `ethers-contracts` as a backend to decode event args (#413) - * Move web3 types from devDep to dep since required when using this package (#429) - -## v0.3.2 - _February 8, 2018_ - - * Fix publishing issue where .npmignore was not properly excluding undesired content (#389) - -## v0.3.0 - _February 4, 2018_ - - * Fix a bug related to event signature collisions (argument indexes aren't included in event signatures) in the abi_decoder. The decoder used to throw on unknown events with identical signatures as a known event (except indexes). (#366) - -## v0.2.0 - _January 16, 2018_ - - * Add `onError` parameter to `intervalUtils.setAsyncExcludingInterval` (#312) - * Add `intervalUtils.setInterval` (#312) diff --git a/packages/utils/README.md b/packages/utils/README.md deleted file mode 100644 index 0b15f00c52..0000000000 --- a/packages/utils/README.md +++ /dev/null @@ -1,84 +0,0 @@ -## @0x/utils - -Utils to be shared across 0x projects and packages - -## Installation - -```bash -yarn add @0x/utils -``` - -If your project is in [TypeScript](https://www.typescriptlang.org/), add the following to your `tsconfig.json`: - -```json -"compilerOptions": { - "typeRoots": ["node_modules/@0x/typescript-typings/types", "node_modules/@types"], -} -``` - -## Usage - -```javascript -import { addressUtils, bigNumberConfigs, classUtils, intervalUtils, promisify } from '@0x/utils'; -``` - -## Troubleshooting - -If you are still seeing TS type errors complaining about missing DOM types such as `Response`: - -``` -error TS2304: Cannot find name 'Response'. -``` - -Then you need to explicitly add the `dom` lib to your compiler options in `tsconfig.json`. The `dom` library is included by default, but customizing the `lib` option can cause it to be dropped. - -``` -"compilerOptions": { - "lib": [..., "dom"], -``` - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install dependencies - -If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: - -```bash -yarn config set workspaces-experimental true -``` - -Then install dependencies - -```bash -yarn install -``` - -### Build - -To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory: - -```bash -PKG=@0x/utils yarn build -``` - -Or continuously rebuild on change: - -```bash -PKG=@0x/utils yarn watch -``` - -### Clean - -```bash -yarn clean -``` - -### Lint - -```bash -yarn lint -``` diff --git a/packages/utils/coverage/.gitkeep b/packages/utils/coverage/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/utils/package.json b/packages/utils/package.json deleted file mode 100644 index ffbd8d7327..0000000000 --- a/packages/utils/package.json +++ /dev/null @@ -1,66 +0,0 @@ -{ - "name": "@0x/utils", - "version": "5.5.1", - "engines": { - "node": ">=6.12" - }, - "description": "0x TS utils", - "main": "lib/src/index.js", - "types": "lib/src/index.d.ts", - "scripts": { - "build": "tsc -b", - "build:ci": "yarn build", - "clean": "shx rm -rf lib", - "lint": "tslint --format stylish --project .", - "fix": "tslint --fix --format stylish --project .", - "test": "yarn run_mocha", - "test:circleci": "yarn test:coverage", - "run_mocha": "mocha --require source-map-support/register --require make-promises-safe 'lib/test/**/*_test.js' '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" - }, - "license": "Apache-2.0", - "repository": { - "type": "git", - "url": "https://github.com/0xProject/0x-monorepo.git" - }, - "bugs": { - "url": "https://github.com/0xProject/0x-monorepo/issues" - }, - "homepage": "https://github.com/0xProject/0x-monorepo/packages/utils/README.md", - "devDependencies": { - "@0x/tslint-config": "^4.1.0", - "@types/detect-node": "2.0.0", - "@types/lodash": "4.14.104", - "@types/mocha": "^5.2.7", - "chai": "^4.0.1", - "chai-as-promised": "^7.1.0", - "chai-bignumber": "^3.0.0", - "dirty-chai": "^2.0.1", - "make-promises-safe": "^1.1.0", - "mocha": "^6.2.0", - "npm-run-all": "^4.1.2", - "shx": "^0.2.2", - "tslint": "5.11.0", - "typescript": "3.0.1" - }, - "dependencies": { - "@0x/types": "^3.2.0", - "@0x/typescript-typings": "^5.1.1", - "@types/node": "12.12.54", - "abortcontroller-polyfill": "^1.1.9", - "bignumber.js": "~9.0.0", - "chalk": "^2.3.0", - "detect-node": "2.0.3", - "ethereum-types": "^3.2.0", - "ethereumjs-util": "^5.1.1", - "ethers": "~4.0.4", - "isomorphic-fetch": "2.2.1", - "js-sha3": "^0.7.0", - "lodash": "^4.17.11" - }, - "publishConfig": { - "access": "public" - }, - "gitHead": "4f91bfd907996b2f4dd383778b50c479c2602b56" -} diff --git a/packages/utils/src/abi_decoder.ts b/packages/utils/src/abi_decoder.ts deleted file mode 100644 index dc2b09d042..0000000000 --- a/packages/utils/src/abi_decoder.ts +++ /dev/null @@ -1,195 +0,0 @@ -import { - AbiDefinition, - AbiType, - DataItem, - DecodedLogArgs, - EventAbi, - LogEntry, - LogWithDecodedArgs, - MethodAbi, - RawLog, -} from 'ethereum-types'; -import * as ethers from 'ethers'; -import * as _ from 'lodash'; - -import { AbiEncoder } from '.'; -import { DecodedCalldata, SelectorToFunctionInfo } from './types'; - -/** - * AbiDecoder allows you to decode event logs given a set of supplied contract ABI's. It takes the contract's event - * signature from the ABI and attempts to decode the logs using it. - */ -export class AbiDecoder { - private readonly _eventIds: { [signatureHash: string]: { [numIndexedArgs: number]: EventAbi } } = {}; - private readonly _selectorToFunctionInfo: SelectorToFunctionInfo = {}; - /** - * Retrieves the function selector from calldata. - * @param calldata hex-encoded calldata. - * @return hex-encoded function selector. - */ - private static _getFunctionSelector(calldata: string): string { - const functionSelectorLength = 10; - if (!calldata.startsWith('0x') || calldata.length < functionSelectorLength) { - throw new Error( - `Malformed calldata. Must include a hex prefix '0x' and 4-byte function selector. Got '${calldata}'`, - ); - } - const functionSelector = calldata.substr(0, functionSelectorLength); - return functionSelector; - } - /** - * Instantiate an AbiDecoder - * @param abiArrays An array of contract ABI's - * @return AbiDecoder instance - */ - constructor(abiArrays: AbiDefinition[][]) { - _.each(abiArrays, abi => { - this.addABI(abi); - }); - } - /** - * Attempt to decode a log given the ABI's the AbiDecoder knows about. - * @param log The log to attempt to decode - * @return The decoded log if the requisite ABI was available. Otherwise the log unaltered. - */ - public tryToDecodeLogOrNoop(log: LogEntry): LogWithDecodedArgs | RawLog { - // Lookup event corresponding to log - const eventId = log.topics[0]; - const numIndexedArgs = log.topics.length - 1; - if (this._eventIds[eventId] === undefined || this._eventIds[eventId][numIndexedArgs] === undefined) { - return log; - } - const event = this._eventIds[eventId][numIndexedArgs]; - - // Create decoders for indexed data - const indexedDataDecoders = _.mapValues(_.filter(event.inputs, { indexed: true }), input => - // tslint:disable:next-line no-unnecessary-type-assertion - AbiEncoder.create(input as DataItem), - ); - - // Decode indexed data - const decodedIndexedData = _.map( - log.topics.slice(1), // ignore first topic, which is the event id. - (input, i) => indexedDataDecoders[i].decode(input), - ); - - // Decode non-indexed data - const decodedNonIndexedData = AbiEncoder.create(_.filter(event.inputs, { indexed: false })).decodeAsArray( - log.data, - ); - - // Construct DecodedLogArgs struct by mapping event parameters to their respective decoded argument. - const decodedArgs: DecodedLogArgs = {}; - let indexedOffset = 0; - let nonIndexedOffset = 0; - for (const param of event.inputs) { - const value = param.indexed - ? decodedIndexedData[indexedOffset++] - : decodedNonIndexedData[nonIndexedOffset++]; - - if (value === undefined) { - return log; - } - - decodedArgs[param.name] = value; - } - - // Decoding was successful. Return decoded log. - return { - ...log, - event: event.name, - args: decodedArgs as ArgsType, - }; - } - /** - * Decodes calldata for a known ABI. - * @param calldata hex-encoded calldata. - * @param contractName used to disambiguate similar ABI's (optional). - * @return Decoded calldata. Includes: function name and signature, along with the decoded arguments. - */ - public decodeCalldataOrThrow(calldata: string, contractName?: string): DecodedCalldata { - const functionSelector = AbiDecoder._getFunctionSelector(calldata); - const candidateFunctionInfos = this._selectorToFunctionInfo[functionSelector]; - if (candidateFunctionInfos === undefined) { - throw new Error(`No functions registered for selector '${functionSelector}'`); - } - const functionInfo = _.find(candidateFunctionInfos, candidateFunctionInfo => { - return ( - contractName === undefined || _.toLower(contractName) === _.toLower(candidateFunctionInfo.contractName) - ); - }); - if (functionInfo === undefined) { - throw new Error( - `No function registered with selector ${functionSelector} and contract name ${contractName}.`, - ); - } else if (functionInfo.abiEncoder === undefined) { - throw new Error( - `Function ABI Encoder is not defined, for function registered with selector ${functionSelector} and contract name ${contractName}.`, - ); - } - const functionName = functionInfo.abiEncoder.getDataItem().name; - const functionSignature = functionInfo.abiEncoder.getSignatureType(); - const functionArguments = functionInfo.abiEncoder.decode(calldata); - const decodedCalldata = { - functionName, - functionSignature, - functionArguments, - }; - return decodedCalldata; - } - /** - * Adds a set of ABI definitions, after which calldata and logs targeting these ABI's can be decoded. - * Additional properties can be included to disambiguate similar ABI's. For example, if two functions - * have the same signature but different parameter names, then their ABI definitions can be disambiguated - * by specifying a contract name. - * @param abiDefinitions ABI definitions for a given contract. - * @param contractName Name of contract that encapsulates the ABI definitions (optional). - * This can be used when decoding calldata to disambiguate methods with - * the same signature but different parameter names. - */ - public addABI(abiArray: AbiDefinition[], contractName?: string): void { - if (abiArray === undefined) { - return; - } - const ethersInterface = new ethers.utils.Interface(abiArray); - _.map(abiArray, (abi: AbiDefinition) => { - switch (abi.type) { - case AbiType.Event: - // tslint:disable-next-line:no-unnecessary-type-assertion - this._addEventABI(abi as EventAbi, ethersInterface); - break; - - case AbiType.Function: - // tslint:disable-next-line:no-unnecessary-type-assertion - this._addMethodABI(abi as MethodAbi, contractName); - break; - - default: - // ignore other types - break; - } - }); - } - private _addEventABI(eventAbi: EventAbi, ethersInterface: ethers.utils.Interface): void { - const topic = ethersInterface.events[eventAbi.name].topic; - const numIndexedArgs = _.reduce(eventAbi.inputs, (sum, input) => (input.indexed ? sum + 1 : sum), 0); - this._eventIds[topic] = { - ...this._eventIds[topic], - [numIndexedArgs]: eventAbi, - }; - } - private _addMethodABI(methodAbi: MethodAbi, contractName?: string): void { - const abiEncoder = new AbiEncoder.Method(methodAbi); - const functionSelector = abiEncoder.getSelector(); - if (!(functionSelector in this._selectorToFunctionInfo)) { - this._selectorToFunctionInfo[functionSelector] = []; - } - // Recored a copy of this ABI for each deployment - const functionSignature = abiEncoder.getSignature(); - this._selectorToFunctionInfo[functionSelector].push({ - functionSignature, - abiEncoder, - contractName, - }); - } -} diff --git a/packages/utils/src/abi_encoder/abstract_data_types/data_type.ts b/packages/utils/src/abi_encoder/abstract_data_types/data_type.ts deleted file mode 100644 index d7caf5d5a0..0000000000 --- a/packages/utils/src/abi_encoder/abstract_data_types/data_type.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { DataItem } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { Calldata } from '../calldata/calldata'; -import { CalldataBlock } from '../calldata/calldata_block'; -import { RawCalldata } from '../calldata/raw_calldata'; -import { constants } from '../utils/constants'; -import { DecodingRules, EncodingRules } from '../utils/rules'; - -import { DataTypeFactory } from './interfaces'; - -export abstract class DataType { - private readonly _dataItem: DataItem; - private readonly _factory: DataTypeFactory; - - constructor(dataItem: DataItem, factory: DataTypeFactory) { - this._dataItem = dataItem; - this._factory = factory; - } - - public getDataItem(): DataItem { - return this._dataItem; - } - - public getFactory(): DataTypeFactory { - return this._factory; - } - - public encode(value: any, rules?: Partial, selector?: string): string { - const rules_ = { ...constants.DEFAULT_ENCODING_RULES, ...rules }; - const calldata = new Calldata(rules_); - if (selector !== undefined) { - calldata.setSelector(selector); - } - const block = this.generateCalldataBlock(value); - calldata.setRoot(block); - const encodedCalldata = calldata.toString(); - return encodedCalldata; - } - - public decode(calldata: string, rules?: Partial, selector?: string): any { - if (selector !== undefined && !_.startsWith(calldata, selector)) { - throw new Error( - `Tried to decode calldata, but it was missing the function selector. Expected prefix '${selector}'. Got '${calldata}'.`, - ); - } - const hasSelector = selector !== undefined; - const rawCalldata = new RawCalldata(calldata, hasSelector); - const rules_ = { ...constants.DEFAULT_DECODING_RULES, ...rules }; - const value = - rules_.isStrictMode || rawCalldata.getSizeInBytes() > 0 - ? this.generateValue(rawCalldata, rules_) - : this.getDefaultValue(rules_); - return value; - } - - public decodeAsArray(returndata: string, rules?: Partial): any[] { - const value = this.decode(returndata, rules); - const valuesAsArray = _.isObject(value) ? _.values(value) : [value]; - return valuesAsArray; - } - - public getSignature(isDetailed?: boolean): string { - if (_.isEmpty(this._dataItem.name) || !isDetailed) { - return this.getSignatureType(); - } - const name = this.getDataItem().name; - const lastIndexOfScopeDelimiter = name.lastIndexOf('.'); - const isScopedName = lastIndexOfScopeDelimiter !== undefined && lastIndexOfScopeDelimiter > 0; - const shortName = isScopedName ? name.substr((lastIndexOfScopeDelimiter as number) + 1) : name; - const detailedSignature = `${shortName} ${this.getSignatureType()}`; - return detailedSignature; - } - - public abstract generateCalldataBlock(value: any, parentBlock?: CalldataBlock): CalldataBlock; - public abstract generateValue(calldata: RawCalldata, rules: DecodingRules): any; - public abstract getDefaultValue(rules?: DecodingRules): any; - public abstract getSignatureType(): string; - public abstract isStatic(): boolean; -} diff --git a/packages/utils/src/abi_encoder/abstract_data_types/interfaces.ts b/packages/utils/src/abi_encoder/abstract_data_types/interfaces.ts deleted file mode 100644 index 2f2f60871e..0000000000 --- a/packages/utils/src/abi_encoder/abstract_data_types/interfaces.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { DataItem } from 'ethereum-types'; - -import { RawCalldata } from '../calldata/raw_calldata'; - -import { DataType } from './data_type'; - -export interface DataTypeFactory { - create: (dataItem: DataItem, parentDataType?: DataType) => DataType; -} - -export interface DataTypeStaticInterface { - matchType: (type: string) => boolean; - encodeValue: (value: any) => Buffer; - decodeValue: (rawCalldata: RawCalldata) => any; -} - -export interface MemberIndexByName { - [key: string]: number; -} diff --git a/packages/utils/src/abi_encoder/abstract_data_types/types/blob.ts b/packages/utils/src/abi_encoder/abstract_data_types/types/blob.ts deleted file mode 100644 index 4c22212fd0..0000000000 --- a/packages/utils/src/abi_encoder/abstract_data_types/types/blob.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { DataItem } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { BlobCalldataBlock } from '../../calldata/blocks/blob'; -import { CalldataBlock } from '../../calldata/calldata_block'; -import { RawCalldata } from '../../calldata/raw_calldata'; -import { DecodingRules } from '../../utils/rules'; - -import { DataType } from '../data_type'; -import { DataTypeFactory } from '../interfaces'; - -export abstract class AbstractBlobDataType extends DataType { - protected _sizeKnownAtCompileTime: boolean; - - public constructor(dataItem: DataItem, factory: DataTypeFactory, sizeKnownAtCompileTime: boolean) { - super(dataItem, factory); - this._sizeKnownAtCompileTime = sizeKnownAtCompileTime; - } - - public generateCalldataBlock(value: any, parentBlock?: CalldataBlock): BlobCalldataBlock { - const encodedValue = this.encodeValue(value); - const name = this.getDataItem().name; - const signature = this.getSignature(); - const parentName = parentBlock === undefined ? '' : parentBlock.getName(); - const block = new BlobCalldataBlock(name, signature, parentName, encodedValue); - return block; - } - - public generateValue(calldata: RawCalldata, rules: DecodingRules): any { - const value = this.decodeValue(calldata); - return value; - } - - public isStatic(): boolean { - return this._sizeKnownAtCompileTime; - } - - public abstract encodeValue(value: any): Buffer; - public abstract decodeValue(calldata: RawCalldata): any; -} diff --git a/packages/utils/src/abi_encoder/abstract_data_types/types/pointer.ts b/packages/utils/src/abi_encoder/abstract_data_types/types/pointer.ts deleted file mode 100644 index 59036dc619..0000000000 --- a/packages/utils/src/abi_encoder/abstract_data_types/types/pointer.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { DataItem } from 'ethereum-types'; -import * as ethUtil from 'ethereumjs-util'; -import * as _ from 'lodash'; - -import { PointerCalldataBlock } from '../../calldata/blocks/pointer'; -import { CalldataBlock } from '../../calldata/calldata_block'; -import { RawCalldata } from '../../calldata/raw_calldata'; -import { constants } from '../../utils/constants'; -import { DecodingRules } from '../../utils/rules'; - -import { DataType } from '../data_type'; -import { DataTypeFactory } from '../interfaces'; - -export abstract class AbstractPointerDataType extends DataType { - protected _destination: DataType; - protected _parent: DataType; - - public constructor(dataItem: DataItem, factory: DataTypeFactory, destination: DataType, parent: DataType) { - super(dataItem, factory); - this._destination = destination; - this._parent = parent; - } - - public generateCalldataBlock(value: any, parentBlock?: CalldataBlock): PointerCalldataBlock { - if (parentBlock === undefined) { - throw new Error(`DependentDataType requires a parent block to generate its block`); - } - const destinationBlock = this._destination.generateCalldataBlock(value, parentBlock); - const name = this.getDataItem().name; - const signature = this.getSignature(); - const parentName = parentBlock.getName(); - const block = new PointerCalldataBlock(name, signature, parentName, destinationBlock, parentBlock); - return block; - } - - public generateValue(calldata: RawCalldata, rules: DecodingRules): any { - const destinationOffsetBuf = calldata.popWord(); - const destinationOffsetHex = ethUtil.bufferToHex(destinationOffsetBuf); - const destinationOffsetRelative = parseInt(destinationOffsetHex, constants.HEX_BASE); - const destinationOffsetAbsolute = calldata.toAbsoluteOffset(destinationOffsetRelative); - const currentOffset = calldata.getOffset(); - calldata.setOffset(destinationOffsetAbsolute); - const value = this._destination.generateValue(calldata, rules); - calldata.setOffset(currentOffset); - return value; - } - - // Disable prefer-function-over-method for inherited abstract method. - /* tslint:disable prefer-function-over-method */ - public isStatic(): boolean { - return true; - } - /* tslint:enable prefer-function-over-method */ -} diff --git a/packages/utils/src/abi_encoder/abstract_data_types/types/set.ts b/packages/utils/src/abi_encoder/abstract_data_types/types/set.ts deleted file mode 100644 index 9bb22180bd..0000000000 --- a/packages/utils/src/abi_encoder/abstract_data_types/types/set.ts +++ /dev/null @@ -1,244 +0,0 @@ -import { ObjectMap } from '@0x/types'; -import { DataItem } from 'ethereum-types'; -import * as ethUtil from 'ethereumjs-util'; -import * as _ from 'lodash'; - -import { BigNumber } from '../../../configured_bignumber'; -import { SetCalldataBlock } from '../../calldata/blocks/set'; -import { CalldataBlock } from '../../calldata/calldata_block'; -import { RawCalldata } from '../../calldata/raw_calldata'; -import { constants } from '../../utils/constants'; -import { DecodingRules } from '../../utils/rules'; - -import { DataType } from '../data_type'; -import { DataTypeFactory, MemberIndexByName } from '../interfaces'; - -import { AbstractPointerDataType } from './pointer'; - -export abstract class AbstractSetDataType extends DataType { - protected readonly _arrayLength: number | undefined; - protected readonly _arrayElementType: string | undefined; - private readonly _memberIndexByName: MemberIndexByName; - private readonly _members: DataType[]; - private readonly _isArray: boolean; - - public constructor( - dataItem: DataItem, - factory: DataTypeFactory, - isArray: boolean = false, - arrayLength?: number, - arrayElementType?: string, - ) { - super(dataItem, factory); - this._memberIndexByName = {}; - this._members = []; - this._isArray = isArray; - this._arrayLength = arrayLength; - this._arrayElementType = arrayElementType; - if (isArray && arrayLength !== undefined) { - [this._members, this._memberIndexByName] = this._createMembersWithLength(dataItem, arrayLength); - } else if (!isArray) { - [this._members, this._memberIndexByName] = this._createMembersWithKeys(dataItem); - } - } - - public generateCalldataBlock(value: any[] | object, parentBlock?: CalldataBlock): SetCalldataBlock { - const block = Array.isArray(value) - ? this._generateCalldataBlockFromArray(value, parentBlock) - : this._generateCalldataBlockFromObject(value, parentBlock); - return block; - } - - public generateValue(calldata: RawCalldata, rules: DecodingRules): any[] | object { - let members = this._members; - // Case 1: This is an array of undefined length, which means that `this._members` was not - // populated in the constructor. So we must construct the set of members now. - if (this._isArray && this._arrayLength === undefined) { - const arrayLengthBuf = calldata.popWord(); - const arrayLengthHex = ethUtil.bufferToHex(arrayLengthBuf); - const arrayLength = new BigNumber(arrayLengthHex, constants.HEX_BASE); - [members] = this._createMembersWithLength(this.getDataItem(), arrayLength.toNumber()); - } - // Create a new scope in the calldata, before descending into the members of this set. - calldata.startScope(); - let value: any[] | object; - if (rules.shouldConvertStructsToObjects && !this._isArray) { - // Construct an object with values for each member of the set. - value = {}; - _.each(this._memberIndexByName, (idx: number, key: string) => { - const member = this._members[idx]; - const memberValue = member.generateValue(calldata, rules); - (value as { [key: string]: any })[key] = memberValue; - }); - } else { - // Construct an array with values for each member of the set. - value = []; - _.each(members, (member: DataType, idx: number) => { - const memberValue = member.generateValue(calldata, rules); - (value as any[]).push(memberValue); - }); - } - // Close this scope and return tetheh value. - calldata.endScope(); - return value; - } - - public isStatic(): boolean { - // An array with an undefined length is never static. - if (this._isArray && this._arrayLength === undefined) { - return false; - } - // If any member of the set is a pointer then the set is not static. - const dependentMember = _.find(this._members, (member: DataType) => { - return member instanceof AbstractPointerDataType; - }); - const isStatic = dependentMember === undefined; - return isStatic; - } - - public getDefaultValue(rules?: DecodingRules): any[] | object { - let defaultValue: any[] | object; - if (this._isArray && this._arrayLength === undefined) { - defaultValue = []; - } else if (rules !== undefined && rules.shouldConvertStructsToObjects && !this._isArray) { - defaultValue = {}; - _.each(this._memberIndexByName, (idx: number, key: string) => { - const member = this._members[idx]; - const memberValue = member.getDefaultValue(); - (defaultValue as { [key: string]: any })[key] = memberValue; - }); - } else { - defaultValue = []; - _.each(this._members, (member: DataType, idx: number) => { - const memberValue = member.getDefaultValue(); - (defaultValue as any[]).push(memberValue); - }); - } - return defaultValue; - } - - protected _generateCalldataBlockFromArray(value: any[], parentBlock?: CalldataBlock): SetCalldataBlock { - // Sanity check: if the set has a defined length then `value` must have the same length. - if (this._arrayLength !== undefined && value.length !== this._arrayLength) { - throw new Error( - `Expected array of ${JSON.stringify( - this._arrayLength, - )} elements, but got array of length ${JSON.stringify(value.length)}`, - ); - } - // Create a new calldata block for this set. - const parentName = parentBlock === undefined ? '' : parentBlock.getName(); - const block = new SetCalldataBlock(this.getDataItem().name, this.getSignature(), parentName); - // If this set has an undefined length then set its header to be the number of elements. - let members = this._members; - if (this._isArray && this._arrayLength === undefined) { - [members] = this._createMembersWithLength(this.getDataItem(), value.length); - const lenBuf = ethUtil.setLengthLeft( - ethUtil.toBuffer(`0x${value.length.toString(constants.HEX_BASE)}`), - constants.EVM_WORD_WIDTH_IN_BYTES, - ); - block.setHeader(lenBuf); - } - // Create blocks for members of set. - const memberCalldataBlocks: CalldataBlock[] = []; - _.each(members, (member: DataType, idx: number) => { - const memberBlock = member.generateCalldataBlock(value[idx], block); - memberCalldataBlocks.push(memberBlock); - }); - block.setMembers(memberCalldataBlocks); - return block; - } - - protected _generateCalldataBlockFromObject(obj: object, parentBlock?: CalldataBlock): SetCalldataBlock { - // Create a new calldata block for this set. - const parentName = parentBlock === undefined ? '' : parentBlock.getName(); - const block = new SetCalldataBlock(this.getDataItem().name, this.getSignature(), parentName); - // Create blocks for members of set. - const memberCalldataBlocks: CalldataBlock[] = []; - _.forEach(this._memberIndexByName, (memberIndex: number, memberName: string) => { - if (!(memberName in obj)) { - throw new Error( - `Could not assign tuple to object: missing key '${memberName}' in object ${JSON.stringify(obj)}`, - ); - } - const memberValue: any = (obj as ObjectMap)[memberName]; - const memberBlock = this._members[memberIndex].generateCalldataBlock(memberValue, block); - memberCalldataBlocks.push(memberBlock); - }); - // Associate member blocks with Set block. - block.setMembers(memberCalldataBlocks); - return block; - } - - protected _computeSignatureOfMembers(isDetailed?: boolean): string { - // Compute signature of members - let signature = `(`; - _.each(this._members, (member: DataType, i: number) => { - signature += member.getSignature(isDetailed); - if (i < this._members.length - 1) { - signature += ','; - } - }); - signature += ')'; - return signature; - } - - private _createMembersWithKeys(dataItem: DataItem): [DataType[], MemberIndexByName] { - // Sanity check - if (dataItem.components === undefined) { - throw new Error( - `Tried to create a set using key/value pairs, but no components were defined by the input DataItem '${ - dataItem.name - }'.`, - ); - } - // Create one member for each component of `dataItem` - const members: DataType[] = []; - const memberIndexByName: MemberIndexByName = {}; - const memberNames: string[] = []; - _.each(dataItem.components, (memberItem: DataItem) => { - // If a component with `name` already exists then - // rename to `name_nameIdx` to avoid naming conflicts. - let memberName = memberItem.name; - let nameIdx = 0; - while (_.includes(memberNames, memberName) || _.isEmpty(memberName)) { - nameIdx++; - memberName = `${memberItem.name}_${nameIdx}`; - } - memberNames.push(memberName); - const childDataItem: DataItem = { - type: memberItem.type, - name: `${dataItem.name}.${memberName}`, - }; - const components = memberItem.components; - if (components !== undefined) { - childDataItem.components = components; - } - const child = this.getFactory().create(childDataItem, this); - memberIndexByName[memberName] = members.length; - members.push(child); - }); - return [members, memberIndexByName]; - } - - private _createMembersWithLength(dataItem: DataItem, length: number): [DataType[], MemberIndexByName] { - // Create `length` members, deriving the type from `dataItem` - const members: DataType[] = []; - const memberIndexByName: MemberIndexByName = {}; - const range = _.range(length); - _.each(range, (idx: number) => { - const memberDataItem: DataItem = { - type: this._arrayElementType === undefined ? '' : this._arrayElementType, - name: `${dataItem.name}[${idx.toString(constants.DEC_BASE)}]`, - }; - const components = dataItem.components; - if (components !== undefined) { - memberDataItem.components = components; - } - const memberType = this.getFactory().create(memberDataItem, this); - memberIndexByName[idx.toString(constants.DEC_BASE)] = members.length; - members.push(memberType); - }); - return [members, memberIndexByName]; - } -} diff --git a/packages/utils/src/abi_encoder/calldata/blocks/blob.ts b/packages/utils/src/abi_encoder/calldata/blocks/blob.ts deleted file mode 100644 index 219ea6c612..0000000000 --- a/packages/utils/src/abi_encoder/calldata/blocks/blob.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { CalldataBlock } from '../calldata_block'; - -export class BlobCalldataBlock extends CalldataBlock { - private readonly _blob: Buffer; - - constructor(name: string, signature: string, parentName: string, blob: Buffer) { - const headerSizeInBytes = 0; - const bodySizeInBytes = blob.byteLength; - super(name, signature, parentName, headerSizeInBytes, bodySizeInBytes); - this._blob = blob; - } - - public toBuffer(): Buffer { - return this._blob; - } - - public getRawData(): Buffer { - return this._blob; - } -} diff --git a/packages/utils/src/abi_encoder/calldata/blocks/pointer.ts b/packages/utils/src/abi_encoder/calldata/blocks/pointer.ts deleted file mode 100644 index 79a2cbd3e9..0000000000 --- a/packages/utils/src/abi_encoder/calldata/blocks/pointer.ts +++ /dev/null @@ -1,60 +0,0 @@ -import * as ethUtil from 'ethereumjs-util'; -import * as _ from 'lodash'; - -import { constants } from '../../utils/constants'; - -import { CalldataBlock } from '../calldata_block'; - -export class PointerCalldataBlock extends CalldataBlock { - public static readonly RAW_DATA_START = Buffer.from('<'); - public static readonly RAW_DATA_END = Buffer.from('>'); - private static readonly _DEPENDENT_PAYLOAD_SIZE_IN_BYTES = 32; - private static readonly _EMPTY_HEADER_SIZE = 0; - private readonly _parent: CalldataBlock; - private readonly _dependency: CalldataBlock; - private _aliasFor: CalldataBlock | undefined; - - constructor(name: string, signature: string, parentName: string, dependency: CalldataBlock, parent: CalldataBlock) { - const headerSizeInBytes = PointerCalldataBlock._EMPTY_HEADER_SIZE; - const bodySizeInBytes = PointerCalldataBlock._DEPENDENT_PAYLOAD_SIZE_IN_BYTES; - super(name, signature, parentName, headerSizeInBytes, bodySizeInBytes); - this._parent = parent; - this._dependency = dependency; - this._aliasFor = undefined; - } - - public toBuffer(): Buffer { - const destinationOffset = - this._aliasFor !== undefined ? this._aliasFor.getOffsetInBytes() : this._dependency.getOffsetInBytes(); - const parentOffset = this._parent.getOffsetInBytes(); - const parentHeaderSize = this._parent.getHeaderSizeInBytes(); - const pointer: number = destinationOffset - (parentOffset + parentHeaderSize); - const pointerHex = `0x${pointer.toString(constants.HEX_BASE)}`; - const pointerBuf = ethUtil.toBuffer(pointerHex); - const pointerBufPadded = ethUtil.setLengthLeft(pointerBuf, constants.EVM_WORD_WIDTH_IN_BYTES); - return pointerBufPadded; - } - - public getDependency(): CalldataBlock { - return this._dependency; - } - - public setAlias(block: CalldataBlock): void { - this._aliasFor = block; - this._setName(`${this.getName()} (alias for ${block.getName()})`); - } - - public getAlias(): CalldataBlock | undefined { - return this._aliasFor; - } - - public getRawData(): Buffer { - const dependencyRawData = this._dependency.getRawData(); - const rawDataComponents: Buffer[] = []; - rawDataComponents.push(PointerCalldataBlock.RAW_DATA_START); - rawDataComponents.push(dependencyRawData); - rawDataComponents.push(PointerCalldataBlock.RAW_DATA_END); - const rawData = Buffer.concat(rawDataComponents); - return rawData; - } -} diff --git a/packages/utils/src/abi_encoder/calldata/blocks/set.ts b/packages/utils/src/abi_encoder/calldata/blocks/set.ts deleted file mode 100644 index ca22144174..0000000000 --- a/packages/utils/src/abi_encoder/calldata/blocks/set.ts +++ /dev/null @@ -1,47 +0,0 @@ -import * as _ from 'lodash'; - -import { CalldataBlock } from '../calldata_block'; - -export class SetCalldataBlock extends CalldataBlock { - private _header: Buffer | undefined; - private _members: CalldataBlock[]; - - constructor(name: string, signature: string, parentName: string) { - super(name, signature, parentName, 0, 0); - this._members = []; - this._header = undefined; - } - - public getRawData(): Buffer { - const rawDataComponents: Buffer[] = []; - if (this._header !== undefined) { - rawDataComponents.push(this._header); - } - _.each(this._members, (member: CalldataBlock) => { - const memberBuffer = member.getRawData(); - rawDataComponents.push(memberBuffer); - }); - const rawData = Buffer.concat(rawDataComponents); - return rawData; - } - - public setMembers(members: CalldataBlock[]): void { - this._members = members; - } - - public setHeader(header: Buffer): void { - this._setHeaderSize(header.byteLength); - this._header = header; - } - - public toBuffer(): Buffer { - if (this._header !== undefined) { - return this._header; - } - return Buffer.from(''); - } - - public getMembers(): CalldataBlock[] { - return this._members; - } -} diff --git a/packages/utils/src/abi_encoder/calldata/calldata.ts b/packages/utils/src/abi_encoder/calldata/calldata.ts deleted file mode 100644 index 72d103c9bc..0000000000 --- a/packages/utils/src/abi_encoder/calldata/calldata.ts +++ /dev/null @@ -1,245 +0,0 @@ -import * as ethUtil from 'ethereumjs-util'; -import * as _ from 'lodash'; - -import { constants } from '../utils/constants'; -import { EncodingRules } from '../utils/rules'; - -import { PointerCalldataBlock } from './blocks/pointer'; -import { SetCalldataBlock } from './blocks/set'; -import { CalldataBlock } from './calldata_block'; -import { CalldataIterator, ReverseCalldataIterator } from './iterator'; - -export class Calldata { - private readonly _rules: EncodingRules; - private _selector: string; - private _root: CalldataBlock | undefined; - - public constructor(rules: EncodingRules) { - this._rules = rules; - this._selector = ''; - this._root = undefined; - } - /** - * Sets the root calldata block. This block usually corresponds to a Method. - */ - public setRoot(block: CalldataBlock): void { - this._root = block; - } - /** - * Sets the selector to be prepended onto the calldata. - * If the root block was created by a Method then a selector will likely be set. - */ - public setSelector(selector: string): void { - if (!_.startsWith(selector, '0x')) { - throw new Error(`Expected selector to be hex. Missing prefix '0x'`); - } else if (selector.length !== constants.HEX_SELECTOR_LENGTH_IN_CHARS) { - throw new Error(`Invalid selector '${selector}'`); - } - this._selector = selector; - } - /** - * Iterates through the calldata blocks, starting from the root block, to construct calldata as a hex string. - * If the `optimize` flag is set then this calldata will be condensed, to save gas. - * If the `annotate` flag is set then this will return human-readable calldata. - * If the `annotate` flag is *not* set then this will return EVM-compatible calldata. - */ - public toString(): string { - // Sanity check: root block must be set - if (this._root === undefined) { - throw new Error('expected root'); - } - // Optimize, if flag set - if (this._rules.shouldOptimize) { - this._optimize(); - } - // Set offsets - const iterator = new CalldataIterator(this._root); - let offset = 0; - for (const block of iterator) { - block.setOffset(offset); - offset += block.getSizeInBytes(); - } - // Generate hex string - const hexString = this._rules.shouldAnnotate - ? this._toHumanReadableCallData() - : this._toEvmCompatibeCallDataHex(); - return hexString; - } - /** - * There are three types of calldata blocks: Blob, Set and Pointer. - * Scenarios arise where distinct pointers resolve to identical values. - * We optimize by keeping only one such instance of the identical value, and redirecting all pointers here. - * We keep the last such duplicate value because pointers can only be positive (they cannot point backwards). - * - * Example #1: - * function f(string[], string[]) - * f(["foo", "bar", "blitz"], ["foo", "bar", "blitz"]) - * The array ["foo", "bar", "blitz"] will only be included in the calldata once. - * - * Example #2: - * function f(string[], string) - * f(["foo", "bar", "blitz"], "foo") - * The string "foo" will only be included in the calldata once. - * - * Example #3: - * function f((string, uint, bytes), string, uint, bytes) - * f(("foo", 5, "0x05"), "foo", 5, "0x05") - * The string "foo" and bytes "0x05" will only be included in the calldata once. - * The duplicate `uint 5` values cannot be optimized out because they are static values (no pointer points to them). - * - * @TODO #1: - * This optimization strategy handles blocks that are exact duplicates of one another. - * But what if some block is a combination of two other blocks? Or a subset of another block? - * This optimization problem is not much different from the current implemetation. - * Instead of tracking "observed" hashes, at each node we would simply do pattern-matching on the calldata. - * This strategy would be applied after assigning offsets to the tree, rather than before (as in this strategy). - * Note that one consequence of this strategy is pointers may resolve to offsets that are not word-aligned. - * This shouldn't be a problem but further investigation should be done. - * - * @TODO #2: - * To be done as a follow-up to @TODO #1. - * Since we optimize from the bottom-up, we could be affecting the outcome of a later potential optimization. - * For example, what if by removing one duplicate value we miss out on optimizing another block higher in the tree. - * To handle this case, at each node we can store a candidate optimization in a priority queue (sorted by calldata size). - * At the end of traversing the tree, the candidate at the front of the queue will be the most optimal output. - * - */ - private _optimize(): void { - // Step 1/1 Create a reverse iterator (starts from the end of the calldata to the beginning) - if (this._root === undefined) { - throw new Error('expected root'); - } - const iterator = new ReverseCalldataIterator(this._root); - // Step 2/2 Iterate over each block, keeping track of which blocks have been seen and pruning redundant blocks. - const blocksByHash: { [key: string]: CalldataBlock } = {}; - for (const block of iterator) { - // If a block is a pointer and its value has already been observed, then update - // the pointer to resolve to the existing value. - if (block instanceof PointerCalldataBlock) { - const dependencyBlockHashBuf = block.getDependency().computeHash(); - const dependencyBlockHash = ethUtil.bufferToHex(dependencyBlockHashBuf); - if (dependencyBlockHash in blocksByHash) { - const blockWithSameHash = blocksByHash[dependencyBlockHash]; - if (blockWithSameHash !== block.getDependency()) { - block.setAlias(blockWithSameHash); - } - } - continue; - } - // This block has not been seen. Record its hash. - const blockHashBuf = block.computeHash(); - const blockHash = ethUtil.bufferToHex(blockHashBuf); - if (!(blockHash in blocksByHash)) { - blocksByHash[blockHash] = block; - } - } - } - private _toEvmCompatibeCallDataHex(): string { - // Sanity check: must have a root block. - if (this._root === undefined) { - throw new Error('expected root'); - } - // Construct an array of buffers (one buffer for each block). - const selectorBuffer = ethUtil.toBuffer(this._selector); - const valueBufs: Buffer[] = [selectorBuffer]; - const iterator = new CalldataIterator(this._root); - for (const block of iterator) { - valueBufs.push(block.toBuffer()); - } - // Create hex from buffer array. - const combinedBuffers = Buffer.concat(valueBufs); - const hexValue = ethUtil.bufferToHex(combinedBuffers); - return hexValue; - } - /** - * Returns human-readable calldata. - * - * Example: - * simpleFunction(string[], string[]) - * strings = ["Hello", "World"] - * simpleFunction(strings, strings) - * - * Output: - * 0xbb4f12e3 - * ### simpleFunction - * 0x0 0000000000000000000000000000000000000000000000000000000000000040 ptr (alias for array2) - * 0x20 0000000000000000000000000000000000000000000000000000000000000040 ptr - * - * 0x40 0000000000000000000000000000000000000000000000000000000000000002 ### array2 - * 0x60 0000000000000000000000000000000000000000000000000000000000000040 ptr - * 0x80 0000000000000000000000000000000000000000000000000000000000000080 ptr - * 0xa0 0000000000000000000000000000000000000000000000000000000000000005 array2[0] - * 0xc0 48656c6c6f000000000000000000000000000000000000000000000000000000 - * 0xe0 0000000000000000000000000000000000000000000000000000000000000005 array2[1] - * 0x100 576f726c64000000000000000000000000000000000000000000000000000000 - */ - private _toHumanReadableCallData(): string { - // Sanity check: must have a root block. - if (this._root === undefined) { - throw new Error('expected root'); - } - // Constants for constructing annotated string - const offsetPadding = 10; - const valuePadding = 74; - const namePadding = 80; - const evmWordStartIndex = 0; - const emptySize = 0; - // Construct annotated calldata - let hexValue = `${this._selector}`; - let offset = 0; - const functionName: string = this._root.getName(); - const iterator = new CalldataIterator(this._root); - for (const block of iterator) { - // Process each block 1 word at a time - const size = block.getSizeInBytes(); - const name = block.getName(); - const parentName = block.getParentName(); - const prettyName = name.replace(`${parentName}.`, '').replace(`${functionName}.`, ''); - // Resulting line will be - let offsetStr = ''; - let valueStr = ''; - let nameStr = ''; - let lineStr = ''; - if (size === emptySize) { - // This is a Set block with no header. - // For example, a tuple or an array with a defined length. - offsetStr = ' '.repeat(offsetPadding); - valueStr = ' '.repeat(valuePadding); - nameStr = `### ${prettyName.padEnd(namePadding)}`; - lineStr = `\n${offsetStr}${valueStr}${nameStr}`; - } else { - // This block has at least one word of value. - offsetStr = `0x${offset.toString(constants.HEX_BASE)}`.padEnd(offsetPadding); - valueStr = ethUtil - .stripHexPrefix( - ethUtil.bufferToHex( - block.toBuffer().slice(evmWordStartIndex, constants.EVM_WORD_WIDTH_IN_BYTES), - ), - ) - .padEnd(valuePadding); - if (block instanceof SetCalldataBlock) { - nameStr = `### ${prettyName.padEnd(namePadding)}`; - lineStr = `\n${offsetStr}${valueStr}${nameStr}`; - } else { - nameStr = ` ${prettyName.padEnd(namePadding)}`; - lineStr = `${offsetStr}${valueStr}${nameStr}`; - } - } - // This block has a value that is more than 1 word. - for (let j = constants.EVM_WORD_WIDTH_IN_BYTES; j < size; j += constants.EVM_WORD_WIDTH_IN_BYTES) { - offsetStr = `0x${(offset + j).toString(constants.HEX_BASE)}`.padEnd(offsetPadding); - valueStr = ethUtil - .stripHexPrefix( - ethUtil.bufferToHex(block.toBuffer().slice(j, j + constants.EVM_WORD_WIDTH_IN_BYTES)), - ) - .padEnd(valuePadding); - nameStr = ' '.repeat(namePadding); - lineStr = `${lineStr}\n${offsetStr}${valueStr}${nameStr}`; - } - // Append to hex value - hexValue = `${hexValue}\n${lineStr}`; - offset += size; - } - return hexValue; - } -} diff --git a/packages/utils/src/abi_encoder/calldata/calldata_block.ts b/packages/utils/src/abi_encoder/calldata/calldata_block.ts deleted file mode 100644 index 35bd994e53..0000000000 --- a/packages/utils/src/abi_encoder/calldata/calldata_block.ts +++ /dev/null @@ -1,77 +0,0 @@ -import * as ethUtil from 'ethereumjs-util'; - -export abstract class CalldataBlock { - private readonly _signature: string; - private readonly _parentName: string; - private _name: string; - private _offsetInBytes: number; - private _headerSizeInBytes: number; - private _bodySizeInBytes: number; - - constructor( - name: string, - signature: string, - parentName: string, - headerSizeInBytes: number, - bodySizeInBytes: number, - ) { - this._name = name; - this._signature = signature; - this._parentName = parentName; - this._offsetInBytes = 0; - this._headerSizeInBytes = headerSizeInBytes; - this._bodySizeInBytes = bodySizeInBytes; - } - - protected _setHeaderSize(headerSizeInBytes: number): void { - this._headerSizeInBytes = headerSizeInBytes; - } - - protected _setBodySize(bodySizeInBytes: number): void { - this._bodySizeInBytes = bodySizeInBytes; - } - - protected _setName(name: string): void { - this._name = name; - } - - public getName(): string { - return this._name; - } - - public getParentName(): string { - return this._parentName; - } - - public getSignature(): string { - return this._signature; - } - public getHeaderSizeInBytes(): number { - return this._headerSizeInBytes; - } - - public getBodySizeInBytes(): number { - return this._bodySizeInBytes; - } - - public getSizeInBytes(): number { - return this.getHeaderSizeInBytes() + this.getBodySizeInBytes(); - } - - public getOffsetInBytes(): number { - return this._offsetInBytes; - } - - public setOffset(offsetInBytes: number): void { - this._offsetInBytes = offsetInBytes; - } - - public computeHash(): Buffer { - const rawData = this.getRawData(); - const hash = ethUtil.sha3(rawData); - return hash; - } - - public abstract toBuffer(): Buffer; - public abstract getRawData(): Buffer; -} diff --git a/packages/utils/src/abi_encoder/calldata/iterator.ts b/packages/utils/src/abi_encoder/calldata/iterator.ts deleted file mode 100644 index 90f06c38b2..0000000000 --- a/packages/utils/src/abi_encoder/calldata/iterator.ts +++ /dev/null @@ -1,114 +0,0 @@ -/* tslint:disable max-classes-per-file */ -import * as _ from 'lodash'; - -import { Queue } from '../utils/queue'; - -import { BlobCalldataBlock } from './blocks/blob'; -import { PointerCalldataBlock } from './blocks/pointer'; -import { SetCalldataBlock } from './blocks/set'; -import { CalldataBlock } from './calldata_block'; - -/** - * Iterator class for Calldata Blocks. Blocks follows the order - * they should be put into calldata that is passed to he EVM. - * - * Example #1: - * Let root = Set { - * Blob{} A, - * Pointer { - * Blob{} a - * } B, - * Blob{} C - * } - * It will iterate as follows: [A, B, C, B.a] - * - * Example #2: - * Let root = Set { - * Blob{} A, - * Pointer { - * Blob{} a - * Pointer { - * Blob{} b - * } - * } B, - * Pointer { - * Blob{} c - * } C - * } - * It will iterate as follows: [A, B, C, B.a, B.b, C.c] - */ -abstract class BaseIterator implements Iterable { - protected readonly _root: CalldataBlock; - protected readonly _queue: Queue; - - private static _createQueue(block: CalldataBlock): Queue { - const queue = new Queue(); - // Base case - if (!(block instanceof SetCalldataBlock)) { - queue.pushBack(block); - return queue; - } - // This is a set; add members - const set = block; - _.eachRight(set.getMembers(), (member: CalldataBlock) => { - queue.mergeFront(BaseIterator._createQueue(member)); - }); - // Add children - _.each(set.getMembers(), (member: CalldataBlock) => { - // Traverse child if it is a unique pointer. - // A pointer that is an alias for another pointer is ignored. - if (member instanceof PointerCalldataBlock && member.getAlias() === undefined) { - const dependency = member.getDependency(); - queue.mergeBack(BaseIterator._createQueue(dependency)); - } - }); - // Put set block at the front of the queue - queue.pushFront(set); - return queue; - } - - public constructor(root: CalldataBlock) { - this._root = root; - this._queue = BaseIterator._createQueue(root); - } - - public [Symbol.iterator](): { next: () => IteratorResult } { - return { - next: () => { - const nextBlock = this.nextBlock(); - if (nextBlock !== undefined) { - return { - value: nextBlock, - done: false, - }; - } - return { - done: true, - value: new BlobCalldataBlock('', '', '', Buffer.from('')), - }; - }, - }; - } - - public abstract nextBlock(): CalldataBlock | undefined; -} - -export class CalldataIterator extends BaseIterator { - public constructor(root: CalldataBlock) { - super(root); - } - - public nextBlock(): CalldataBlock | undefined { - return this._queue.popFront(); - } -} - -export class ReverseCalldataIterator extends BaseIterator { - public constructor(root: CalldataBlock) { - super(root); - } - - public nextBlock(): CalldataBlock | undefined { - return this._queue.popBack(); - } -} diff --git a/packages/utils/src/abi_encoder/calldata/raw_calldata.ts b/packages/utils/src/abi_encoder/calldata/raw_calldata.ts deleted file mode 100644 index 3a591bd774..0000000000 --- a/packages/utils/src/abi_encoder/calldata/raw_calldata.ts +++ /dev/null @@ -1,92 +0,0 @@ -import * as ethUtil from 'ethereumjs-util'; -import * as _ from 'lodash'; - -import { constants } from '../utils/constants'; -import { Queue } from '../utils/queue'; - -export class RawCalldata { - private static readonly _INITIAL_OFFSET = 0; - private readonly _value: Buffer; - private readonly _selector: string; - private readonly _scopes: Queue; - private _offset: number; - - public constructor(value: string | Buffer, hasSelector: boolean = true) { - // Sanity check - if (typeof value === 'string' && !_.startsWith(value, '0x')) { - throw new Error(`Expected raw calldata to start with '0x'`); - } - // Construct initial values - this._value = ethUtil.toBuffer(value); - this._selector = '0x'; - this._scopes = new Queue(); - this._scopes.pushBack(RawCalldata._INITIAL_OFFSET); - this._offset = RawCalldata._INITIAL_OFFSET; - // If there's a selector then slice it - if (hasSelector) { - const selectorBuf = this._value.slice(constants.HEX_SELECTOR_LENGTH_IN_BYTES); - this._value = this._value.slice(constants.HEX_SELECTOR_LENGTH_IN_BYTES); - this._selector = ethUtil.bufferToHex(selectorBuf); - } - } - - public popBytes(lengthInBytes: number): Buffer { - const popBegin = this._offset; - const popEnd = popBegin + lengthInBytes; - if (popEnd > this._value.byteLength) { - throw new Error(`Tried to decode beyond the end of calldata`); - } - const value = this._value.slice(popBegin, popEnd); - this.setOffset(popEnd); - return value; - } - - public popWord(): Buffer { - const wordInBytes = 32; - return this.popBytes(wordInBytes); - } - - public popWords(length: number): Buffer { - const wordInBytes = 32; - return this.popBytes(length * wordInBytes); - } - - public readBytes(from: number, to: number): Buffer { - const value = this._value.slice(from, to); - return value; - } - - public setOffset(offsetInBytes: number): void { - this._offset = offsetInBytes; - } - - public startScope(): void { - this._scopes.pushFront(this._offset); - } - - public endScope(): void { - this._scopes.popFront(); - } - - public getOffset(): number { - return this._offset; - } - - public toAbsoluteOffset(relativeOffset: number): number { - const scopeOffset = this._scopes.peekFront(); - if (scopeOffset === undefined) { - throw new Error(`Tried to access undefined scope.`); - } - const absoluteOffset = relativeOffset + scopeOffset; - return absoluteOffset; - } - - public getSelector(): string { - return this._selector; - } - - public getSizeInBytes(): number { - const sizeInBytes = this._value.byteLength; - return sizeInBytes; - } -} diff --git a/packages/utils/src/abi_encoder/evm_data_type_factory.ts b/packages/utils/src/abi_encoder/evm_data_type_factory.ts deleted file mode 100644 index b68be3ea04..0000000000 --- a/packages/utils/src/abi_encoder/evm_data_type_factory.ts +++ /dev/null @@ -1,220 +0,0 @@ -/* tslint:disable max-classes-per-file */ -import { DataItem, MethodAbi } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { generateDataItemFromSignature } from './utils/signature_parser'; - -import { DataType } from './abstract_data_types/data_type'; -import { DataTypeFactory } from './abstract_data_types/interfaces'; -import { AddressDataType } from './evm_data_types/address'; -import { ArrayDataType } from './evm_data_types/array'; -import { BoolDataType } from './evm_data_types/bool'; -import { DynamicBytesDataType } from './evm_data_types/dynamic_bytes'; -import { IntDataType } from './evm_data_types/int'; -import { MethodDataType } from './evm_data_types/method'; -import { PointerDataType } from './evm_data_types/pointer'; -import { StaticBytesDataType } from './evm_data_types/static_bytes'; -import { StringDataType } from './evm_data_types/string'; -import { TupleDataType } from './evm_data_types/tuple'; -import { UIntDataType } from './evm_data_types/uint'; - -export class Address extends AddressDataType { - public constructor(dataItem: DataItem) { - super(dataItem, EvmDataTypeFactory.getInstance()); - } -} - -export class Bool extends BoolDataType { - public constructor(dataItem: DataItem) { - super(dataItem, EvmDataTypeFactory.getInstance()); - } -} - -export class Int extends IntDataType { - public constructor(dataItem: DataItem) { - super(dataItem, EvmDataTypeFactory.getInstance()); - } -} - -export class UInt extends UIntDataType { - public constructor(dataItem: DataItem) { - super(dataItem, EvmDataTypeFactory.getInstance()); - } -} - -export class StaticBytes extends StaticBytesDataType { - public constructor(dataItem: DataItem) { - super(dataItem, EvmDataTypeFactory.getInstance()); - } -} - -export class DynamicBytes extends DynamicBytesDataType { - public constructor(dataItem: DataItem) { - super(dataItem, EvmDataTypeFactory.getInstance()); - } -} - -export class String extends StringDataType { - public constructor(dataItem: DataItem) { - super(dataItem, EvmDataTypeFactory.getInstance()); - } -} - -export class Pointer extends PointerDataType { - public constructor(destDataType: DataType, parentDataType: DataType) { - super(destDataType, parentDataType, EvmDataTypeFactory.getInstance()); - } -} - -export class Tuple extends TupleDataType { - public constructor(dataItem: DataItem) { - super(dataItem, EvmDataTypeFactory.getInstance()); - } -} - -export class Array extends ArrayDataType { - public constructor(dataItem: DataItem) { - super(dataItem, EvmDataTypeFactory.getInstance()); - } -} - -export class Method extends MethodDataType { - public constructor(abi: MethodAbi) { - super(abi, EvmDataTypeFactory.getInstance()); - } -} - -/* tslint:disable no-construct */ -export class EvmDataTypeFactory implements DataTypeFactory { - private static _instance: DataTypeFactory; - - public static getInstance(): DataTypeFactory { - if (!EvmDataTypeFactory._instance) { - EvmDataTypeFactory._instance = new EvmDataTypeFactory(); - } - return EvmDataTypeFactory._instance; - } - - /* tslint:disable prefer-function-over-method */ - public create(dataItem: DataItem, parentDataType?: DataType): DataType { - // Create data type - let dataType: undefined | DataType; - if (Array.matchType(dataItem.type)) { - dataType = new Array(dataItem); - } else if (Address.matchType(dataItem.type)) { - dataType = new Address(dataItem); - } else if (Bool.matchType(dataItem.type)) { - dataType = new Bool(dataItem); - } else if (Int.matchType(dataItem.type)) { - dataType = new Int(dataItem); - } else if (UInt.matchType(dataItem.type)) { - dataType = new UInt(dataItem); - } else if (StaticBytes.matchType(dataItem.type)) { - dataType = new StaticBytes(dataItem); - } else if (Tuple.matchType(dataItem.type)) { - dataType = new Tuple(dataItem); - } else if (DynamicBytes.matchType(dataItem.type)) { - dataType = new DynamicBytes(dataItem); - } else if (String.matchType(dataItem.type)) { - dataType = new String(dataItem); - } - // @TODO: DataTypeement Fixed/UFixed types - if (dataType === undefined) { - throw new Error(`Unrecognized data type: '${dataItem.type}'`); - } else if (parentDataType !== undefined && !dataType.isStatic()) { - const pointerToDataType = new Pointer(dataType, parentDataType); - return pointerToDataType; - } - return dataType; - } - /* tslint:enable prefer-function-over-method */ - - private constructor() {} -} - -/** - * Convenience function for creating a DataType from different inputs. - * @param input A single or set of DataItem or a signature for an EVM data type. - * @return DataType corresponding to input. - */ -export function create(input: DataItem | DataItem[] | string): DataType { - const dataItem = consolidateDataItemsIntoSingle(input); - const dataType = EvmDataTypeFactory.getInstance().create(dataItem); - return dataType; -} - -/** - * Convenience function to aggregate a single input or a set of inputs into a single DataItem. - * An array of data items is grouped into a single tuple. - * @param input A single data item; a set of data items; a signature. - * @return A single data item corresponding to input. - */ -function consolidateDataItemsIntoSingle(input: DataItem | DataItem[] | string): DataItem { - let dataItem: DataItem; - if (_.isArray(input)) { - const dataItems = input as DataItem[]; - dataItem = { - name: '', - type: 'tuple', - components: dataItems, - }; - } else { - dataItem = _.isString(input) ? generateDataItemFromSignature(input) : (input as DataItem); - } - return dataItem; -} - -/** - * Convenience function for creating a Method encoder from different inputs. - * @param methodName name of method. - * @param input A single data item; a set of data items; a signature; or an array of signatures (optional). - * @param output A single data item; a set of data items; a signature; or an array of signatures (optional). - * @return Method corresponding to input. - */ -export function createMethod( - methodName: string, - input?: DataItem | DataItem[] | string | string[], - output?: DataItem | DataItem[] | string | string[], -): Method { - const methodInput = input === undefined ? [] : consolidateDataItemsIntoArray(input); - const methodOutput = output === undefined ? [] : consolidateDataItemsIntoArray(output); - const methodAbi: MethodAbi = { - name: methodName, - inputs: methodInput, - outputs: methodOutput, - type: 'function', - // default fields not used by ABI - constant: false, - payable: false, - stateMutability: 'nonpayable', - }; - const dataType = new Method(methodAbi); - return dataType; -} - -/** - * Convenience function that aggregates a single input or a set of inputs into an array of DataItems. - * @param input A single data item; a set of data items; a signature; or an array of signatures. - * @return Array of data items corresponding to input. - */ -function consolidateDataItemsIntoArray(input: DataItem | DataItem[] | string | string[]): DataItem[] { - let dataItems: DataItem[]; - if (_.isArray(input) && _.isEmpty(input)) { - dataItems = []; - } else if (_.isArray(input) && _.isString(input[0])) { - dataItems = []; - _.each(input as string[], (signature: string) => { - const dataItem = generateDataItemFromSignature(signature); - dataItems.push(dataItem); - }); - } else if (_.isArray(input)) { - dataItems = input as DataItem[]; - } else if (typeof input === 'string') { - const dataItem = generateDataItemFromSignature(input); - dataItems = [dataItem]; - } else { - dataItems = [input as DataItem]; - } - return dataItems; -} -/* tslint:enable no-construct */ diff --git a/packages/utils/src/abi_encoder/evm_data_types/address.ts b/packages/utils/src/abi_encoder/evm_data_types/address.ts deleted file mode 100644 index 7e92d3888b..0000000000 --- a/packages/utils/src/abi_encoder/evm_data_types/address.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { DataItem, SolidityTypes } from 'ethereum-types'; -import * as ethUtil from 'ethereumjs-util'; -import * as _ from 'lodash'; - -import { DataTypeFactory } from '../abstract_data_types/interfaces'; -import { AbstractBlobDataType } from '../abstract_data_types/types/blob'; -import { RawCalldata } from '../calldata/raw_calldata'; -import { constants } from '../utils/constants'; - -export class AddressDataType extends AbstractBlobDataType { - private static readonly _SIZE_KNOWN_AT_COMPILE_TIME: boolean = true; - private static readonly _ADDRESS_SIZE_IN_BYTES = 20; - private static readonly _DECODED_ADDRESS_OFFSET_IN_BYTES = - constants.EVM_WORD_WIDTH_IN_BYTES - AddressDataType._ADDRESS_SIZE_IN_BYTES; - private static readonly _DEFAULT_VALUE = '0x0000000000000000000000000000000000000000'; - - public static matchType(type: string): boolean { - return type === SolidityTypes.Address; - } - - public constructor(dataItem: DataItem, dataTypeFactory: DataTypeFactory) { - super(dataItem, dataTypeFactory, AddressDataType._SIZE_KNOWN_AT_COMPILE_TIME); - if (!AddressDataType.matchType(dataItem.type)) { - throw new Error(`Tried to instantiate Address with bad input: ${dataItem}`); - } - } - - // Disable prefer-function-over-method for inherited abstract methods. - /* tslint:disable prefer-function-over-method */ - public encodeValue(value: string): Buffer { - if (!ethUtil.isValidAddress(value)) { - throw new Error(`Invalid address: '${value}'`); - } - const valueBuf = ethUtil.toBuffer(value); - const encodedValueBuf = ethUtil.setLengthLeft(valueBuf, constants.EVM_WORD_WIDTH_IN_BYTES); - return encodedValueBuf; - } - - public decodeValue(calldata: RawCalldata): string { - const valueBufPadded = calldata.popWord(); - const valueBuf = valueBufPadded.slice(AddressDataType._DECODED_ADDRESS_OFFSET_IN_BYTES); - const value = ethUtil.bufferToHex(valueBuf); - const valueLowercase = _.toLower(value); - return valueLowercase; - } - - public getDefaultValue(): string { - return AddressDataType._DEFAULT_VALUE; - } - - public getSignatureType(): string { - return SolidityTypes.Address; - } - /* tslint:enable prefer-function-over-method */ -} diff --git a/packages/utils/src/abi_encoder/evm_data_types/array.ts b/packages/utils/src/abi_encoder/evm_data_types/array.ts deleted file mode 100644 index 58a7e3f4c8..0000000000 --- a/packages/utils/src/abi_encoder/evm_data_types/array.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { DataItem } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { DataTypeFactory } from '../abstract_data_types/interfaces'; -import { AbstractSetDataType } from '../abstract_data_types/types/set'; -import { constants } from '../utils/constants'; - -export class ArrayDataType extends AbstractSetDataType { - private static readonly _MATCHER = RegExp('^(.+)\\[([0-9]*)\\]$'); - private readonly _elementType: string; - - public static matchType(type: string): boolean { - return ArrayDataType._MATCHER.test(type); - } - - private static _decodeElementTypeAndLengthFromType(type: string): [string, undefined | number] { - const matches = ArrayDataType._MATCHER.exec(type); - if (matches === null || matches.length !== 3) { - throw new Error(`Could not parse array: ${type}`); - } else if (matches[1] === undefined) { - throw new Error(`Could not parse array type: ${type}`); - } else if (matches[2] === undefined) { - throw new Error(`Could not parse array length: ${type}`); - } - const arrayElementType = matches[1]; - const arrayLength = _.isEmpty(matches[2]) ? undefined : parseInt(matches[2], constants.DEC_BASE); - return [arrayElementType, arrayLength]; - } - - public constructor(dataItem: DataItem, dataTypeFactory: DataTypeFactory) { - // Construct parent - const isArray = true; - const [arrayElementType, arrayLength] = ArrayDataType._decodeElementTypeAndLengthFromType(dataItem.type); - super(dataItem, dataTypeFactory, isArray, arrayLength, arrayElementType); - // Set array properties - this._elementType = arrayElementType; - } - - public getSignatureType(): string { - return this._computeSignature(false); - } - - public getSignature(isDetailed?: boolean): string { - if (_.isEmpty(this.getDataItem().name) || !isDetailed) { - return this.getSignatureType(); - } - const name = this.getDataItem().name; - const lastIndexOfScopeDelimiter = name.lastIndexOf('.'); - const isScopedName = lastIndexOfScopeDelimiter !== undefined && lastIndexOfScopeDelimiter > 0; - const shortName = isScopedName ? name.substr((lastIndexOfScopeDelimiter as number) + 1) : name; - const detailedSignature = `${shortName} ${this._computeSignature(isDetailed)}`; - return detailedSignature; - } - - private _computeSignature(isDetailed?: boolean): string { - // Compute signature for a single array element - const elementDataItem: DataItem = { - type: this._elementType, - name: '', - }; - const elementComponents = this.getDataItem().components; - if (elementComponents !== undefined) { - elementDataItem.components = elementComponents; - } - const elementDataType = this.getFactory().create(elementDataItem); - const elementSignature = elementDataType.getSignature(isDetailed); - // Construct signature for array of type `element` - if (this._arrayLength === undefined) { - return `${elementSignature}[]`; - } else { - return `${elementSignature}[${this._arrayLength}]`; - } - } -} diff --git a/packages/utils/src/abi_encoder/evm_data_types/bool.ts b/packages/utils/src/abi_encoder/evm_data_types/bool.ts deleted file mode 100644 index 24887c509c..0000000000 --- a/packages/utils/src/abi_encoder/evm_data_types/bool.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { DataItem, SolidityTypes } from 'ethereum-types'; -import * as ethUtil from 'ethereumjs-util'; -import * as _ from 'lodash'; - -import { BigNumber } from '../../configured_bignumber'; -import { DataTypeFactory } from '../abstract_data_types/interfaces'; -import { AbstractBlobDataType } from '../abstract_data_types/types/blob'; -import { RawCalldata } from '../calldata/raw_calldata'; -import { constants } from '../utils/constants'; - -export class BoolDataType extends AbstractBlobDataType { - private static readonly _SIZE_KNOWN_AT_COMPILE_TIME: boolean = true; - private static readonly _DEFAULT_VALUE: boolean = false; - - public static matchType(type: string): boolean { - return type === SolidityTypes.Bool; - } - - public constructor(dataItem: DataItem, dataTypeFactory: DataTypeFactory) { - super(dataItem, dataTypeFactory, BoolDataType._SIZE_KNOWN_AT_COMPILE_TIME); - if (!BoolDataType.matchType(dataItem.type)) { - throw new Error(`Tried to instantiate Bool with bad input: ${dataItem}`); - } - } - - // Disable prefer-function-over-method for inherited abstract methods. - /* tslint:disable prefer-function-over-method */ - public encodeValue(value: boolean): Buffer { - const encodedValue = value ? '0x1' : '0x0'; - const encodedValueBuf = ethUtil.setLengthLeft( - ethUtil.toBuffer(encodedValue), - constants.EVM_WORD_WIDTH_IN_BYTES, - ); - return encodedValueBuf; - } - - public decodeValue(calldata: RawCalldata): boolean { - const valueBuf = calldata.popWord(); - const valueHex = ethUtil.bufferToHex(valueBuf); - // Hack @hysz: there are some cases where `false` is encoded as 0x instead of 0x0. - const valueNumber = valueHex === '0x' ? new BigNumber(0) : new BigNumber(valueHex, constants.HEX_BASE); - if (!(valueNumber.isEqualTo(0) || valueNumber.isEqualTo(1))) { - throw new Error(`Failed to decode boolean. Expected 0x0 or 0x1, got ${valueHex}`); - } - /* tslint:disable boolean-naming */ - const value: boolean = !valueNumber.isEqualTo(0); - /* tslint:enable boolean-naming */ - return value; - } - - public getDefaultValue(): boolean { - return BoolDataType._DEFAULT_VALUE; - } - - public getSignatureType(): string { - return SolidityTypes.Bool; - } - /* tslint:enable prefer-function-over-method */ -} diff --git a/packages/utils/src/abi_encoder/evm_data_types/dynamic_bytes.ts b/packages/utils/src/abi_encoder/evm_data_types/dynamic_bytes.ts deleted file mode 100644 index 9b1415a834..0000000000 --- a/packages/utils/src/abi_encoder/evm_data_types/dynamic_bytes.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { DataItem, SolidityTypes } from 'ethereum-types'; -import * as ethUtil from 'ethereumjs-util'; -import * as _ from 'lodash'; - -import { DataTypeFactory } from '../abstract_data_types/interfaces'; -import { AbstractBlobDataType } from '../abstract_data_types/types/blob'; -import { RawCalldata } from '../calldata/raw_calldata'; -import { constants } from '../utils/constants'; - -export class DynamicBytesDataType extends AbstractBlobDataType { - private static readonly _SIZE_KNOWN_AT_COMPILE_TIME: boolean = false; - private static readonly _DEFAULT_VALUE = '0x'; - - public static matchType(type: string): boolean { - return type === SolidityTypes.Bytes; - } - - private static _sanityCheckValue(value: string | Buffer): void { - if (typeof value !== 'string') { - return; - } - if (!_.startsWith(value, '0x')) { - throw new Error(`Tried to encode non-hex value. Value must include '0x' prefix.`); - } else if (value.length % 2 !== 0) { - throw new Error(`Tried to assign ${value}, which is contains a half-byte. Use full bytes only.`); - } - } - - public constructor(dataItem: DataItem, dataTypeFactory: DataTypeFactory) { - super(dataItem, dataTypeFactory, DynamicBytesDataType._SIZE_KNOWN_AT_COMPILE_TIME); - if (!DynamicBytesDataType.matchType(dataItem.type)) { - throw new Error(`Tried to instantiate Dynamic Bytes with bad input: ${dataItem}`); - } - } - - // Disable prefer-function-over-method for inherited abstract methods. - /* tslint:disable prefer-function-over-method */ - public encodeValue(value: string | Buffer): Buffer { - // Encoded value is of the form: , with each field padded to be word-aligned. - // 1/3 Construct the length - const valueBuf = ethUtil.toBuffer(value); - const wordsToStoreValuePadded = Math.ceil(valueBuf.byteLength / constants.EVM_WORD_WIDTH_IN_BYTES); - const bytesToStoreValuePadded = wordsToStoreValuePadded * constants.EVM_WORD_WIDTH_IN_BYTES; - const lengthBuf = ethUtil.toBuffer(valueBuf.byteLength); - const lengthBufPadded = ethUtil.setLengthLeft(lengthBuf, constants.EVM_WORD_WIDTH_IN_BYTES); - // 2/3 Construct the value - DynamicBytesDataType._sanityCheckValue(value); - const valueBufPadded = ethUtil.setLengthRight(valueBuf, bytesToStoreValuePadded); - // 3/3 Combine length and value - const encodedValue = Buffer.concat([lengthBufPadded, valueBufPadded]); - return encodedValue; - } - - public decodeValue(calldata: RawCalldata): string { - // Encoded value is of the form: , with each field padded to be word-aligned. - // 1/2 Decode length - const lengthBuf = calldata.popWord(); - const lengthHex = ethUtil.bufferToHex(lengthBuf); - const length = parseInt(lengthHex, constants.HEX_BASE); - // 2/2 Decode value - const wordsToStoreValuePadded = Math.ceil(length / constants.EVM_WORD_WIDTH_IN_BYTES); - const valueBufPadded = calldata.popWords(wordsToStoreValuePadded); - const valueBuf = valueBufPadded.slice(0, length); - const value = ethUtil.bufferToHex(valueBuf); - DynamicBytesDataType._sanityCheckValue(value); - return value; - } - - public getDefaultValue(): string { - return DynamicBytesDataType._DEFAULT_VALUE; - } - - public getSignatureType(): string { - return SolidityTypes.Bytes; - } - /* tslint:enable prefer-function-over-method */ -} diff --git a/packages/utils/src/abi_encoder/evm_data_types/int.ts b/packages/utils/src/abi_encoder/evm_data_types/int.ts deleted file mode 100644 index ff7d71552f..0000000000 --- a/packages/utils/src/abi_encoder/evm_data_types/int.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { DataItem, SolidityTypes } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { BigNumber } from '../../configured_bignumber'; -import { DataTypeFactory } from '../abstract_data_types/interfaces'; -import { AbstractBlobDataType } from '../abstract_data_types/types/blob'; -import { RawCalldata } from '../calldata/raw_calldata'; -import { constants } from '../utils/constants'; -import * as EncoderMath from '../utils/math'; - -export class IntDataType extends AbstractBlobDataType { - private static readonly _MATCHER = RegExp( - '^int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256){0,1}$', - ); - private static readonly _SIZE_KNOWN_AT_COMPILE_TIME: boolean = true; - private static readonly _MAX_WIDTH: number = 256; - private static readonly _DEFAULT_WIDTH: number = IntDataType._MAX_WIDTH; - private static readonly _DEFAULT_VALUE = new BigNumber(0); - private readonly _width: number; - private readonly _minValue: BigNumber; - private readonly _maxValue: BigNumber; - - public static matchType(type: string): boolean { - return IntDataType._MATCHER.test(type); - } - - private static _decodeWidthFromType(type: string): number { - const matches = IntDataType._MATCHER.exec(type); - const width = - matches !== null && matches.length === 2 && matches[1] !== undefined - ? parseInt(matches[1], constants.DEC_BASE) - : IntDataType._DEFAULT_WIDTH; - return width; - } - - public constructor(dataItem: DataItem, dataTypeFactory: DataTypeFactory) { - super(dataItem, dataTypeFactory, IntDataType._SIZE_KNOWN_AT_COMPILE_TIME); - if (!IntDataType.matchType(dataItem.type)) { - throw new Error(`Tried to instantiate Int with bad input: ${dataItem}`); - } - this._width = IntDataType._decodeWidthFromType(dataItem.type); - this._minValue = new BigNumber(2).exponentiatedBy(this._width - 1).times(-1); - this._maxValue = new BigNumber(2).exponentiatedBy(this._width - 1).minus(1); - } - - public encodeValue(value: BigNumber | string | number): Buffer { - const encodedValue = EncoderMath.safeEncodeNumericValue(value, this._minValue, this._maxValue); - return encodedValue; - } - - public decodeValue(calldata: RawCalldata): BigNumber | number { - const valueBuf = calldata.popWord(); - const value = EncoderMath.safeDecodeNumericValue(valueBuf, this._minValue, this._maxValue); - if (this._width === constants.NUMBER_OF_BYTES_IN_INT8) { - return value.toNumber(); - } - return value; - } - - public getDefaultValue(): BigNumber | number { - const defaultValue = IntDataType._DEFAULT_VALUE; - if (this._width === constants.NUMBER_OF_BYTES_IN_INT8) { - return defaultValue.toNumber(); - } - return defaultValue; - } - - public getSignatureType(): string { - return `${SolidityTypes.Int}${this._width}`; - } -} diff --git a/packages/utils/src/abi_encoder/evm_data_types/method.ts b/packages/utils/src/abi_encoder/evm_data_types/method.ts deleted file mode 100644 index e50009d344..0000000000 --- a/packages/utils/src/abi_encoder/evm_data_types/method.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { DataItem, MethodAbi } from 'ethereum-types'; -import * as ethUtil from 'ethereumjs-util'; -import * as _ from 'lodash'; - -import { DataType } from '../abstract_data_types/data_type'; -import { DataTypeFactory } from '../abstract_data_types/interfaces'; -import { AbstractSetDataType } from '../abstract_data_types/types/set'; -import { constants } from '../utils/constants'; -import { DecodingRules, EncodingRules } from '../utils/rules'; - -import { TupleDataType } from './tuple'; - -export class MethodDataType extends AbstractSetDataType { - private readonly _methodSignature: string; - private readonly _methodSelector: string; - private readonly _returnDataType: DataType; - - public constructor(abi: MethodAbi, dataTypeFactory: DataTypeFactory) { - const methodDataItem = { type: 'method', name: abi.name, components: abi.inputs }; - super(methodDataItem, dataTypeFactory); - this._methodSignature = this._computeSignature(); - this._methodSelector = this._computeSelector(); - const returnDataItem: DataItem = { type: 'tuple', name: abi.name, components: abi.outputs }; - this._returnDataType = new TupleDataType(returnDataItem, this.getFactory()); - } - - public encode(value: any, rules?: EncodingRules): string { - const calldata = super.encode(value, rules, this._methodSelector); - return calldata; - } - - public decode(calldata: string, rules?: Partial): any[] | object { - const value = super.decode(calldata, rules, this._methodSelector); - return value; - } - - public strictDecode(calldata: string, rules?: Partial): T { - const value = super.decode(calldata, { ...rules, isStrictMode: true }, this._methodSelector); - const valueAsArray: any = _.isObject(value) ? _.values(value) : [value]; - switch (valueAsArray.length) { - case 0: - return undefined as any; - case 1: - return valueAsArray[0]; - default: - return valueAsArray; - } - } - - public encodeReturnValues(value: any, rules?: EncodingRules): string { - const returnData = this._returnDataType.encode(value, rules); - return returnData; - } - - public decodeReturnValues(returndata: string, rules?: Partial): any { - const returnValues = this._returnDataType.decode(returndata, rules); - return returnValues; - } - - public strictDecodeReturnValue(returndata: string, rules?: Partial): T { - const returnValues = this._returnDataType.decode(returndata, { ...rules, isStrictMode: true }); - const returnValuesAsArray: any = _.isObject(returnValues) ? _.values(returnValues) : [returnValues]; - switch (returnValuesAsArray.length) { - case 0: - return undefined as any; - case 1: - return returnValuesAsArray[0]; - default: - return returnValuesAsArray; - } - } - - public getSignatureType(): string { - return this._methodSignature; - } - - public getSelector(): string { - return this._methodSelector; - } - - public getReturnValueDataItem(): DataItem { - const returnValueDataItem = this._returnDataType.getDataItem(); - return returnValueDataItem; - } - - private _computeSignature(): string { - const memberSignature = this._computeSignatureOfMembers(); - const methodSignature = `${this.getDataItem().name}${memberSignature}`; - return methodSignature; - } - - private _computeSelector(): string { - const signature = this._computeSignature(); - const selector = ethUtil.bufferToHex( - ethUtil.toBuffer( - ethUtil - .sha3(signature) - .slice(constants.HEX_SELECTOR_BYTE_OFFSET_IN_CALLDATA, constants.HEX_SELECTOR_LENGTH_IN_BYTES), - ), - ); - return selector; - } -} diff --git a/packages/utils/src/abi_encoder/evm_data_types/pointer.ts b/packages/utils/src/abi_encoder/evm_data_types/pointer.ts deleted file mode 100644 index 50f68f5ea8..0000000000 --- a/packages/utils/src/abi_encoder/evm_data_types/pointer.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { DataItem } from 'ethereum-types'; - -import { DataType } from '../abstract_data_types/data_type'; -import { DataTypeFactory } from '../abstract_data_types/interfaces'; -import { AbstractPointerDataType } from '../abstract_data_types/types/pointer'; - -export class PointerDataType extends AbstractPointerDataType { - constructor(destDataType: DataType, parentDataType: DataType, dataTypeFactory: DataTypeFactory) { - const destDataItem = destDataType.getDataItem(); - const dataItem: DataItem = { name: `ptr<${destDataItem.name}>`, type: `ptr<${destDataItem.type}>` }; - super(dataItem, dataTypeFactory, destDataType, parentDataType); - } - - public getSignatureType(): string { - return this._destination.getSignature(false); - } - - public getSignature(isDetailed?: boolean): string { - return this._destination.getSignature(isDetailed); - } - - public getDefaultValue(): any { - const defaultValue = this._destination.getDefaultValue(); - return defaultValue; - } -} diff --git a/packages/utils/src/abi_encoder/evm_data_types/static_bytes.ts b/packages/utils/src/abi_encoder/evm_data_types/static_bytes.ts deleted file mode 100644 index 2092533f4a..0000000000 --- a/packages/utils/src/abi_encoder/evm_data_types/static_bytes.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { DataItem, SolidityTypes } from 'ethereum-types'; -import * as ethUtil from 'ethereumjs-util'; -import * as _ from 'lodash'; - -import { DataTypeFactory } from '../abstract_data_types/interfaces'; -import { AbstractBlobDataType } from '../abstract_data_types/types/blob'; -import { RawCalldata } from '../calldata/raw_calldata'; -import { constants } from '../utils/constants'; - -export class StaticBytesDataType extends AbstractBlobDataType { - private static readonly _SIZE_KNOWN_AT_COMPILE_TIME: boolean = true; - private static readonly _MATCHER = RegExp( - '^(byte|bytes(1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31|32))$', - ); - private static readonly _DEFAULT_WIDTH = 1; - private readonly _width: number; - - public static matchType(type: string): boolean { - return StaticBytesDataType._MATCHER.test(type); - } - - private static _decodeWidthFromType(type: string): number { - const matches = StaticBytesDataType._MATCHER.exec(type); - const width = - matches !== null && matches.length === 3 && matches[2] !== undefined - ? parseInt(matches[2], constants.DEC_BASE) - : StaticBytesDataType._DEFAULT_WIDTH; - return width; - } - - public constructor(dataItem: DataItem, dataTypeFactory: DataTypeFactory) { - super(dataItem, dataTypeFactory, StaticBytesDataType._SIZE_KNOWN_AT_COMPILE_TIME); - if (!StaticBytesDataType.matchType(dataItem.type)) { - throw new Error(`Tried to instantiate Static Bytes with bad input: ${dataItem}`); - } - this._width = StaticBytesDataType._decodeWidthFromType(dataItem.type); - } - - public getSignatureType(): string { - // Note that `byte` reduces to `bytes1` - return `${SolidityTypes.Bytes}${this._width}`; - } - - public encodeValue(value: string | Buffer): Buffer { - // 1/2 Convert value into a buffer and do bounds checking - this._sanityCheckValue(value); - const valueBuf = ethUtil.toBuffer(value); - // 2/2 Store value as hex - const valuePadded = ethUtil.setLengthRight(valueBuf, constants.EVM_WORD_WIDTH_IN_BYTES); - return valuePadded; - } - - public decodeValue(calldata: RawCalldata): string { - const valueBufPadded = calldata.popWord(); - const valueBuf = valueBufPadded.slice(0, this._width); - const value = ethUtil.bufferToHex(valueBuf); - this._sanityCheckValue(value); - return value; - } - - public getDefaultValue(): string { - const valueBufPadded = constants.EMPTY_EVM_WORD_BUFFER; - const valueBuf = valueBufPadded.slice(0, this._width); - const value = ethUtil.bufferToHex(valueBuf); - return value; - } - - private _sanityCheckValue(value: string | Buffer): void { - if (typeof value === 'string') { - if (!_.startsWith(value, '0x')) { - throw new Error(`Tried to encode non-hex value. Value must include '0x' prefix.`); - } else if (value.length % 2 !== 0) { - throw new Error(`Tried to assign ${value}, which is contains a half-byte. Use full bytes only.`); - } - } - const valueBuf = ethUtil.toBuffer(value); - if (valueBuf.byteLength > this._width) { - throw new Error( - `Tried to assign ${value} (${ - valueBuf.byteLength - } bytes), which exceeds max bytes that can be stored in a ${this.getSignature()}`, - ); - } - } -} diff --git a/packages/utils/src/abi_encoder/evm_data_types/string.ts b/packages/utils/src/abi_encoder/evm_data_types/string.ts deleted file mode 100644 index e19fa159c7..0000000000 --- a/packages/utils/src/abi_encoder/evm_data_types/string.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { DataItem, SolidityTypes } from 'ethereum-types'; -import * as ethUtil from 'ethereumjs-util'; -import * as _ from 'lodash'; - -import { DataTypeFactory } from '../abstract_data_types/interfaces'; -import { AbstractBlobDataType } from '../abstract_data_types/types/blob'; -import { RawCalldata } from '../calldata/raw_calldata'; -import { constants } from '../utils/constants'; - -export class StringDataType extends AbstractBlobDataType { - private static readonly _SIZE_KNOWN_AT_COMPILE_TIME: boolean = false; - private static readonly _DEFAULT_VALUE = ''; - - public static matchType(type: string): boolean { - return type === SolidityTypes.String; - } - - public constructor(dataItem: DataItem, dataTypeFactory: DataTypeFactory) { - super(dataItem, dataTypeFactory, StringDataType._SIZE_KNOWN_AT_COMPILE_TIME); - if (!StringDataType.matchType(dataItem.type)) { - throw new Error(`Tried to instantiate String with bad input: ${dataItem}`); - } - } - - // Disable prefer-function-over-method for inherited abstract methods. - /* tslint:disable prefer-function-over-method */ - public encodeValue(value: string): Buffer { - // Encoded value is of the form: , with each field padded to be word-aligned. - // 1/3 Construct the value - const valueBuf = Buffer.from(value); - const valueLengthInBytes = valueBuf.byteLength; - const wordsToStoreValuePadded = Math.ceil(valueLengthInBytes / constants.EVM_WORD_WIDTH_IN_BYTES); - const bytesToStoreValuePadded = wordsToStoreValuePadded * constants.EVM_WORD_WIDTH_IN_BYTES; - const valueBufPadded = ethUtil.setLengthRight(valueBuf, bytesToStoreValuePadded); - // 2/3 Construct the length - const lengthBuf = ethUtil.toBuffer(valueLengthInBytes); - const lengthBufPadded = ethUtil.setLengthLeft(lengthBuf, constants.EVM_WORD_WIDTH_IN_BYTES); - // 3/3 Combine length and value - const encodedValue = Buffer.concat([lengthBufPadded, valueBufPadded]); - return encodedValue; - } - - public decodeValue(calldata: RawCalldata): string { - // Encoded value is of the form: , with each field padded to be word-aligned. - // 1/2 Decode length - const lengthBufPadded = calldata.popWord(); - const lengthHexPadded = ethUtil.bufferToHex(lengthBufPadded); - const length = parseInt(lengthHexPadded, constants.HEX_BASE); - // 2/2 Decode value - const wordsToStoreValuePadded = Math.ceil(length / constants.EVM_WORD_WIDTH_IN_BYTES); - const valueBufPadded = calldata.popWords(wordsToStoreValuePadded); - const valueBuf = valueBufPadded.slice(0, length); - const value = valueBuf.toString('UTF-8'); - return value; - } - - public getDefaultValue(): string { - return StringDataType._DEFAULT_VALUE; - } - - public getSignatureType(): string { - return SolidityTypes.String; - } - /* tslint:enable prefer-function-over-method */ -} diff --git a/packages/utils/src/abi_encoder/evm_data_types/tuple.ts b/packages/utils/src/abi_encoder/evm_data_types/tuple.ts deleted file mode 100644 index 6325c8fa48..0000000000 --- a/packages/utils/src/abi_encoder/evm_data_types/tuple.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { DataItem, SolidityTypes } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { DataTypeFactory } from '../abstract_data_types/interfaces'; -import { AbstractSetDataType } from '../abstract_data_types/types/set'; - -export class TupleDataType extends AbstractSetDataType { - public static matchType(type: string): boolean { - return type === SolidityTypes.Tuple; - } - - public constructor(dataItem: DataItem, dataTypeFactory: DataTypeFactory) { - super(dataItem, dataTypeFactory); - if (!TupleDataType.matchType(dataItem.type)) { - throw new Error(`Tried to instantiate Tuple with bad input: ${dataItem}`); - } - } - - public getSignatureType(): string { - return this._computeSignatureOfMembers(false); - } - - public getSignature(isDetailed?: boolean): string { - if (_.isEmpty(this.getDataItem().name) || !isDetailed) { - return this.getSignatureType(); - } - const name = this.getDataItem().name; - const lastIndexOfScopeDelimiter = name.lastIndexOf('.'); - const isScopedName = lastIndexOfScopeDelimiter !== undefined && lastIndexOfScopeDelimiter > 0; - const shortName = isScopedName ? name.substr((lastIndexOfScopeDelimiter as number) + 1) : name; - const detailedSignature = `${shortName} ${this._computeSignatureOfMembers(isDetailed)}`; - return detailedSignature; - } -} diff --git a/packages/utils/src/abi_encoder/evm_data_types/uint.ts b/packages/utils/src/abi_encoder/evm_data_types/uint.ts deleted file mode 100644 index 153da7f7f5..0000000000 --- a/packages/utils/src/abi_encoder/evm_data_types/uint.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { DataItem, SolidityTypes } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { BigNumber } from '../../configured_bignumber'; -import { DataTypeFactory } from '../abstract_data_types/interfaces'; -import { AbstractBlobDataType } from '../abstract_data_types/types/blob'; -import { RawCalldata } from '../calldata/raw_calldata'; -import { constants } from '../utils/constants'; -import * as EncoderMath from '../utils/math'; - -export class UIntDataType extends AbstractBlobDataType { - private static readonly _MATCHER = RegExp( - '^uint(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256){0,1}$', - ); - private static readonly _SIZE_KNOWN_AT_COMPILE_TIME: boolean = true; - private static readonly _MAX_WIDTH: number = 256; - private static readonly _DEFAULT_WIDTH: number = UIntDataType._MAX_WIDTH; - private static readonly _MIN_VALUE = new BigNumber(0); - private static readonly _DEFAULT_VALUE = new BigNumber(0); - private readonly _width: number; - private readonly _maxValue: BigNumber; - - public static matchType(type: string): boolean { - return UIntDataType._MATCHER.test(type); - } - - private static _decodeWidthFromType(type: string): number { - const matches = UIntDataType._MATCHER.exec(type); - const width = - matches !== null && matches.length === 2 && matches[1] !== undefined - ? parseInt(matches[1], constants.DEC_BASE) - : UIntDataType._DEFAULT_WIDTH; - return width; - } - - public constructor(dataItem: DataItem, dataTypeFactory: DataTypeFactory) { - super(dataItem, dataTypeFactory, UIntDataType._SIZE_KNOWN_AT_COMPILE_TIME); - if (!UIntDataType.matchType(dataItem.type)) { - throw new Error(`Tried to instantiate UInt with bad input: ${dataItem}`); - } - this._width = UIntDataType._decodeWidthFromType(dataItem.type); - this._maxValue = new BigNumber(2).exponentiatedBy(this._width).minus(1); - } - - public encodeValue(value: BigNumber | string | number): Buffer { - const encodedValue = EncoderMath.safeEncodeNumericValue(value, UIntDataType._MIN_VALUE, this._maxValue); - return encodedValue; - } - - public decodeValue(calldata: RawCalldata): BigNumber | number { - const valueBuf = calldata.popWord(); - const value = EncoderMath.safeDecodeNumericValue(valueBuf, UIntDataType._MIN_VALUE, this._maxValue); - if (this._width === constants.NUMBER_OF_BYTES_IN_UINT8) { - return value.toNumber(); - } - return value; - } - - public getDefaultValue(): BigNumber | number { - const defaultValue = UIntDataType._DEFAULT_VALUE; - if (this._width === constants.NUMBER_OF_BYTES_IN_UINT8) { - return defaultValue.toNumber(); - } - return defaultValue; - } - - public getSignatureType(): string { - return `${SolidityTypes.Uint}${this._width}`; - } -} diff --git a/packages/utils/src/abi_encoder/index.ts b/packages/utils/src/abi_encoder/index.ts deleted file mode 100644 index 976bac8e6b..0000000000 --- a/packages/utils/src/abi_encoder/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -export { EncodingRules, DecodingRules } from './utils/rules'; -export { - Address, - Array, - Bool, - DynamicBytes, - Int, - Method, - Pointer, - StaticBytes, - String, - Tuple, - UInt, - create, - createMethod, -} from './evm_data_type_factory'; -export { DataType } from './abstract_data_types/data_type'; diff --git a/packages/utils/src/abi_encoder/utils/constants.ts b/packages/utils/src/abi_encoder/utils/constants.ts deleted file mode 100644 index 2ed83ab7fc..0000000000 --- a/packages/utils/src/abi_encoder/utils/constants.ts +++ /dev/null @@ -1,23 +0,0 @@ -import * as ethUtil from 'ethereumjs-util'; - -import { DecodingRules, EncodingRules } from './rules'; - -export const constants = { - EVM_WORD_WIDTH_IN_BYTES: 32, - EVM_WORD_WIDTH_IN_BITS: 256, - HEX_BASE: 16, - DEC_BASE: 10, - BIN_BASE: 2, - HEX_SELECTOR_LENGTH_IN_CHARS: 10, - HEX_SELECTOR_LENGTH_IN_BYTES: 4, - HEX_SELECTOR_BYTE_OFFSET_IN_CALLDATA: 0, - // Disable no-object-literal-type-assertion so we can enforce cast - /* tslint:disable no-object-literal-type-assertion */ - DEFAULT_DECODING_RULES: { shouldConvertStructsToObjects: true, isStrictMode: false } as DecodingRules, - DEFAULT_ENCODING_RULES: { shouldOptimize: true, shouldAnnotate: false } as EncodingRules, - /* tslint:enable no-object-literal-type-assertion */ - EMPTY_EVM_WORD_STRING: '0x0000000000000000000000000000000000000000000000000000000000000000', - EMPTY_EVM_WORD_BUFFER: ethUtil.toBuffer('0x0000000000000000000000000000000000000000000000000000000000000000'), - NUMBER_OF_BYTES_IN_UINT8: 8, - NUMBER_OF_BYTES_IN_INT8: 8, -}; diff --git a/packages/utils/src/abi_encoder/utils/math.ts b/packages/utils/src/abi_encoder/utils/math.ts deleted file mode 100644 index a2a79e2a8d..0000000000 --- a/packages/utils/src/abi_encoder/utils/math.ts +++ /dev/null @@ -1,113 +0,0 @@ -import * as ethUtil from 'ethereumjs-util'; -import * as _ from 'lodash'; - -import { BigNumber } from '../../configured_bignumber'; -import { constants } from '../utils/constants'; - -function sanityCheckBigNumberRange( - value_: BigNumber | string | number, - minValue: BigNumber, - maxValue: BigNumber, -): void { - const value = new BigNumber(value_, 10); - if (value.isGreaterThan(maxValue)) { - throw new Error(`Tried to assign value of ${value}, which exceeds max value of ${maxValue}`); - } else if (value.isLessThan(minValue)) { - throw new Error(`Tried to assign value of ${value}, which exceeds min value of ${minValue}`); - } else if (value.isNaN()) { - throw new Error(`Tried to assign NaN value`); - } -} -function bigNumberToPaddedBuffer(value: BigNumber): Buffer { - const valueHex = `0x${value.toString(constants.HEX_BASE)}`; - const valueBuf = ethUtil.toBuffer(valueHex); - const valueBufPadded = ethUtil.setLengthLeft(valueBuf, constants.EVM_WORD_WIDTH_IN_BYTES); - return valueBufPadded; -} -/** - * Takes a numeric value and returns its ABI-encoded value - * @param value_ The value to encode. - * @return ABI Encoded value - */ -export function encodeNumericValue(value_: BigNumber | string | number): Buffer { - const value = new BigNumber(value_, 10); - // Case 1/2: value is non-negative - if (value.isGreaterThanOrEqualTo(0)) { - const encodedPositiveValue = bigNumberToPaddedBuffer(value); - return encodedPositiveValue; - } - // Case 2/2: Value is negative - // Use two's-complement to encode the value - // Step 1/3: Convert negative value to positive binary string - const valueBin = value.times(-1).toString(constants.BIN_BASE); - // Step 2/3: Invert binary value - let invertedValueBin = '1'.repeat(constants.EVM_WORD_WIDTH_IN_BITS - valueBin.length); - _.each(valueBin, (bit: string) => { - invertedValueBin += bit === '1' ? '0' : '1'; - }); - const invertedValue = new BigNumber(invertedValueBin, constants.BIN_BASE); - // Step 3/3: Add 1 to inverted value - const negativeValue = invertedValue.plus(1); - const encodedValue = bigNumberToPaddedBuffer(negativeValue); - return encodedValue; -} -/** - * Takes a numeric value and returns its ABI-encoded value. - * Performs an additional sanity check, given the min/max allowed value. - * @param value_ The value to encode. - * @return ABI Encoded value - */ -export function safeEncodeNumericValue( - value: BigNumber | string | number, - minValue: BigNumber, - maxValue: BigNumber, -): Buffer { - sanityCheckBigNumberRange(value, minValue, maxValue); - const encodedValue = encodeNumericValue(value); - return encodedValue; -} -/** - * Takes an ABI-encoded numeric value and returns its decoded value as a BigNumber. - * @param encodedValue The encoded numeric value. - * @param minValue The minimum possible decoded value. - * @return ABI Decoded value - */ -export function decodeNumericValue(encodedValue: Buffer, minValue: BigNumber): BigNumber { - const valueHex = ethUtil.bufferToHex(encodedValue); - // Case 1/3: value is definitely non-negative because of numeric boundaries - const value = new BigNumber(valueHex, constants.HEX_BASE); - if (!minValue.isLessThan(0)) { - return value; - } - // Case 2/3: value is non-negative because there is no leading 1 (encoded as two's-complement) - const valueBin = value.toString(constants.BIN_BASE); - const isValueNegative = valueBin.length === constants.EVM_WORD_WIDTH_IN_BITS && _.startsWith(valueBin[0], '1'); - if (!isValueNegative) { - return value; - } - // Case 3/3: value is negative - // Step 1/3: Invert b inary value - let invertedValueBin = ''; - _.each(valueBin, (bit: string) => { - invertedValueBin += bit === '1' ? '0' : '1'; - }); - const invertedValue = new BigNumber(invertedValueBin, constants.BIN_BASE); - // Step 2/3: Add 1 to inverted value - // The result is the two's-complement representation of the input value. - const positiveValue = invertedValue.plus(1); - // Step 3/3: Invert positive value to get the negative value - const negativeValue = positiveValue.times(-1); - return negativeValue; -} -/** - * Takes an ABI-encoded numeric value and returns its decoded value as a BigNumber. - * Performs an additional sanity check, given the min/max allowed value. - * @param encodedValue The encoded numeric value. - * @param minValue The minimum possible decoded value. - * @return ABI Decoded value - */ -export function safeDecodeNumericValue(encodedValue: Buffer, minValue: BigNumber, maxValue: BigNumber): BigNumber { - const value = decodeNumericValue(encodedValue, minValue); - sanityCheckBigNumberRange(value, minValue, maxValue); - return value; -} diff --git a/packages/utils/src/abi_encoder/utils/queue.ts b/packages/utils/src/abi_encoder/utils/queue.ts deleted file mode 100644 index 53afb7e112..0000000000 --- a/packages/utils/src/abi_encoder/utils/queue.ts +++ /dev/null @@ -1,39 +0,0 @@ -export class Queue { - private _store: T[] = []; - - public pushBack(val: T): void { - this._store.push(val); - } - - public pushFront(val: T): void { - this._store.unshift(val); - } - - public popFront(): T | undefined { - return this._store.shift(); - } - - public popBack(): T | undefined { - if (this._store.length === 0) { - return undefined; - } - const backElement = this._store.splice(-1, 1)[0]; - return backElement; - } - - public mergeBack(q: Queue): void { - this._store = this._store.concat(q._store); - } - - public mergeFront(q: Queue): void { - this._store = q._store.concat(this._store); - } - - public getStore(): T[] { - return this._store; - } - - public peekFront(): T | undefined { - return this._store.length >= 0 ? this._store[0] : undefined; - } -} diff --git a/packages/utils/src/abi_encoder/utils/rules.ts b/packages/utils/src/abi_encoder/utils/rules.ts deleted file mode 100644 index 9239305742..0000000000 --- a/packages/utils/src/abi_encoder/utils/rules.ts +++ /dev/null @@ -1,9 +0,0 @@ -export interface DecodingRules { - shouldConvertStructsToObjects: boolean; - isStrictMode: boolean; -} - -export interface EncodingRules { - shouldOptimize?: boolean; - shouldAnnotate?: boolean; -} diff --git a/packages/utils/src/abi_encoder/utils/signature_parser.ts b/packages/utils/src/abi_encoder/utils/signature_parser.ts deleted file mode 100644 index d3996bf8e9..0000000000 --- a/packages/utils/src/abi_encoder/utils/signature_parser.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { DataItem } from 'ethereum-types'; -import * as _ from 'lodash'; - -interface Node { - name: string; - value: string; - children: Node[]; - parent?: Node; -} - -function parseNode(node: Node): DataItem { - const components: DataItem[] = []; - _.each(node.children, (child: Node) => { - const component = parseNode(child); - components.push(component); - }); - const dataItem: DataItem = { - name: node.name, - type: node.value, - }; - if (!_.isEmpty(components)) { - dataItem.components = components; - } - return dataItem; -} - -/** - * Returns a DataItem corresponding to the input signature. - * A signature can be in two forms: `type` or `(type_1,type_2,...,type_n)` - * An example of the first form would be 'address' or 'uint256[]' or 'bytes[5][]' - * An example of the second form would be '(address,uint256)' or '(address,uint256)[]' - * @param signature of input DataItem. - * @return DataItem derived from input signature. - */ -export function generateDataItemFromSignature(signature: string): DataItem { - // No data item corresponds to an empty signature - if (_.isEmpty(signature)) { - throw new Error(`Cannot parse data item from empty signature, ''`); - } - // Create a parse tree for data item - let node: Node = { - name: '', - value: '', - children: [], - }; - for (const char of signature) { - switch (char) { - case '(': - const child = { - name: '', - value: '', - children: [], - parent: node, - }; - node.value = 'tuple'; - node.children.push(child); - node = child; - break; - - case ')': - node = node.parent as Node; - break; - - case ',': - const sibling = { - name: '', - value: '', - children: [], - parent: node.parent, - }; - (node.parent as Node).children.push(sibling); - node = sibling; - break; - - case ' ': - node.name = node.value; - node.value = ''; - break; - - default: - node.value += char; - break; - } - } - // Interpret data item from parse tree - const dataItem = parseNode(node); - return dataItem; -} diff --git a/packages/utils/src/abi_utils.ts b/packages/utils/src/abi_utils.ts deleted file mode 100644 index 15f51c20ed..0000000000 --- a/packages/utils/src/abi_utils.ts +++ /dev/null @@ -1,229 +0,0 @@ -import { AbiDefinition, AbiType, ContractAbi, DataItem, MethodAbi } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { BigNumber } from './configured_bignumber'; - -type ParamName = null | string | NestedParamName; -interface NestedParamName { - name: string | null; - names: ParamName[]; -} - -// Note(albrow): This function is unexported in ethers.js. Copying it here for -// now. -// Source: https://github.com/ethers-io/ethers.js/blob/884593ab76004a808bf8097e9753fb5f8dcc3067/contracts/interface.js#L30 -function parseEthersParams(params: DataItem[]): { names: ParamName[]; types: string[] } { - const names: ParamName[] = []; - const types: string[] = []; - - params.forEach((param: DataItem) => { - if (param.components != null) { - let suffix = ''; - const arrayBracket = param.type.indexOf('['); - if (arrayBracket >= 0) { - suffix = param.type.substring(arrayBracket); - } - - const result = parseEthersParams(param.components); - names.push({ name: param.name || null, names: result.names }); - types.push(`tuple(${result.types.join(',')})${suffix}`); - } else { - names.push(param.name || null); - types.push(param.type); - } - }); - - return { - names, - types, - }; -} - -// returns true if x is equal to y and false otherwise. Performs some minimal -// type conversion and data massaging for x and y, depending on type. name and -// type should typically be derived from parseEthersParams. -function isAbiDataEqual(name: ParamName, type: string, x: any, y: any): boolean { - if (x === undefined && y === undefined) { - return true; - } else if (x === undefined && y !== undefined) { - return false; - } else if (x !== undefined && y === undefined) { - return false; - } - if (_.endsWith(type, '[]')) { - // For array types, we iterate through the elements and check each one - // individually. Strangely, name does not need to be changed in this - // case. - if (x.length !== y.length) { - return false; - } - const newType = _.trimEnd(type, '[]'); - for (let i = 0; i < x.length; i++) { - if (!isAbiDataEqual(name, newType, x[i], y[i])) { - return false; - } - } - return true; - } - if (_.startsWith(type, 'tuple(')) { - if (_.isString(name)) { - throw new Error('Internal error: type was tuple but names was a string'); - } else if (name === null) { - throw new Error('Internal error: type was tuple but names was null'); - } - // For tuples, we iterate through the underlying values and check each - // one individually. - const types = splitTupleTypes(type); - if (types.length !== name.names.length) { - throw new Error( - `Internal error: parameter types/names length mismatch (${types.length} != ${name.names.length})`, - ); - } - for (let i = 0; i < types.length; i++) { - // For tuples, name is an object with a names property that is an - // array. As an example, for orders, name looks like: - // - // { - // name: 'orders', - // names: [ - // 'makerAddress', - // // ... - // 'takerAssetData' - // ] - // } - // - const nestedName = _.isString(name.names[i]) - ? (name.names[i] as string) - : ((name.names[i] as NestedParamName).name as string); - if (!isAbiDataEqual(name.names[i], types[i], x[nestedName], y[nestedName])) { - return false; - } - } - return true; - } else if (type === 'address' || type === 'bytes') { - // HACK(albrow): ethers.js returns the checksummed address even when - // initially passed in a non-checksummed address. To account for that, - // we convert to lowercase before comparing. - return _.isEqual(_.toLower(x), _.toLower(y)); - } else if (_.startsWith(type, 'uint') || _.startsWith(type, 'int')) { - return new BigNumber(x).eq(new BigNumber(y)); - } - return _.isEqual(x, y); -} - -// splitTupleTypes splits a tuple type string (of the form `tuple(X)` where X is -// any other type or list of types) into its component types. It works with -// nested tuples, so, e.g., `tuple(tuple(uint256,address),bytes32)` will yield: -// `['tuple(uint256,address)', 'bytes32']`. It expects exactly one tuple type as -// an argument (not an array). -function splitTupleTypes(type: string): string[] { - if (_.endsWith(type, '[]')) { - throw new Error('Internal error: array types are not supported'); - } else if (!_.startsWith(type, 'tuple(')) { - throw new Error(`Internal error: expected tuple type but got non-tuple type: ${type}`); - } - // Trim the outtermost tuple(). - const trimmedType = type.substring('tuple('.length, type.length - 1); - const types: string[] = []; - let currToken = ''; - let parenCount = 0; - // Tokenize the type string while keeping track of parentheses. - for (const char of trimmedType) { - switch (char) { - case '(': - parenCount += 1; - currToken += char; - break; - case ')': - parenCount -= 1; - currToken += char; - break; - case ',': - if (parenCount === 0) { - types.push(currToken); - currToken = ''; - break; - } else { - currToken += char; - break; - } - default: - currToken += char; - break; - } - } - types.push(currToken); - return types; -} - -export const abiUtils = { - parseEthersParams, - isAbiDataEqual, - splitTupleTypes, - parseFunctionParam(param: DataItem): string { - if (param.type === 'tuple') { - // Parse out tuple types into {type_1, type_2, ..., type_N} - const tupleComponents = param.components; - const paramString = _.map(tupleComponents, component => abiUtils.parseFunctionParam(component)); - const tupleParamString = `{${paramString}}`; - return tupleParamString; - } - return param.type; - }, - getFunctionSignature(methodAbi: MethodAbi): string { - const functionName = methodAbi.name; - const parameterTypeList = _.map(methodAbi.inputs, (param: DataItem) => abiUtils.parseFunctionParam(param)); - const functionSignature = `${functionName}(${parameterTypeList})`; - return functionSignature; - }, - /** - * Solidity supports function overloading whereas TypeScript does not. - * See: https://solidity.readthedocs.io/en/v0.4.21/contracts.html?highlight=overload#function-overloading - * In order to support overloaded functions, we suffix overloaded function names with an index. - * This index should be deterministic, regardless of function ordering within the smart contract. To do so, - * we assign indexes based on the alphabetical order of function signatures. - * - * E.g - * ['f(uint)', 'f(uint,byte32)'] - * Should always be renamed to: - * ['f1(uint)', 'f2(uint,byte32)'] - * Regardless of the order in which these these overloaded functions are declared within the contract ABI. - */ - renameOverloadedMethods(inputContractAbi: ContractAbi): ContractAbi { - const contractAbi = _.cloneDeep(inputContractAbi); - const methodAbis = contractAbi.filter((abi: AbiDefinition) => abi.type === AbiType.Function) as MethodAbi[]; - // Sort method Abis into alphabetical order, by function signature - const methodAbisOrdered = _.sortBy(methodAbis, [ - (methodAbi: MethodAbi) => { - const functionSignature = abiUtils.getFunctionSignature(methodAbi); - return functionSignature; - }, - ]); - // Group method Abis by name (overloaded methods will be grouped together, in alphabetical order) - const methodAbisByName: { [key: string]: MethodAbi[] } = {}; - _.each(methodAbisOrdered, methodAbi => { - (methodAbisByName[methodAbi.name] || (methodAbisByName[methodAbi.name] = [])).push(methodAbi); - }); - // Rename overloaded methods to overloadedMethodName1, overloadedMethodName2, ... - _.each(methodAbisByName, methodAbisWithSameName => { - _.each(methodAbisWithSameName, (methodAbi, i: number) => { - if (methodAbisWithSameName.length > 1) { - const overloadedMethodId = i + 1; - const sanitizedMethodName = `${methodAbi.name}${overloadedMethodId}`; - const indexOfExistingAbiWithSanitizedMethodNameIfExists = _.findIndex( - methodAbis, - currentMethodAbi => currentMethodAbi.name === sanitizedMethodName, - ); - if (indexOfExistingAbiWithSanitizedMethodNameIfExists >= 0) { - const methodName = methodAbi.name; - throw new Error( - `Failed to rename overloaded method '${methodName}' to '${sanitizedMethodName}'. A method with this name already exists.`, - ); - } - methodAbi.name = sanitizedMethodName; - } - }); - }); - return contractAbi; - }, -}; diff --git a/packages/utils/src/address_utils.ts b/packages/utils/src/address_utils.ts deleted file mode 100644 index 361e35cd81..0000000000 --- a/packages/utils/src/address_utils.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { addHexPrefix, sha3, stripHexPrefix } from 'ethereumjs-util'; -import * as jsSHA3 from 'js-sha3'; -import * as _ from 'lodash'; - -import { generatePseudoRandom256BitNumber } from './random'; - -const BASIC_ADDRESS_REGEX = /^(0x)?[0-9a-f]{40}$/i; -const SAME_CASE_ADDRESS_REGEX = /^(0x)?([0-9a-f]{40}|[0-9A-F]{40})$/; -const ADDRESS_LENGTH = 40; - -export const addressUtils = { - isChecksumAddress(address: string): boolean { - // Check each case - const unprefixedAddress = address.replace('0x', ''); - const addressHash = jsSHA3.keccak256(unprefixedAddress.toLowerCase()); - - for (let i = 0; i < ADDRESS_LENGTH; i++) { - // The nth letter should be uppercase if the nth digit of casemap is 1 - const hexBase = 16; - const lowercaseRange = 7; - if ( - (parseInt(addressHash[i], hexBase) > lowercaseRange && - unprefixedAddress[i].toUpperCase() !== unprefixedAddress[i]) || - (parseInt(addressHash[i], hexBase) <= lowercaseRange && - unprefixedAddress[i].toLowerCase() !== unprefixedAddress[i]) - ) { - return false; - } - } - return true; - }, - isAddress(address: string): boolean { - if (!BASIC_ADDRESS_REGEX.test(address)) { - // Check if it has the basic requirements of an address - return false; - } else if (SAME_CASE_ADDRESS_REGEX.test(address)) { - // If it's all small caps or all all caps, return true - return true; - } else { - // Otherwise check each case - const isValidChecksummedAddress = addressUtils.isChecksumAddress(address); - return isValidChecksummedAddress; - } - }, - padZeros(address: string): string { - return addHexPrefix(_.padStart(stripHexPrefix(address), ADDRESS_LENGTH, '0')); - }, - generatePseudoRandomAddress(): string { - const randomBigNum = generatePseudoRandom256BitNumber(); - const randomBuff = sha3(randomBigNum.toString()); - const addressLengthInBytes = 20; - const randomAddress = `0x${randomBuff.slice(0, addressLengthInBytes).toString('hex')}`; - return randomAddress; - }, -}; diff --git a/packages/utils/src/class_utils.ts b/packages/utils/src/class_utils.ts deleted file mode 100644 index 04e60ee57c..0000000000 --- a/packages/utils/src/class_utils.ts +++ /dev/null @@ -1,18 +0,0 @@ -import * as _ from 'lodash'; - -export const classUtils = { - // This is useful for classes that have nested methods. Nested methods don't get bound out of the box. - bindAll(self: any, exclude: string[] = ['contructor'], thisArg?: any): void { - for (const key of Object.getOwnPropertyNames(self)) { - const val = self[key]; - if (!_.includes(exclude, key)) { - if (_.isFunction(val)) { - self[key] = val.bind(thisArg || self); - } else if (_.isObject(val)) { - classUtils.bindAll(val, exclude, self); - } - } - } - return self; - }, -}; diff --git a/packages/utils/src/configured_bignumber.ts b/packages/utils/src/configured_bignumber.ts deleted file mode 100644 index 2c3317108d..0000000000 --- a/packages/utils/src/configured_bignumber.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { BigNumber } from 'bignumber.js'; - -BigNumber.config({ - // By default BigNumber's `toString` method converts to exponential notation if the value has - // more then 20 digits. We want to avoid this behavior, so we set EXPONENTIAL_AT to a high number - EXPONENTIAL_AT: 1000, - // Note(albrow): This is the lowest value for which - // `x.div(y).floor() === x.divToInt(y)` - // for all values of x and y <= MAX_UINT256, where MAX_UINT256 is the - // maximum number represented by the uint256 type in Solidity (2^256-1). - DECIMAL_PLACES: 78, -}); - -// Set a debug print function for NodeJS -// Upstream issue: https://github.com/MikeMcl/bignumber.js/issues/188 -import isNode = require('detect-node'); -if (isNode) { - // Dynamically load a NodeJS specific module. - // TypeScript requires all imports to be global, so we need to use - // `const` here and disable the tslint warning. - // tslint:disable-next-line: no-var-requires - const util = require('util'); - - // Set a custom util.inspect function - // HACK: We add a function to the BigNumber class by assigning to the - // prototype. The function name is a symbol provided by Node. - (BigNumber.prototype as any)[util.inspect.custom] = function(): string { - // HACK: When executed, `this` will refer to the BigNumber instance. - // This is also why we need a function expression instead of an - // arrow function, as the latter does not have a `this`. - // Return the readable string representation - // tslint:disable-next-line: no-invalid-this - return this.toString(); - }; -} - -// HACK: CLobber config and set to prevent imported packages from poisoning -// global BigNumber config -(orig => (BigNumber.config = (..._args: any[]) => orig({})))(BigNumber.config); -BigNumber.set = BigNumber.config; - -export { BigNumber }; diff --git a/packages/utils/src/constants.ts b/packages/utils/src/constants.ts deleted file mode 100644 index 94fb16d430..0000000000 --- a/packages/utils/src/constants.ts +++ /dev/null @@ -1,2 +0,0 @@ -export const NULL_BYTES = '0x'; -export const NULL_ADDRESS = '0x0000000000000000000000000000000000000000'; diff --git a/packages/utils/src/delete_nested_property.ts b/packages/utils/src/delete_nested_property.ts deleted file mode 100644 index 271e37dc53..0000000000 --- a/packages/utils/src/delete_nested_property.ts +++ /dev/null @@ -1,25 +0,0 @@ -/* Deletes deeply nested properties from an object. MUTATES the object - * @param obj the object to be operated on - * @param propPath the full dot-separated path to the property to delete, e.g. 'animals.mammals.dog.name' - * returns void - */ -export const deleteNestedProperty = (obj: any, propPath: string): void => { - if (!obj || !propPath) { - return; - } - - const propPathParts = propPath.split('.'); - - let _obj = obj; - for (let i = 0; i < propPathParts.length - 1; i++) { - _obj = _obj[propPathParts[i]]; - - if (typeof _obj === 'undefined') { - return; - } - } - - while (propPathParts.length > 0) { - delete _obj[propPathParts.pop() as string]; - } -}; diff --git a/packages/utils/src/error_utils.ts b/packages/utils/src/error_utils.ts deleted file mode 100644 index 735d3940ba..0000000000 --- a/packages/utils/src/error_utils.ts +++ /dev/null @@ -1,5 +0,0 @@ -export const errorUtils = { - spawnSwitchErr(name: string, value: any): Error { - return new Error(`Unexpected switch value: ${value} encountered for ${name}`); - }, -}; diff --git a/packages/utils/src/fetch_async.ts b/packages/utils/src/fetch_async.ts deleted file mode 100644 index b4c85718d3..0000000000 --- a/packages/utils/src/fetch_async.ts +++ /dev/null @@ -1,40 +0,0 @@ -import isNode = require('detect-node'); -import 'isomorphic-fetch'; -// WARNING: This needs to be imported after isomorphic-fetch: https://github.com/mo/abortcontroller-polyfill#using-it-on-browsers-without-fetch -// tslint:disable-next-line:ordered-imports -import 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'; - -export const fetchAsync = async ( - endpoint: string, - options: RequestInit = {}, - timeoutMs: number = 20000, -): Promise => { - if (options.signal || (options as any).timeout) { - throw new Error( - 'Cannot call fetchAsync with options.signal or options.timeout. To set a timeout, please use the supplied "timeoutMs" parameter.', - ); - } - let optionsWithAbortParam; - if (!isNode) { - const controller = new AbortController(); - const signal = controller.signal; - setTimeout(() => { - controller.abort(); - }, timeoutMs); - optionsWithAbortParam = { - signal, - ...options, - }; - } else { - // HACK: the `timeout` param only exists in `node-fetch`, and not on the `isomorphic-fetch` - // `RequestInit` type. Since `isomorphic-fetch` conditionally wraps `node-fetch` when the - // execution environment is `Node.js`, we need to cast it to `any` in that scenario. - optionsWithAbortParam = { - timeout: timeoutMs, - ...options, - } as any; - } - - const response = await fetch(endpoint, optionsWithAbortParam); - return response; -}; diff --git a/packages/utils/src/globals.d.ts b/packages/utils/src/globals.d.ts deleted file mode 100644 index 94e63a32de..0000000000 --- a/packages/utils/src/globals.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -declare module '*.json' { - const json: any; - /* tslint:disable */ - export default json; - /* tslint:enable */ -} diff --git a/packages/utils/src/hex_utils.ts b/packages/utils/src/hex_utils.ts deleted file mode 100644 index d8abe44b2a..0000000000 --- a/packages/utils/src/hex_utils.ts +++ /dev/null @@ -1,121 +0,0 @@ -import * as crypto from 'crypto'; -import * as ethUtil from 'ethereumjs-util'; - -import { BigNumber } from './configured_bignumber'; -import { Numberish } from './types'; - -// tslint:disable:custom-no-magic-numbers - -const WORD_LENGTH = 32; -const WORD_CEIL = new BigNumber(2).pow(WORD_LENGTH * 8); - -export const hexUtils = { - concat, - random, - leftPad, - rightPad, - invert, - slice, - hash, - size, - toHex, - isHex, -}; - -/** - * Concatenate all arguments as a hex string. - */ -function concat(...args: Array): string { - return ethUtil.bufferToHex(Buffer.concat(args.map(h => ethUtil.toBuffer(h)))); -} - -/** - * Generate a random hex string. - */ -function random(_size: number = WORD_LENGTH): string { - return ethUtil.bufferToHex(crypto.randomBytes(_size)); -} - -/** - * Left-pad a hex number to a number of bytes. - */ -function leftPad(n: Numberish, _size: number = WORD_LENGTH): string { - return ethUtil.bufferToHex(ethUtil.setLengthLeft(hexUtils.toHex(n), _size)); -} - -/** - * Right-pad a hex number to a number of bytes. - */ -function rightPad(n: Numberish, _size: number = WORD_LENGTH): string { - return ethUtil.bufferToHex(ethUtil.setLengthRight(hexUtils.toHex(n), _size)); -} - -/** - * Inverts a hex word. - */ -function invert(n: Numberish, _size: number = WORD_LENGTH): string { - const buf = ethUtil.setLengthLeft(hexUtils.toHex(n), _size); - // tslint:disable-next-line: no-bitwise - return ethUtil.bufferToHex(Buffer.from(buf.map(b => ~b))); -} - -/** - * Slices a hex number. - */ -function slice(n: Numberish, start: number, end?: number): string { - const hex = hexUtils.toHex(n).substr(2); - const sliceStart = start >= 0 ? start * 2 : Math.max(0, hex.length + start * 2); - let sliceEnd = hex.length; - if (end !== undefined) { - sliceEnd = end >= 0 ? end * 2 : Math.max(0, hex.length + end * 2); - } - return '0x'.concat(hex.substring(sliceStart, sliceEnd)); -} - -/** - * Get the keccak hash of some data. - */ -function hash(n: Numberish): string { - return ethUtil.bufferToHex(ethUtil.sha3(ethUtil.toBuffer(hexUtils.toHex(n)))); -} - -/** - * Get the length, in bytes, of a hex string. - */ -function size(hex: string): number { - return Math.ceil((hex.length - 2) / 2); -} - -/** - * Convert a string, a number, a Buffer, or a BigNumber into a hex string. - * Works with negative numbers, as well. - */ -function toHex(n: Numberish | Buffer, _size: number = WORD_LENGTH): string { - if (Buffer.isBuffer(n)) { - return `0x${n.toString('hex')}`; - } - if (typeof n === 'string' && /^0x[0-9a-f]+$/i.test(n)) { - // Already a hex. - return n; - } - let _n = new BigNumber(n); - if (_n.isNegative()) { - // Perform two's-complement. - // prettier-ignore - _n = new BigNumber( - invert( - toHex(_n.abs()), - _size, - ).substr(2), - 16, - ).plus(1).mod(WORD_CEIL); - } - return `0x${_n.toString(16)}`; -} - -/** - * Check if a string is a hex string. - */ -function isHex(s: string): boolean { - return /^0x[0-9a-f]+$/i.test(s); -} diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts deleted file mode 100644 index 74c518ddc4..0000000000 --- a/packages/utils/src/index.ts +++ /dev/null @@ -1,58 +0,0 @@ -export { promisify } from './promisify'; -export { addressUtils } from './address_utils'; -export { classUtils } from './class_utils'; -export { deleteNestedProperty } from './delete_nested_property'; -export { intervalUtils } from './interval_utils'; -export { providerUtils } from './provider_utils'; -export { BigNumber } from './configured_bignumber'; -export { AbiDecoder } from './abi_decoder'; -export { logUtils } from './log_utils'; -export { abiUtils } from './abi_utils'; -export { NULL_BYTES, NULL_ADDRESS } from './constants'; -export { errorUtils } from './error_utils'; -export { fetchAsync } from './fetch_async'; -export { signTypedDataUtils } from './sign_typed_data_utils'; -export { hexUtils } from './hex_utils'; -export import AbiEncoder = require('./abi_encoder'); -export * from './types'; -export { generatePseudoRandom256BitNumber } from './random'; -export { - decodeBytesAsRevertError, - decodeThrownErrorAsRevertError, - coerceThrownErrorAsRevertError, - RawRevertError, - registerRevertErrorType, - RevertError, - StringRevertError, - AnyRevertError, -} from './revert_error'; -export { fromTokenUnitAmount, toTokenUnitAmount } from './token_utils'; - -export import BrokerRevertErrors = require('./revert_errors/broker/revert_errors'); -export import CoordinatorRevertErrors = require('./revert_errors/coordinator/revert_errors'); -export import ExchangeForwarderRevertErrors = require('./revert_errors/exchange-forwarder/revert_errors'); -export import LibMathRevertErrors = require('./revert_errors/exchange-libs/lib_math_revert_errors'); -export import ExchangeRevertErrors = require('./revert_errors/exchange/revert_errors'); -export import LibAssetDataTransferRevertErrors = require('./revert_errors/extensions/lib_asset_data_transfer_revert_errors'); -export import MixinWethUtilsRevertErrors = require('./revert_errors/extensions/mixin_weth_utils_revert_errors'); -export import FixedMathRevertErrors = require('./revert_errors/staking/fixed_math_revert_errors'); -export import StakingRevertErrors = require('./revert_errors/staking/staking_revert_errors'); -export import AuthorizableRevertErrors = require('./revert_errors/utils/authorizable_revert_errors'); -export import LibAddressArrayRevertErrors = require('./revert_errors/utils/lib_address_array_revert_errors'); -export import LibBytesRevertErrors = require('./revert_errors/utils/lib_bytes_revert_errors'); -export import OwnableRevertErrors = require('./revert_errors/utils/ownable_revert_errors'); -export import ReentrancyGuardRevertErrors = require('./revert_errors/utils/reentrancy_guard_revert_errors'); -export import SafeMathRevertErrors = require('./revert_errors/utils/safe_math_revert_errors'); - -export const ZeroExRevertErrors = { - Common: require('./revert_errors/zero-ex/common_revert_errors'), - Proxy: require('./revert_errors/zero-ex/proxy_revert_errors'), - SimpleFunctionRegistry: require('./revert_errors/zero-ex/simple_function_registry_revert_errors'), - Ownable: require('./revert_errors/zero-ex/ownable_revert_errors'), - Spender: require('./revert_errors/zero-ex/spender_revert_errors'), - TransformERC20: require('./revert_errors/zero-ex/transform_erc20_revert_errors'), - Wallet: require('./revert_errors/zero-ex/wallet_revert_errors'), - MetaTransactions: require('./revert_errors/zero-ex/meta_transaction_revert_errors'), - SignatureValidator: require('./revert_errors/zero-ex/signature_validator_revert_errors'), - LiquidityProvider: require('./revert_errors/zero-ex/liquidity_provider_revert_errors'), -}; diff --git a/packages/utils/src/interval_utils.ts b/packages/utils/src/interval_utils.ts deleted file mode 100644 index 3d0561cd29..0000000000 --- a/packages/utils/src/interval_utils.ts +++ /dev/null @@ -1,39 +0,0 @@ -export const intervalUtils = { - setAsyncExcludingInterval( - fn: () => Promise, - intervalMs: number, - onError: (err: Error) => void, - ): NodeJS.Timer { - let isLocked = false; - const intervalId = setInterval(async () => { - if (isLocked) { - return; - } else { - isLocked = true; - try { - await fn(); - } catch (err) { - onError(err); - } - isLocked = false; - } - }, intervalMs); - return intervalId; - }, - clearAsyncExcludingInterval(intervalId: NodeJS.Timer): void { - clearInterval(intervalId); - }, - setInterval(fn: () => void, intervalMs: number, onError: (err: Error) => void): NodeJS.Timer { - const intervalId = setInterval(() => { - try { - fn(); - } catch (err) { - onError(err); - } - }, intervalMs); - return intervalId; - }, - clearInterval(intervalId: NodeJS.Timer): void { - clearInterval(intervalId); - }, -}; diff --git a/packages/utils/src/log_utils.ts b/packages/utils/src/log_utils.ts deleted file mode 100644 index 4c32f89cbd..0000000000 --- a/packages/utils/src/log_utils.ts +++ /dev/null @@ -1,30 +0,0 @@ -import chalk from 'chalk'; -import * as _ from 'lodash'; - -const DEFAULT_TERMINAL_WIDTH = 80; -const TERMINAL_WIDTH = _.get(process, 'stdout.columns') || DEFAULT_TERMINAL_WIDTH; - -export const logUtils = { - log(...args: any[]): void { - console.log(...args); // tslint:disable-line:no-console - }, - header(text: string, padStr: string = '='): void { - const padLength = TERMINAL_WIDTH - text.length; - const padLengthEnd = (padLength + 1) / 2; - const leftPadded = text.padStart(TERMINAL_WIDTH - padLengthEnd, padStr); - const padded = leftPadded.padEnd(TERMINAL_WIDTH, padStr); - console.log(padded); // tslint:disable-line:no-console - }, - warn(...args: any[]): void { - console.warn(...args); // tslint:disable-line:no-console - }, - table(columnarData: { [rowName: string]: any }): void { - const formattedColumnarData = _.mapValues(columnarData, (columnOrColumns: any, _rowName: string) => - _.isNumber(columnOrColumns) ? columnOrColumns.toLocaleString() : columnOrColumns, - ); - console.table(formattedColumnarData); // tslint:disable-line:no-console - }, - logWithTime(arg: string): void { - logUtils.log(`[${chalk.gray(new Date().toLocaleTimeString())}] ${arg}`); - }, -}; diff --git a/packages/utils/src/promisify.ts b/packages/utils/src/promisify.ts deleted file mode 100644 index c460fce19e..0000000000 --- a/packages/utils/src/promisify.ts +++ /dev/null @@ -1,19 +0,0 @@ -import * as _ from 'lodash'; - -/** - * Transforms callback-based function -- func(arg1, arg2 .. argN, callback) -- into an ES6-compatible Promise. - * Promisify provides a default callback of the form (error, result) and rejects when `error` is not null. You can also - * supply thisArg object as the second argument which will be passed to `apply`. - */ -// HACK: This can't be properly typed without variadic kinds https://github.com/Microsoft/TypeScript/issues/5453 -export function promisify(originalFn: (...args: any[]) => void, thisArg?: any): (...callArgs: any[]) => Promise { - const promisifiedFunction = async (...callArgs: any[]): Promise => { - return new Promise((resolve, reject) => { - const callback = (err: Error | null, data?: T) => { - err === null || err === undefined ? resolve(data) : reject(err); - }; - originalFn.apply(thisArg, [...callArgs, callback]); - }); - }; - return promisifiedFunction; -} diff --git a/packages/utils/src/provider_utils.ts b/packages/utils/src/provider_utils.ts deleted file mode 100644 index a2d81bb848..0000000000 --- a/packages/utils/src/provider_utils.ts +++ /dev/null @@ -1,133 +0,0 @@ -import { - EIP1193Provider, - JSONRPCErrorCallback, - JSONRPCRequestPayload, - JSONRPCResponsePayload, - SupportedProvider, - ZeroExProvider, -} from 'ethereum-types'; -import * as _ from 'lodash'; - -export const providerUtils = { - /** - * Starts the Web3ProviderEngine without excess block polling - * @param providerEngine The Web3ProviderEngine - */ - startProviderEngine(providerEngine: any): void { - if (providerEngine.start === undefined) { - throw new Error(`Invalid Web3ProviderEngine`); - } - // HACK: When calling start() Web3ProviderEngine starts a block polling service - // this continuously pulls data from the network and can result in high data usage - // for long running services. If used in a front end application this can cause - // a high amount of load on a node (one request per user per block). - providerEngine._ready.go(); - providerEngine._running = true; - }, - /** - * Standardize the supported provider types into our internal provider interface - * or throw if unsupported provider supplied. - * @param supportedProvider Potentially supported provider instance - * @return Provider that conforms of our internal provider interface - */ - standardizeOrThrow(supportedProvider: SupportedProvider): ZeroExProvider { - if (supportedProvider === undefined) { - throw new Error(`supportedProvider cannot be 'undefined'`); - } - const provider = { - isStandardizedProvider: true, - isMetaMask: (supportedProvider as any).isMetaMask, - isParity: (supportedProvider as any).isParity, - stop: (supportedProvider as any).stop, - enable: (supportedProvider as any).enable, - sendAsync: _.noop.bind(_), // Will be replaced - }; - if (provider.enable) { - // Need to bind, metamask can lose reference to function without binding as of 7.7.0 - provider.enable.bind(supportedProvider); - } - // Case 1: We've already converted to our ZeroExProvider so noop. - if ((supportedProvider as any).isStandardizedProvider) { - // tslint:disable-next-line:no-unnecessary-type-assertion - return supportedProvider as ZeroExProvider; - // Case 2: It's a compliant EIP 1193 Provider - // tslint:disable-next-line:no-unnecessary-type-assertion - } else if ((supportedProvider as EIP1193Provider).isEIP1193) { - provider.sendAsync = (payload: JSONRPCRequestPayload, callback: JSONRPCErrorCallback) => { - const method = payload.method; - const params = payload.params; - (supportedProvider as any) - .send(method, params) - .then((result: any) => { - callback(null, result); - }) - .catch((err: Error) => { - callback(err); - }); - }; - return provider; - // Case 3: The provider has a `sendAsync` method, so we use it. - } else if ((supportedProvider as any).sendAsync !== undefined) { - provider.sendAsync = (supportedProvider as any).sendAsync.bind(supportedProvider); - return provider; - // Case 4: The provider does not have a `sendAsync` method but does have a `send` method - } else if ((supportedProvider as any).send !== undefined) { - // HACK(fabio): Detect if the `send` method has the old interface `send(payload, cb)` such - // as in versions < Web3.js@1.0.0-beta.37. If so, do a simple re-mapping - if (_.includes((supportedProvider as any).send.toString().replace(' ', ''), 'function(payload,callback)')) { - provider.sendAsync = (supportedProvider as any).send.bind(supportedProvider); - return provider; - } else { - // If doesn't have old interface, we assume it has new interface `send(method, payload)` - // such as in versions > Web3.js@1.0.0-beta.38 and convert it to `sendAsync` - provider.sendAsync = (payload: JSONRPCRequestPayload, callback: JSONRPCErrorCallback) => { - const method = payload.method; - const params = payload.params; - (supportedProvider as any) - .send(method, params) - .then((result: any) => { - callback(null, result); - }) - .catch((err: Error) => { - callback(err); - }); - }; - return provider; - } - } - throw new Error( - `Unsupported provider found. Please make sure it conforms to one of the supported providers. See 'Provider' type in 'ethereum-types' package.`, - ); - }, - - /** - * Retrieve the chain ID from a supported provider. - * @param supportedProvider A supported provider instance. - * @return A promise that resolves to the chain ID of the network the provider - * is connected to. - */ - async getChainIdAsync(supportedProvider: SupportedProvider): Promise { - const provider = providerUtils.standardizeOrThrow(supportedProvider); - // tslint:disable-next-line:custom-no-magic-numbers - const RPC_ID_MAX = 2 ** 64; - return new Promise((accept, reject) => { - provider.sendAsync( - { - jsonrpc: '2.0', - id: _.random(1, RPC_ID_MAX), - method: 'eth_chainId', - params: [], - }, - (err: Error | null, result?: JSONRPCResponsePayload) => { - if (!_.isNil(err)) { - reject(err); - } - if (!result) { - throw new Error("Invalid 'eth_chainId' response"); - } - accept(_.toNumber(result.result)); - }, - ); - }); - }, -}; diff --git a/packages/utils/src/random.ts b/packages/utils/src/random.ts deleted file mode 100644 index 69243bab84..0000000000 --- a/packages/utils/src/random.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { BigNumber } from './configured_bignumber'; - -const MAX_DIGITS_IN_UNSIGNED_256_INT = 78; - -/** - * Generates a pseudo-random 256-bit number. - * @return A pseudo-random 256-bit number. - */ -export function generatePseudoRandom256BitNumber(): BigNumber { - // BigNumber.random returns a pseudo-random number between 0 & 1 with a passed in number of decimal places. - // Source: https://mikemcl.github.io/bignumber.js/#random - const randomNumber = BigNumber.random(MAX_DIGITS_IN_UNSIGNED_256_INT); - const factor = new BigNumber(10).pow(MAX_DIGITS_IN_UNSIGNED_256_INT - 1); - const randomNumberScaledTo256Bits = randomNumber.times(factor).integerValue(); - return randomNumberScaledTo256Bits; -} diff --git a/packages/utils/src/revert_error.ts b/packages/utils/src/revert_error.ts deleted file mode 100644 index 15d5378a9c..0000000000 --- a/packages/utils/src/revert_error.ts +++ /dev/null @@ -1,584 +0,0 @@ -import { ObjectMap } from '@0x/types'; -import { DataItem, RevertErrorAbi } from 'ethereum-types'; -import * as ethUtil from 'ethereumjs-util'; -import * as _ from 'lodash'; -import { inspect } from 'util'; - -import * as AbiEncoder from './abi_encoder'; -import { BigNumber } from './configured_bignumber'; - -// tslint:disable: max-classes-per-file no-unnecessary-type-assertion - -type ArgTypes = - | string - | BigNumber - | number - | boolean - | RevertError - | BigNumber[] - | string[] - | number[] - | boolean[] - | Array; -type ValueMap = ObjectMap; -type RevertErrorDecoder = (hex: string) => ValueMap; - -interface RevertErrorType { - new (): RevertError; -} - -interface RevertErrorRegistryItem { - type: RevertErrorType; - decoder: RevertErrorDecoder; -} - -/** - * Register a RevertError type so that it can be decoded by - * `decodeRevertError`. - * @param revertClass A class that inherits from RevertError. - */ -export function registerRevertErrorType(revertClass: RevertErrorType): void { - RevertError.registerType(revertClass); -} - -/** - * Decode an ABI encoded revert error. - * Throws if the data cannot be decoded as a known RevertError type. - * @param bytes The ABI encoded revert error. Either a hex string or a Buffer. - * @param coerce Coerce unknown selectors into a `RawRevertError` type. - * @return A RevertError object. - */ -export function decodeBytesAsRevertError(bytes: string | Buffer, coerce: boolean = false): RevertError { - return RevertError.decode(bytes, coerce); -} - -/** - * Decode a thrown error. - * Throws if the data cannot be decoded as a known RevertError type. - * @param error Any thrown error. - * @param coerce Coerce unknown selectors into a `RawRevertError` type. - * @return A RevertError object. - */ -export function decodeThrownErrorAsRevertError(error: Error, coerce: boolean = false): RevertError { - if (error instanceof RevertError) { - return error; - } - return RevertError.decode(getThrownErrorRevertErrorBytes(error), coerce); -} - -/** - * Coerce a thrown error into a `RevertError`. Always succeeds. - * @param error Any thrown error. - * @return A RevertError object. - */ -export function coerceThrownErrorAsRevertError(error: Error): RevertError { - if (error instanceof RevertError) { - return error; - } - try { - return decodeThrownErrorAsRevertError(error, true); - } catch (err) { - if (isGanacheTransactionRevertError(error)) { - throw err; - } - // Handle geth transaction reverts. - if (isGethTransactionRevertError(error)) { - // Geth transaction reverts are opaque, meaning no useful data is returned, - // so we just return an AnyRevertError type. - return new AnyRevertError(); - } - // Coerce plain errors into a StringRevertError. - return new StringRevertError(error.message); - } -} - -/** - * Base type for revert errors. - */ -export abstract class RevertError extends Error { - // Map of types registered via `registerType`. - private static readonly _typeRegistry: ObjectMap = {}; - public readonly abi?: RevertErrorAbi; - public readonly values: ValueMap = {}; - protected readonly _raw?: string; - - /** - * Decode an ABI encoded revert error. - * Throws if the data cannot be decoded as a known RevertError type. - * @param bytes The ABI encoded revert error. Either a hex string or a Buffer. - * @param coerce Whether to coerce unknown selectors into a `RawRevertError` type. - * @return A RevertError object. - */ - public static decode(bytes: string | Buffer | RevertError, coerce: boolean = false): RevertError { - if (bytes instanceof RevertError) { - return bytes; - } - const _bytes = bytes instanceof Buffer ? ethUtil.bufferToHex(bytes) : ethUtil.addHexPrefix(bytes); - // tslint:disable-next-line: custom-no-magic-numbers - const selector = _bytes.slice(2, 10); - if (!(selector in RevertError._typeRegistry)) { - if (coerce) { - return new RawRevertError(bytes); - } - throw new Error(`Unknown selector: ${selector}`); - } - const { type, decoder } = RevertError._typeRegistry[selector]; - const instance = new type(); - try { - Object.assign(instance, { values: decoder(_bytes) }); - instance.message = instance.toString(); - return instance; - } catch (err) { - throw new Error( - `Bytes ${_bytes} cannot be decoded as a revert error of type ${instance.signature}: ${err.message}`, - ); - } - } - - /** - * Register a RevertError type so that it can be decoded by - * `RevertError.decode`. - * @param revertClass A class that inherits from RevertError. - */ - public static registerType(revertClass: RevertErrorType): void { - const instance = new revertClass(); - if (instance.selector in RevertError._typeRegistry) { - throw new Error(`RevertError type with signature "${instance.signature}" is already registered`); - } - if (_.isNil(instance.abi)) { - throw new Error(`Attempting to register a RevertError class with no ABI`); - } - RevertError._typeRegistry[instance.selector] = { - type: revertClass, - decoder: createDecoder(instance.abi), - }; - } - - /** - * Create a RevertError instance with optional parameter values. - * Parameters that are left undefined will not be tested in equality checks. - * @param declaration Function-style declaration of the revert (e.g., Error(string message)) - * @param values Optional mapping of parameters to values. - * @param raw Optional encoded form of the revert error. If supplied, this - * instance will be treated as a `RawRevertError`, meaning it can only - * match other `RawRevertError` types with the same encoded payload. - */ - protected constructor(name: string, declaration?: string, values?: ValueMap, raw?: string) { - super(createErrorMessage(name, values)); - if (declaration !== undefined) { - this.abi = declarationToAbi(declaration); - if (values !== undefined) { - _.assign(this.values, _.cloneDeep(values)); - } - } - this._raw = raw; - // Extending Error is tricky; we need to explicitly set the prototype. - Object.setPrototypeOf(this, new.target.prototype); - } - - /** - * Get the ABI name for this revert. - */ - get name(): string { - if (!_.isNil(this.abi)) { - return this.abi.name; - } - return `<${this.typeName}>`; - } - - /** - * Get the class name of this type. - */ - get typeName(): string { - // tslint:disable-next-line: no-string-literal - return this.constructor.name; - } - - /** - * Get the hex selector for this revert (without leading '0x'). - */ - get selector(): string { - if (!_.isNil(this.abi)) { - return toSelector(this.abi); - } - if (this._isRawType) { - // tslint:disable-next-line: custom-no-magic-numbers - return (this._raw as string).slice(2, 10); - } - return ''; - } - - /** - * Get the signature for this revert: e.g., 'Error(string)'. - */ - get signature(): string { - if (!_.isNil(this.abi)) { - return toSignature(this.abi); - } - return ''; - } - - /** - * Get the ABI arguments for this revert. - */ - get arguments(): DataItem[] { - if (!_.isNil(this.abi)) { - return this.abi.arguments || []; - } - return []; - } - - get [Symbol.toStringTag](): string { - return this.toString(); - } - - /** - * Compares this instance with another. - * Fails if instances are not of the same type. - * Only fields/values defined in both instances are compared. - * @param other Either another RevertError instance, hex-encoded bytes, or a Buffer of the ABI encoded revert. - * @return True if both instances match. - */ - public equals(other: RevertError | Buffer | string): boolean { - let _other = other; - if (_other instanceof Buffer) { - _other = ethUtil.bufferToHex(_other); - } - if (typeof _other === 'string') { - _other = RevertError.decode(_other); - } - if (!(_other instanceof RevertError)) { - return false; - } - // If either is of the `AnyRevertError` type, always succeed. - if (this._isAnyType || _other._isAnyType) { - return true; - } - // If either are raw types, they must match their raw data. - if (this._isRawType || _other._isRawType) { - return this._raw === _other._raw; - } - // Must be of same type. - if (this.constructor !== _other.constructor) { - return false; - } - // Must share the same parameter values if defined in both instances. - for (const name of Object.keys(this.values)) { - const a = this.values[name]; - const b = _other.values[name]; - if (a === b) { - continue; - } - if (!_.isNil(a) && !_.isNil(b)) { - const { type } = this._getArgumentByName(name); - if (!checkArgEquality(type, a, b)) { - return false; - } - } - } - return true; - } - - public encode(): string { - if (this._raw !== undefined) { - return this._raw; - } - if (!this._hasAllArgumentValues) { - throw new Error(`Instance of ${this.typeName} does not have all its parameter values set.`); - } - const encoder = createEncoder(this.abi as RevertErrorAbi); - return encoder(this.values); - } - - public toString(): string { - if (this._isRawType) { - return `${this.constructor.name}(${this._raw})`; - } - const values = _.omitBy(this.values, (v: any) => _.isNil(v)); - // tslint:disable-next-line: forin - for (const k in values) { - const { type: argType } = this._getArgumentByName(k); - if (argType === 'bytes') { - // Try to decode nested revert errors. - try { - values[k] = RevertError.decode(values[k] as any); - } catch (err) {} // tslint:disable-line:no-empty - } - } - const inner = _.isEmpty(values) ? '' : inspect(values); - return `${this.constructor.name}(${inner})`; - } - - private _getArgumentByName(name: string): DataItem { - const arg = _.find(this.arguments, (a: DataItem) => a.name === name); - if (_.isNil(arg)) { - throw new Error(`RevertError ${this.signature} has no argument named ${name}`); - } - return arg; - } - - private get _isAnyType(): boolean { - return _.isNil(this.abi) && _.isNil(this._raw); - } - - private get _isRawType(): boolean { - return !_.isNil(this._raw); - } - - private get _hasAllArgumentValues(): boolean { - if (_.isNil(this.abi) || _.isNil(this.abi.arguments)) { - return false; - } - for (const arg of this.abi.arguments) { - if (_.isNil(this.values[arg.name])) { - return false; - } - } - return true; - } -} - -const PARITY_TRANSACTION_REVERT_ERROR_MESSAGE = /^VM execution error/; -const GANACHE_TRANSACTION_REVERT_ERROR_MESSAGE = /^VM Exception while processing transaction: revert/; -const GETH_TRANSACTION_REVERT_ERROR_MESSAGE = /always failing transaction$/; - -interface GanacheTransactionRevertResult { - error: 'revert'; - program_counter: number; - return?: string; - reason?: string; -} - -interface GanacheTransactionRevertError extends Error { - results: { [hash: string]: GanacheTransactionRevertResult }; - hashes: string[]; -} - -interface ParityTransactionRevertError extends Error { - code: number; - data: string; - message: string; -} - -/** - * Try to extract the ecnoded revert error bytes from a thrown `Error`. - */ -export function getThrownErrorRevertErrorBytes( - error: Error | GanacheTransactionRevertError | ParityTransactionRevertError, -): string { - // Handle ganache transaction reverts. - if (isGanacheTransactionRevertError(error)) { - // Grab the first result attached. - const result = error.results[error.hashes[0]]; - // If a reason is provided, just wrap it in a StringRevertError - if (result.reason !== undefined) { - return new StringRevertError(result.reason).encode(); - } - if (result.return !== undefined && result.return !== '0x') { - return result.return; - } - } else if (isParityTransactionRevertError(error)) { - // Parity returns { data: 'Reverted 0xa6bcde47...', ... } - const { data } = error; - const hexDataIndex = data.indexOf('0x'); - if (hexDataIndex !== -1) { - return data.slice(hexDataIndex); - } - } else { - // Handle geth transaction reverts. - if (isGethTransactionRevertError(error)) { - // Geth transaction reverts are opaque, meaning no useful data is returned, - // so we do nothing. - } - } - throw new Error(`Cannot decode thrown Error "${error.message}" as a RevertError`); -} - -function isParityTransactionRevertError( - error: Error | ParityTransactionRevertError, -): error is ParityTransactionRevertError { - if (PARITY_TRANSACTION_REVERT_ERROR_MESSAGE.test(error.message) && 'code' in error && 'data' in error) { - return true; - } - return false; -} - -function isGanacheTransactionRevertError( - error: Error | GanacheTransactionRevertError, -): error is GanacheTransactionRevertError { - if (GANACHE_TRANSACTION_REVERT_ERROR_MESSAGE.test(error.message) && 'hashes' in error && 'results' in error) { - return true; - } - return false; -} - -function isGethTransactionRevertError(error: Error | GanacheTransactionRevertError): boolean { - return GETH_TRANSACTION_REVERT_ERROR_MESSAGE.test(error.message); -} - -/** - * RevertError type for standard string reverts. - */ -export class StringRevertError extends RevertError { - constructor(message?: string) { - super('StringRevertError', 'Error(string message)', { message }); - } -} - -/** - * Special RevertError type that matches with any other RevertError instance. - */ -export class AnyRevertError extends RevertError { - constructor() { - super('AnyRevertError'); - } -} - -/** - * Special RevertError type that is not decoded. - */ -export class RawRevertError extends RevertError { - constructor(encoded: string | Buffer) { - super( - 'RawRevertError', - undefined, - undefined, - typeof encoded === 'string' ? encoded : ethUtil.bufferToHex(encoded), - ); - } -} - -/** - * Create an error message for a RevertError. - * @param name The name of the RevertError. - * @param values The values for the RevertError. - */ -function createErrorMessage(name: string, values?: ValueMap): string { - if (values === undefined) { - return `${name}()`; - } - const _values = _.omitBy(values, (v: any) => _.isNil(v)); - const inner = _.isEmpty(_values) ? '' : inspect(_values); - return `${name}(${inner})`; -} - -/** - * Parse a solidity function declaration into a RevertErrorAbi object. - * @param declaration Function declaration (e.g., 'foo(uint256 bar)'). - * @return A RevertErrorAbi object. - */ -function declarationToAbi(declaration: string): RevertErrorAbi { - let m = /^\s*([_a-z][a-z0-9_]*)\((.*)\)\s*$/i.exec(declaration); - if (!m) { - throw new Error(`Invalid Revert Error signature: "${declaration}"`); - } - const [name, args] = m.slice(1); - const argList: string[] = _.filter(args.split(',')); - const argData: DataItem[] = _.map(argList, (a: string) => { - // Match a function parameter in the format 'TYPE ID', where 'TYPE' may be - // an array type. - m = /^\s*(([_a-z][a-z0-9_]*)(\[\d*\])*)\s+([_a-z][a-z0-9_]*)\s*$/i.exec(a); - if (!m) { - throw new Error(`Invalid Revert Error signature: "${declaration}"`); - } - // tslint:disable: custom-no-magic-numbers - return { - name: m[4], - type: m[1], - }; - // tslint:enable: custom-no-magic-numbers - }); - const r: RevertErrorAbi = { - type: 'error', - name, - arguments: _.isEmpty(argData) ? [] : argData, - }; - return r; -} - -function checkArgEquality(type: string, lhs: ArgTypes, rhs: ArgTypes): boolean { - // Try to compare as decoded revert errors first. - try { - return RevertError.decode(lhs as any).equals(RevertError.decode(rhs as any)); - } catch (err) { - // no-op - } - if (type === 'address') { - return normalizeAddress(lhs as string) === normalizeAddress(rhs as string); - } else if (type === 'bytes' || /^bytes(\d+)$/.test(type)) { - return normalizeBytes(lhs as string) === normalizeBytes(rhs as string); - } else if (type === 'string') { - return lhs === rhs; - } else if (/\[\d*\]$/.test(type)) { - // An array type. - // tslint:disable: custom-no-magic-numbers - // Arguments must be arrays and have the same dimensions. - if ((lhs as any[]).length !== (rhs as any[]).length) { - return false; - } - const m = /^(.+)\[(\d*)\]$/.exec(type) as string[]; - const baseType = m[1]; - const isFixedLength = m[2].length !== 0; - if (isFixedLength) { - const length = parseInt(m[2], 10); - // Fixed-size arrays have a fixed dimension. - if ((lhs as any[]).length !== length) { - return false; - } - } - // Recurse into sub-elements. - for (const [slhs, srhs] of _.zip(lhs as any[], rhs as any[])) { - if (!checkArgEquality(baseType, slhs, srhs)) { - return false; - } - } - return true; - // tslint:enable: no-magic-numbers - } - // tslint:disable-next-line - return new BigNumber((lhs as any) || 0).eq(rhs as any); -} - -function normalizeAddress(addr: string): string { - const ADDRESS_SIZE = 20; - return ethUtil.bufferToHex(ethUtil.setLengthLeft(ethUtil.toBuffer(ethUtil.addHexPrefix(addr)), ADDRESS_SIZE)); -} - -function normalizeBytes(bytes: string): string { - return ethUtil.addHexPrefix(bytes).toLowerCase(); -} - -function createEncoder(abi: RevertErrorAbi): (values: ObjectMap) => string { - const encoder = AbiEncoder.createMethod(abi.name, abi.arguments || []); - return (values: ObjectMap): string => { - const valuesArray = _.map(abi.arguments, (arg: DataItem) => values[arg.name]); - return encoder.encode(valuesArray); - }; -} - -function createDecoder(abi: RevertErrorAbi): (hex: string) => ValueMap { - const encoder = AbiEncoder.createMethod(abi.name, abi.arguments || []); - return (hex: string): ValueMap => { - return encoder.decode(hex) as ValueMap; - }; -} - -function toSignature(abi: RevertErrorAbi): string { - const argTypes = _.map(abi.arguments, (a: DataItem) => a.type); - const args = argTypes.join(','); - return `${abi.name}(${args})`; -} - -function toSelector(abi: RevertErrorAbi): string { - return ( - ethUtil - .sha3(Buffer.from(toSignature(abi))) - // tslint:disable-next-line: custom-no-magic-numbers - .slice(0, 4) - .toString('hex') - ); -} - -// Register StringRevertError -RevertError.registerType(StringRevertError); -// tslint:disable-next-line max-file-line-count diff --git a/packages/utils/src/revert_errors/broker/revert_errors.ts b/packages/utils/src/revert_errors/broker/revert_errors.ts deleted file mode 100644 index 1e634813d4..0000000000 --- a/packages/utils/src/revert_errors/broker/revert_errors.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { BigNumber } from '../../configured_bignumber'; -import { RevertError } from '../../revert_error'; - -// tslint:disable:max-classes-per-file - -export class InvalidFromAddressError extends RevertError { - constructor(from?: string) { - super('InvalidFromAddressError', 'InvalidFromAddressError(address from)', { from }); - } -} - -export class AmountsLengthMustEqualOneError extends RevertError { - constructor(amountsLength?: BigNumber | number | string) { - super('AmountsLengthMustEqualOneError', 'AmountsLengthMustEqualOneError(uint256 amountsLength)', { - amountsLength, - }); - } -} - -export class TooFewBrokerAssetsProvidedError extends RevertError { - constructor(numBrokeredAssets?: BigNumber | number | string) { - super('TooFewBrokerAssetsProvidedError', 'TooFewBrokerAssetsProvidedError(uint256 numBrokeredAssets)', { - numBrokeredAssets, - }); - } -} - -export class InvalidFunctionSelectorError extends RevertError { - constructor(selector?: string) { - super('InvalidFunctionSelectorError', 'InvalidFunctionSelectorError(bytes4 selector)', { selector }); - } -} - -export class OnlyERC1155ProxyError extends RevertError { - constructor(sender?: string) { - super('OnlyERC1155ProxyError', 'OnlyERC1155ProxyError(address sender)', { sender }); - } -} - -const types = [ - InvalidFromAddressError, - AmountsLengthMustEqualOneError, - TooFewBrokerAssetsProvidedError, - InvalidFunctionSelectorError, - OnlyERC1155ProxyError, -]; - -// Register the types we've defined. -for (const type of types) { - RevertError.registerType(type); -} diff --git a/packages/utils/src/revert_errors/coordinator/revert_errors.ts b/packages/utils/src/revert_errors/coordinator/revert_errors.ts deleted file mode 100644 index a117890b38..0000000000 --- a/packages/utils/src/revert_errors/coordinator/revert_errors.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { BigNumber } from '../../configured_bignumber'; -import { RevertError } from '../../revert_error'; - -// tslint:disable:max-classes-per-file - -export enum SignatureErrorCodes { - InvalidLength, - Unsupported, - Illegal, - Invalid, -} - -export class SignatureError extends RevertError { - constructor(errorCode?: SignatureErrorCodes, hash?: string, signature?: string) { - super('SignatureError', 'SignatureError(uint8 errorCode, bytes32 hash, bytes signature)', { - errorCode, - hash, - signature, - }); - } -} - -export class InvalidOriginError extends RevertError { - constructor(expectedOrigin?: string) { - super('InvalidOriginError', 'InvalidOriginError(address expectedOrigin)', { expectedOrigin }); - } -} - -export class ApprovalExpiredError extends RevertError { - constructor(transactionHash?: string, approvalExpirationTime?: BigNumber | number | string) { - super('ApprovalExpiredError', 'ApprovalExpiredError(bytes32 transactionHash, uint256 approvalExpirationTime)', { - transactionHash, - approvalExpirationTime, - }); - } -} - -export class InvalidApprovalSignatureError extends RevertError { - constructor(transactionHash?: string, approverAddress?: string) { - super( - 'InvalidApprovalSignatureError', - 'InvalidApprovalSignatureError(bytes32 transactionHash, address approverAddress)', - { transactionHash, approverAddress }, - ); - } -} - -const types = [SignatureError, InvalidOriginError, ApprovalExpiredError, InvalidApprovalSignatureError]; - -// Register the types we've defined. -for (const type of types) { - RevertError.registerType(type); -} diff --git a/packages/utils/src/revert_errors/exchange-forwarder/revert_errors.ts b/packages/utils/src/revert_errors/exchange-forwarder/revert_errors.ts deleted file mode 100644 index 0b078269ea..0000000000 --- a/packages/utils/src/revert_errors/exchange-forwarder/revert_errors.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { BigNumber } from '../../configured_bignumber'; -import { RevertError } from '../../revert_error'; - -// tslint:disable:max-classes-per-file - -export class UnregisteredAssetProxyError extends RevertError { - constructor() { - super('UnregisteredAssetProxyError', 'UnregisteredAssetProxyError()', {}); - } -} - -export class CompleteBuyFailedError extends RevertError { - constructor( - expectedAssetBuyAmount?: BigNumber | number | string, - actualAssetBuyAmount?: BigNumber | number | string, - ) { - super( - 'CompleteBuyFailedError', - 'CompleteBuyFailedError(uint256 expectedAssetBuyAmount, uint256 actualAssetBuyAmount)', - { expectedAssetBuyAmount, actualAssetBuyAmount }, - ); - } -} - -export class CompleteSellFailedError extends RevertError { - constructor( - expectedAssetSellAmount?: BigNumber | number | string, - actualAssetSellAmount?: BigNumber | number | string, - ) { - super( - 'CompleteSellFailedError', - 'CompleteSellFailedError(uint256 expectedAssetSellAmount, uint256 actualAssetSellAmount)', - { expectedAssetSellAmount, actualAssetSellAmount }, - ); - } -} - -export class UnsupportedFeeError extends RevertError { - constructor(takerFeeAssetData?: string) { - super('UnsupportedFeeError', 'UnsupportedFeeError(bytes takerFeeAssetData)', { takerFeeAssetData }); - } -} - -export class OverspentWethError extends RevertError { - constructor(wethSpent?: BigNumber | number | string, msgValue?: BigNumber | number | string) { - super('OverspentWethError', 'OverspentWethError(uint256 wethSpent, uint256 msgValue)', { - wethSpent, - msgValue, - }); - } -} - -export class MsgValueCannotEqualZeroError extends RevertError { - constructor() { - super('MsgValueCannotEqualZeroError', 'MsgValueCannotEqualZeroError()', {}); - } -} - -const types = [ - UnregisteredAssetProxyError, - CompleteBuyFailedError, - CompleteSellFailedError, - UnsupportedFeeError, - OverspentWethError, - MsgValueCannotEqualZeroError, -]; - -// Register the types we've defined. -for (const type of types) { - RevertError.registerType(type); -} diff --git a/packages/utils/src/revert_errors/exchange-libs/lib_math_revert_errors.ts b/packages/utils/src/revert_errors/exchange-libs/lib_math_revert_errors.ts deleted file mode 100644 index 860fd3223b..0000000000 --- a/packages/utils/src/revert_errors/exchange-libs/lib_math_revert_errors.ts +++ /dev/null @@ -1,33 +0,0 @@ -import * as _ from 'lodash'; - -import { BigNumber } from '../../configured_bignumber'; -import { RevertError } from '../../revert_error'; - -// tslint:disable:max-classes-per-file - -export class DivisionByZeroError extends RevertError { - constructor() { - super('DivisionByZeroError', 'DivisionByZeroError()', {}); - } -} - -export class RoundingError extends RevertError { - constructor( - numerator?: BigNumber | number | string, - denominator?: BigNumber | number | string, - target?: BigNumber | number | string, - ) { - super('RoundingError', 'RoundingError(uint256 numerator, uint256 denominator, uint256 target)', { - numerator, - denominator, - target, - }); - } -} - -const types = [DivisionByZeroError, RoundingError]; - -// Register the types we've defined. -for (const type of types) { - RevertError.registerType(type); -} diff --git a/packages/utils/src/revert_errors/exchange/revert_errors.ts b/packages/utils/src/revert_errors/exchange/revert_errors.ts deleted file mode 100644 index 83cece37fb..0000000000 --- a/packages/utils/src/revert_errors/exchange/revert_errors.ts +++ /dev/null @@ -1,289 +0,0 @@ -import { OrderStatus } from '@0x/types'; -import * as _ from 'lodash'; - -import { BigNumber } from '../../configured_bignumber'; -import { RevertError } from '../../revert_error'; - -// tslint:disable:max-classes-per-file - -export enum BatchMatchOrdersErrorCodes { - ZeroLeftOrders, - ZeroRightOrders, - InvalidLengthLeftSignatures, - InvalidLengthRightSignatures, -} - -export enum ExchangeContextErrorCodes { - InvalidMaker, - InvalidTaker, - InvalidSender, -} - -export enum FillErrorCode { - InvalidTakerAmount, - TakerOverpay, - Overfill, - InvalidFillPrice, -} - -export enum SignatureErrorCode { - BadOrderSignature, - BadTransactionSignature, - InvalidLength, - Unsupported, - Illegal, - InappropriateSignatureType, - InvalidSigner, -} - -export enum AssetProxyDispatchErrorCode { - InvalidAssetDataLength, - UnknownAssetProxy, -} - -export enum TransactionErrorCode { - AlreadyExecuted, - Expired, -} - -export enum IncompleteFillErrorCode { - IncompleteMarketBuyOrders, - IncompleteMarketSellOrders, - IncompleteFillOrder, -} - -export class BatchMatchOrdersError extends RevertError { - constructor(error?: BatchMatchOrdersErrorCodes) { - super('BatchMatchOrdersError', 'BatchMatchOrdersError(uint8 error)', { error }); - } -} - -export class SignatureError extends RevertError { - constructor(error?: SignatureErrorCode, hash?: string, signer?: string, signature?: string) { - super('SignatureError', 'SignatureError(uint8 error, bytes32 hash, address signer, bytes signature)', { - error, - hash, - signer, - signature, - }); - } -} - -export class SignatureValidatorNotApprovedError extends RevertError { - constructor(signer?: string, validator?: string) { - super( - 'SignatureValidatorNotApprovedError', - 'SignatureValidatorNotApprovedError(address signer, address validator)', - { - signer, - validator, - }, - ); - } -} - -export class SignatureWalletError extends RevertError { - constructor(hash?: string, wallet?: string, signature?: string, errorData?: string) { - super( - 'SignatureWalletError', - 'SignatureWalletError(bytes32 hash, address wallet, bytes signature, bytes errorData)', - { - hash, - wallet, - signature, - errorData, - }, - ); - } -} - -export class EIP1271SignatureError extends RevertError { - constructor(verifyingContract?: string, data?: string, signature?: string, errorData?: string) { - super( - 'EIP1271SignatureError', - 'EIP1271SignatureError(address verifyingContract, bytes data, bytes signature, bytes errorData)', - { - verifyingContract, - data, - signature, - errorData, - }, - ); - } -} - -export class OrderStatusError extends RevertError { - constructor(orderHash?: string, status?: OrderStatus) { - super('OrderStatusError', 'OrderStatusError(bytes32 orderHash, uint8 status)', { orderHash, status }); - } -} - -export class FillError extends RevertError { - constructor(error?: FillErrorCode, orderHash?: string) { - super('FillError', 'FillError(uint8 error, bytes32 orderHash)', { error, orderHash }); - } -} - -export class OrderEpochError extends RevertError { - constructor(maker?: string, sender?: string, currentEpoch?: BigNumber) { - super('OrderEpochError', 'OrderEpochError(address maker, address sender, uint256 currentEpoch)', { - maker, - sender, - currentEpoch, - }); - } -} - -export class AssetProxyExistsError extends RevertError { - constructor(assetProxyId?: string, assetProxy?: string) { - super('AssetProxyExistsError', 'AssetProxyExistsError(bytes4 assetProxyId, address assetProxy)', { - assetProxyId, - assetProxy, - }); - } -} - -export class AssetProxyDispatchError extends RevertError { - constructor(error?: AssetProxyDispatchErrorCode, orderHash?: string, assetData?: string) { - super('AssetProxyDispatchError', 'AssetProxyDispatchError(uint8 error, bytes32 orderHash, bytes assetData)', { - error, - orderHash, - assetData, - }); - } -} - -export class AssetProxyTransferError extends RevertError { - constructor(orderHash?: string, assetData?: string, errorData?: string) { - super( - 'AssetProxyTransferError', - 'AssetProxyTransferError(bytes32 orderHash, bytes assetData, bytes errorData)', - { - orderHash, - assetData, - errorData, - }, - ); - } -} - -export class NegativeSpreadError extends RevertError { - constructor(leftOrderHash?: string, rightOrderHash?: string) { - super('NegativeSpreadError', 'NegativeSpreadError(bytes32 leftOrderHash, bytes32 rightOrderHash)', { - leftOrderHash, - rightOrderHash, - }); - } -} - -export class TransactionError extends RevertError { - constructor(error?: TransactionErrorCode, transactionHash?: string) { - super('TransactionError', 'TransactionError(uint8 error, bytes32 transactionHash)', { error, transactionHash }); - } -} - -export class TransactionExecutionError extends RevertError { - constructor(transactionHash?: string, errorData?: string) { - super('TransactionExecutionError', 'TransactionExecutionError(bytes32 transactionHash, bytes errorData)', { - transactionHash, - errorData, - }); - } -} - -export class TransactionGasPriceError extends RevertError { - constructor(transactionHash?: string, actualGasPrice?: BigNumber, requiredGasPrice?: BigNumber) { - super( - 'TransactionGasPriceError', - 'TransactionGasPriceError(bytes32 transactionHash, uint256 actualGasPrice, uint256 requiredGasPrice)', - { - transactionHash, - actualGasPrice, - requiredGasPrice, - }, - ); - } -} - -export class TransactionInvalidContextError extends RevertError { - constructor(transactionHash?: string, currentContextAddress?: string) { - super( - 'TransactionInvalidContextError', - 'TransactionInvalidContextError(bytes32 transactionHash, address currentContextAddress)', - { - transactionHash, - currentContextAddress, - }, - ); - } -} - -export class IncompleteFillError extends RevertError { - constructor( - error?: IncompleteFillErrorCode, - expectedAssetFillAmount?: BigNumber, - actualAssetFillAmount?: BigNumber, - ) { - super( - 'IncompleteFillError', - 'IncompleteFillError(uint8 error, uint256 expectedAssetFillAmount, uint256 actualAssetFillAmount)', - { - error, - expectedAssetFillAmount, - actualAssetFillAmount, - }, - ); - } -} - -export class ExchangeInvalidContextError extends RevertError { - constructor(error?: ExchangeContextErrorCodes, orderHash?: string, contextAddress?: string) { - super( - 'ExchangeInvalidContextError', - 'ExchangeInvalidContextError(uint8 error, bytes32 orderHash, address contextAddress)', - { error, orderHash, contextAddress }, - ); - } -} -export class PayProtocolFeeError extends RevertError { - constructor( - orderHash?: string, - protocolFee?: BigNumber, - makerAddress?: string, - takerAddress?: string, - errorData?: string, - ) { - super( - 'PayProtocolFeeError', - 'PayProtocolFeeError(bytes32 orderHash, uint256 protocolFee, address makerAddress, address takerAddress, bytes errorData)', - { orderHash, protocolFee, makerAddress, takerAddress, errorData }, - ); - } -} - -const types = [ - AssetProxyExistsError, - AssetProxyDispatchError, - AssetProxyTransferError, - BatchMatchOrdersError, - EIP1271SignatureError, - ExchangeInvalidContextError, - FillError, - IncompleteFillError, - NegativeSpreadError, - OrderEpochError, - OrderStatusError, - PayProtocolFeeError, - SignatureError, - SignatureValidatorNotApprovedError, - SignatureWalletError, - TransactionError, - TransactionExecutionError, - TransactionGasPriceError, - TransactionInvalidContextError, -]; - -// Register the types we've defined. -for (const type of types) { - RevertError.registerType(type); -} diff --git a/packages/utils/src/revert_errors/extensions/lib_asset_data_transfer_revert_errors.ts b/packages/utils/src/revert_errors/extensions/lib_asset_data_transfer_revert_errors.ts deleted file mode 100644 index d2c6944994..0000000000 --- a/packages/utils/src/revert_errors/extensions/lib_asset_data_transfer_revert_errors.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { BigNumber } from '../../configured_bignumber'; -import { RevertError } from '../../revert_error'; - -// tslint:disable:max-classes-per-file - -export class UnsupportedAssetProxyError extends RevertError { - constructor(proxyId?: string) { - super('UnsupportedAssetProxyError', 'UnsupportedAssetProxyError(bytes4 proxyId)', { proxyId }); - } -} - -export class Erc721AmountMustEqualOneError extends RevertError { - constructor(amount?: BigNumber | number | string) { - super('Erc721AmountMustEqualOneError', 'Erc721AmountMustEqualOneError(uint256 amount)', { - amount, - }); - } -} - -const types = [UnsupportedAssetProxyError, Erc721AmountMustEqualOneError]; - -// Register the types we've defined. -for (const type of types) { - RevertError.registerType(type); -} diff --git a/packages/utils/src/revert_errors/extensions/mixin_weth_utils_revert_errors.ts b/packages/utils/src/revert_errors/extensions/mixin_weth_utils_revert_errors.ts deleted file mode 100644 index 79d85c5a56..0000000000 --- a/packages/utils/src/revert_errors/extensions/mixin_weth_utils_revert_errors.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { BigNumber } from '../../configured_bignumber'; -import { RevertError } from '../../revert_error'; - -// tslint:disable:max-classes-per-file - -export class UnregisteredAssetProxyError extends RevertError { - constructor() { - super('UnregisteredAssetProxyError', 'UnregisteredAssetProxyError()', {}); - } -} - -export class InsufficientEthForFeeError extends RevertError { - constructor(ethFeeRequired?: BigNumber | number | string, ethAvailable?: BigNumber | number | string) { - super( - 'InsufficientEthForFeeError', - 'InsufficientEthForFeeError(uint256 ethFeeRequired, uint256 ethAvailable)', - { ethFeeRequired, ethAvailable }, - ); - } -} - -export class DefaultFunctionWethContractOnlyError extends RevertError { - constructor(senderAddress?: string) { - super('DefaultFunctionWethContractOnlyError', 'DefaultFunctionWethContractOnlyError(address senderAddress)', { - senderAddress, - }); - } -} - -export class EthFeeLengthMismatchError extends RevertError { - constructor(ethFeesLength?: BigNumber | number | string, feeRecipientsLength?: BigNumber | number | string) { - super( - 'EthFeeLengthMismatchError', - 'EthFeeLengthMismatchError(uint256 ethFeesLength, uint256 feeRecipientsLength)', - { - ethFeesLength, - feeRecipientsLength, - }, - ); - } -} - -const types = [InsufficientEthForFeeError, DefaultFunctionWethContractOnlyError, EthFeeLengthMismatchError]; - -// Register the types we've defined. -for (const type of types) { - RevertError.registerType(type); -} diff --git a/packages/utils/src/revert_errors/staking/fixed_math_revert_errors.ts b/packages/utils/src/revert_errors/staking/fixed_math_revert_errors.ts deleted file mode 100644 index fafe47cf2d..0000000000 --- a/packages/utils/src/revert_errors/staking/fixed_math_revert_errors.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { BigNumber } from '../../configured_bignumber'; -import { RevertError } from '../../revert_error'; - -// tslint:disable:max-classes-per-file - -export enum ValueErrorCodes { - TooSmall, - TooLarge, -} - -export enum BinOpErrorCodes { - AdditionOverflow, - MultiplicationOverflow, - DivisionByZero, - DivisionOverflow, -} - -export class SignedValueError extends RevertError { - constructor(error?: ValueErrorCodes, n?: BigNumber | number | string) { - super('SignedValueError', 'SignedValueError(uint8 error, int256 n)', { - error, - n, - }); - } -} - -export class UnsignedValueError extends RevertError { - constructor(error?: ValueErrorCodes, n?: BigNumber | number | string) { - super('UnsignedValueError', 'UnsignedValueError(uint8 error, uint256 n)', { - error, - n, - }); - } -} - -export class BinOpError extends RevertError { - constructor(error?: BinOpErrorCodes, a?: BigNumber | number | string, b?: BigNumber | number | string) { - super('BinOpError', 'BinOpError(uint8 error, int256 a, int256 b)', { - error, - a, - b, - }); - } -} - -const types = [SignedValueError, UnsignedValueError, BinOpError]; - -// Register the types we've defined. -for (const type of types) { - RevertError.registerType(type); -} diff --git a/packages/utils/src/revert_errors/staking/staking_revert_errors.ts b/packages/utils/src/revert_errors/staking/staking_revert_errors.ts deleted file mode 100644 index 82a3816c3b..0000000000 --- a/packages/utils/src/revert_errors/staking/staking_revert_errors.ts +++ /dev/null @@ -1,205 +0,0 @@ -import { BigNumber } from '../../configured_bignumber'; -import { RevertError } from '../../revert_error'; - -// tslint:disable:max-classes-per-file - -export enum MakerPoolAssignmentErrorCodes { - MakerAddressAlreadyRegistered, - MakerAddressNotRegistered, - MakerAddressNotPendingAdd, - PoolIsFull, -} - -export enum OperatorShareErrorCodes { - OperatorShareTooLarge, - CanOnlyDecreaseOperatorShare, -} - -export enum InvalidParamValueErrorCodes { - InvalidCobbDouglasAlpha, - InvalidRewardDelegatedStakeWeight, - InvalidMaximumMakersInPool, - InvalidMinimumPoolStake, - InvalidEpochDuration, -} - -export enum InitializationErrorCodes { - MixinSchedulerAlreadyInitialized, - MixinParamsAlreadyInitialized, -} - -export enum ExchangeManagerErrorCodes { - ExchangeAlreadyRegistered, - ExchangeNotRegistered, -} - -export class OnlyCallableByExchangeError extends RevertError { - constructor(senderAddress?: string) { - super('OnlyCallableByExchangeError', 'OnlyCallableByExchangeError(address senderAddress)', { senderAddress }); - } -} - -export class ExchangeManagerError extends RevertError { - constructor(errorCode?: ExchangeManagerErrorCodes, senderAddress?: string) { - super('ExchangeManagerError', 'ExchangeManagerError(uint8 errorCode, address senderAddress)', { - errorCode, - senderAddress, - }); - } -} - -export class InsufficientBalanceError extends RevertError { - constructor(amount?: BigNumber | number | string, balance?: BigNumber | number | string) { - super('InsufficientBalanceError', 'InsufficientBalanceError(uint256 amount, uint256 balance)', { - amount, - balance, - }); - } -} - -export class OnlyCallableByPoolOperatorError extends RevertError { - constructor(senderAddress?: string, poolId?: string) { - super( - 'OnlyCallableByPoolOperatorError', - 'OnlyCallableByPoolOperatorError(address senderAddress, bytes32 poolId)', - { senderAddress, poolId }, - ); - } -} - -export class MakerPoolAssignmentError extends RevertError { - constructor(error?: MakerPoolAssignmentErrorCodes, makerAddress?: string, poolId?: string) { - super( - 'MakerPoolAssignmentError', - 'MakerPoolAssignmentError(uint8 error, address makerAddress, bytes32 poolId)', - { - error, - makerAddress, - poolId, - }, - ); - } -} - -export class BlockTimestampTooLowError extends RevertError { - constructor(epochEndTime?: BigNumber | number | string, currentBlockTimestamp?: BigNumber | number | string) { - super( - 'BlockTimestampTooLowError', - 'BlockTimestampTooLowError(uint256 epochEndTime, uint256 currentBlockTimestamp)', - { epochEndTime, currentBlockTimestamp }, - ); - } -} - -export class OnlyCallableByStakingContractError extends RevertError { - constructor(senderAddress?: string) { - super('OnlyCallableByStakingContractError', 'OnlyCallableByStakingContractError(address senderAddress)', { - senderAddress, - }); - } -} - -export class OnlyCallableIfInCatastrophicFailureError extends RevertError { - constructor() { - super('OnlyCallableIfInCatastrophicFailureError', 'OnlyCallableIfInCatastrophicFailureError()', {}); - } -} - -export class OnlyCallableIfNotInCatastrophicFailureError extends RevertError { - constructor() { - super('OnlyCallableIfNotInCatastrophicFailureError', 'OnlyCallableIfNotInCatastrophicFailureError()', {}); - } -} - -export class OperatorShareError extends RevertError { - constructor(error?: OperatorShareErrorCodes, poolId?: string, operatorShare?: BigNumber | number | string) { - super('OperatorShareError', 'OperatorShareError(uint8 error, bytes32 poolId, uint32 operatorShare)', { - error, - poolId, - operatorShare, - }); - } -} - -export class PoolExistenceError extends RevertError { - constructor(poolId?: string, alreadyExists?: boolean) { - super('PoolExistenceError', 'PoolExistenceError(bytes32 poolId, bool alreadyExists)', { - poolId, - alreadyExists, - }); - } -} - -export class InvalidParamValueError extends RevertError { - constructor(error?: InvalidParamValueErrorCodes) { - super('InvalidParamValueError', 'InvalidParamValueError(uint8 error)', { - error, - }); - } -} - -export class InvalidProtocolFeePaymentError extends RevertError { - constructor( - expectedProtocolFeePaid?: BigNumber | number | string, - actualProtocolFeePaid?: BigNumber | number | string, - ) { - super( - 'InvalidProtocolFeePaymentError', - 'InvalidProtocolFeePaymentError(uint256 expectedProtocolFeePaid, uint256 actualProtocolFeePaid)', - { expectedProtocolFeePaid, actualProtocolFeePaid }, - ); - } -} - -export class InitializationError extends RevertError { - constructor(error?: InitializationErrorCodes) { - super('InitializationError', 'InitializationError(uint8 error)', { error }); - } -} - -export class ProxyDestinationCannotBeNilError extends RevertError { - constructor() { - super('ProxyDestinationCannotBeNilError', 'ProxyDestinationCannotBeNilError()', {}); - } -} - -export class PreviousEpochNotFinalizedError extends RevertError { - constructor(closingEpoch?: BigNumber | number | string, unfinalizedPoolsRemaining?: BigNumber | number | string) { - super( - 'PreviousEpochNotFinalizedError', - 'PreviousEpochNotFinalizedError(uint256 closingEpoch, uint256 unfinalizedPoolsRemaining)', - { closingEpoch, unfinalizedPoolsRemaining }, - ); - } -} - -export class PoolNotFinalizedError extends RevertError { - constructor(poolId: string, epoch: BigNumber | number | string) { - super('PoolNotFinalizedError', 'PoolNotFinalizedError(bytes32 poolId, uint256 epoch)', { poolId, epoch }); - } -} - -const types = [ - BlockTimestampTooLowError, - ExchangeManagerError, - InitializationError, - InsufficientBalanceError, - InvalidProtocolFeePaymentError, - InvalidParamValueError, - MakerPoolAssignmentError, - OnlyCallableByExchangeError, - OnlyCallableByPoolOperatorError, - OnlyCallableByStakingContractError, - OnlyCallableIfInCatastrophicFailureError, - OnlyCallableIfNotInCatastrophicFailureError, - OperatorShareError, - PoolExistenceError, - PreviousEpochNotFinalizedError, - ProxyDestinationCannotBeNilError, - PoolNotFinalizedError, -]; - -// Register the types we've defined. -for (const type of types) { - RevertError.registerType(type); -} diff --git a/packages/utils/src/revert_errors/utils/authorizable_revert_errors.ts b/packages/utils/src/revert_errors/utils/authorizable_revert_errors.ts deleted file mode 100644 index e7f5d9bf97..0000000000 --- a/packages/utils/src/revert_errors/utils/authorizable_revert_errors.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { BigNumber } from '../../configured_bignumber'; -import { RevertError } from '../../revert_error'; - -// tslint:disable:max-classes-per-file -export class AuthorizedAddressMismatchError extends RevertError { - constructor(authorized?: string, target?: string) { - super('AuthorizedAddressMismatchError', 'AuthorizedAddressMismatchError(address authorized, address target)', { - authorized, - target, - }); - } -} - -export class IndexOutOfBoundsError extends RevertError { - constructor(index?: BigNumber, len?: BigNumber) { - super('IndexOutOfBoundsError', 'IndexOutOfBoundsError(uint256 index, uint256 len)', { index, len }); - } -} - -export class SenderNotAuthorizedError extends RevertError { - constructor(sender?: string) { - super('SenderNotAuthorizedError', 'SenderNotAuthorizedError(address sender)', { sender }); - } -} - -export class TargetAlreadyAuthorizedError extends RevertError { - constructor(target?: string) { - super('TargetAlreadyAuthorizedError', 'TargetAlreadyAuthorizedError(address target)', { target }); - } -} - -export class TargetNotAuthorizedError extends RevertError { - constructor(target?: string) { - super('TargetNotAuthorizedError', 'TargetNotAuthorizedError(address target)', { target }); - } -} - -export class ZeroCantBeAuthorizedError extends RevertError { - constructor() { - super('ZeroCantBeAuthorizedError', 'ZeroCantBeAuthorizedError()', {}); - } -} - -const types = [ - AuthorizedAddressMismatchError, - IndexOutOfBoundsError, - SenderNotAuthorizedError, - TargetAlreadyAuthorizedError, - TargetNotAuthorizedError, - ZeroCantBeAuthorizedError, -]; - -// Register the types we've defined. -for (const type of types) { - RevertError.registerType(type); -} diff --git a/packages/utils/src/revert_errors/utils/lib_address_array_revert_errors.ts b/packages/utils/src/revert_errors/utils/lib_address_array_revert_errors.ts deleted file mode 100644 index d9d0e878b9..0000000000 --- a/packages/utils/src/revert_errors/utils/lib_address_array_revert_errors.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { BigNumber } from '../../configured_bignumber'; -import { RevertError } from '../../revert_error'; - -export class MismanagedMemoryError extends RevertError { - constructor(freeMemPtr?: BigNumber, addressArrayEndPtr?: BigNumber) { - super('MismanagedMemoryError', 'MismanagedMemoryError(uint256 freeMemPtr, uint256 addressArrayEndPtr)', { - freeMemPtr, - addressArrayEndPtr, - }); - } -} - -// Register the MismanagedMemoryError type -RevertError.registerType(MismanagedMemoryError); diff --git a/packages/utils/src/revert_errors/utils/lib_bytes_revert_errors.ts b/packages/utils/src/revert_errors/utils/lib_bytes_revert_errors.ts deleted file mode 100644 index a83e5013ce..0000000000 --- a/packages/utils/src/revert_errors/utils/lib_bytes_revert_errors.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { BigNumber } from '../../configured_bignumber'; -import { RevertError } from '../../revert_error'; - -export enum InvalidByteOperationErrorCodes { - FromLessThanOrEqualsToRequired, - ToLessThanOrEqualsLengthRequired, - LengthGreaterThanZeroRequired, - LengthGreaterThanOrEqualsFourRequired, - LengthGreaterThanOrEqualsTwentyRequired, - LengthGreaterThanOrEqualsThirtyTwoRequired, - LengthGreaterThanOrEqualsNestedBytesLengthRequired, - DestinationLengthGreaterThanOrEqualSourceLengthRequired, -} - -export class InvalidByteOperationError extends RevertError { - constructor(error?: InvalidByteOperationErrorCodes, offset?: BigNumber, required?: BigNumber) { - super('InvalidByteOperationError', 'InvalidByteOperationError(uint8 error, uint256 offset, uint256 required)', { - error, - offset, - required, - }); - } -} - -// Register the InvalidByteOperationError type -RevertError.registerType(InvalidByteOperationError); diff --git a/packages/utils/src/revert_errors/utils/ownable_revert_errors.ts b/packages/utils/src/revert_errors/utils/ownable_revert_errors.ts deleted file mode 100644 index 14e18df617..0000000000 --- a/packages/utils/src/revert_errors/utils/ownable_revert_errors.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { RevertError } from '../../revert_error'; - -// tslint:disable:max-classes-per-file -export class OnlyOwnerError extends RevertError { - constructor(sender?: string, owner?: string) { - super('OnlyOwnerError', 'OnlyOwnerError(address sender, address owner)', { - sender, - owner, - }); - } -} - -export class TransferOwnerToZeroError extends RevertError { - constructor() { - super('TransferOwnerToZeroError', 'TransferOwnerToZeroError()', {}); - } -} - -const types = [OnlyOwnerError, TransferOwnerToZeroError]; - -// Register the types we've defined. -for (const type of types) { - RevertError.registerType(type); -} diff --git a/packages/utils/src/revert_errors/utils/reentrancy_guard_revert_errors.ts b/packages/utils/src/revert_errors/utils/reentrancy_guard_revert_errors.ts deleted file mode 100644 index 75cf0c7fe1..0000000000 --- a/packages/utils/src/revert_errors/utils/reentrancy_guard_revert_errors.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { RevertError } from '../../revert_error'; - -export class IllegalReentrancyError extends RevertError { - constructor() { - super('IllegalReentrancyError', 'IllegalReentrancyError()', {}); - } -} - -// Register the IllegalReentrancyError type -RevertError.registerType(IllegalReentrancyError); diff --git a/packages/utils/src/revert_errors/utils/safe_math_revert_errors.ts b/packages/utils/src/revert_errors/utils/safe_math_revert_errors.ts deleted file mode 100644 index b90f11b1d4..0000000000 --- a/packages/utils/src/revert_errors/utils/safe_math_revert_errors.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { BigNumber } from '../../configured_bignumber'; -import { RevertError } from '../../revert_error'; - -// tslint:disable:max-classes-per-file - -export enum BinOpErrorCodes { - AdditionOverflow, - MultiplicationOverflow, - SubtractionUnderflow, - DivisionByZero, -} - -export enum DowncastErrorCodes { - ValueTooLargeToDowncastToUint32, - ValueTooLargeToDowncastToUint64, - ValueTooLargeToDowncastToUint96, -} - -export class Uint256BinOpError extends RevertError { - constructor(error?: BinOpErrorCodes, a?: BigNumber, b?: BigNumber) { - super('Uint256BinOpError', 'Uint256BinOpError(uint8 error, uint256 a, uint256 b)', { - error, - a, - b, - }); - } -} - -export class Uint96BinOpError extends RevertError { - constructor(error?: BinOpErrorCodes, a?: BigNumber, b?: BigNumber) { - super('Uint96BinOpError', 'Uint96BinOpError(uint8 error, uint96 a, uint96 b)', { - error, - a, - b, - }); - } -} - -export class Uint64BinOpError extends RevertError { - constructor(error?: BinOpErrorCodes, a?: BigNumber, b?: BigNumber) { - super('Uint64BinOpError', 'Uint64BinOpError(uint8 error, uint64 a, uint64 b)', { - error, - a, - b, - }); - } -} - -export class Uint256DowncastError extends RevertError { - constructor(error?: DowncastErrorCodes, a?: BigNumber) { - super('Uint256DowncastError', 'Uint256DowncastError(uint8 error, uint256 a)', { - error, - a, - }); - } -} - -const types = [Uint256BinOpError, Uint96BinOpError, Uint64BinOpError, Uint256DowncastError]; - -// Register the types we've defined. -for (const type of types) { - RevertError.registerType(type); -} diff --git a/packages/utils/src/revert_errors/zero-ex/common_revert_errors.ts b/packages/utils/src/revert_errors/zero-ex/common_revert_errors.ts deleted file mode 100644 index 67df68fff0..0000000000 --- a/packages/utils/src/revert_errors/zero-ex/common_revert_errors.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { RevertError } from '../../revert_error'; -import { Numberish } from '../../types'; - -// tslint:disable:max-classes-per-file -export class OnlyCallableBySelfError extends RevertError { - constructor(sender?: string) { - super('OnlyCallableBySelfError', 'OnlyCallableBySelfError(address sender)', { - sender, - }); - } -} - -export class IllegalReentrancyError extends RevertError { - constructor(selector?: string, reentrancyFlags?: Numberish) { - super('IllegalReentrancyError', 'IllegalReentrancyError(bytes4 selector, uint256 reentrancyFlags)', { - selector, - reentrancyFlags, - }); - } -} - -const types = [OnlyCallableBySelfError, IllegalReentrancyError]; - -// Register the types we've defined. -for (const type of types) { - RevertError.registerType(type); -} diff --git a/packages/utils/src/revert_errors/zero-ex/liquidity_provider_revert_errors.ts b/packages/utils/src/revert_errors/zero-ex/liquidity_provider_revert_errors.ts deleted file mode 100644 index 5adafe0127..0000000000 --- a/packages/utils/src/revert_errors/zero-ex/liquidity_provider_revert_errors.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { RevertError } from '../../revert_error'; -import { Numberish } from '../../types'; - -// tslint:disable:max-classes-per-file -export class LiquidityProviderIncompleteSellError extends RevertError { - constructor( - providerAddress?: string, - makerToken?: string, - takerToken?: string, - sellAmount?: Numberish, - boughtAmount?: Numberish, - minBuyAmount?: Numberish, - ) { - super( - 'LiquidityProviderIncompleteSellError', - 'LiquidityProviderIncompleteSellError(address providerAddress, address makerToken, address takerToken, uint256 sellAmount, uint256 boughtAmount, uint256 minBuyAmount)', - { - providerAddress, - makerToken, - takerToken, - sellAmount, - boughtAmount, - minBuyAmount, - }, - ); - } -} - -export class NoLiquidityProviderForMarketError extends RevertError { - constructor(xAsset?: string, yAsset?: string) { - super( - 'NoLiquidityProviderForMarketError', - 'NoLiquidityProviderForMarketError(address xAsset, address yAsset)', - { - xAsset, - yAsset, - }, - ); - } -} - -const types = [LiquidityProviderIncompleteSellError, NoLiquidityProviderForMarketError]; - -// Register the types we've defined. -for (const type of types) { - RevertError.registerType(type); -} diff --git a/packages/utils/src/revert_errors/zero-ex/meta_transaction_revert_errors.ts b/packages/utils/src/revert_errors/zero-ex/meta_transaction_revert_errors.ts deleted file mode 100644 index 86ad905cda..0000000000 --- a/packages/utils/src/revert_errors/zero-ex/meta_transaction_revert_errors.ts +++ /dev/null @@ -1,144 +0,0 @@ -import { RevertError } from '../../revert_error'; -import { Numberish } from '../../types'; - -// tslint:disable:max-classes-per-file -export class InvalidMetaTransactionsArrayLengthsError extends RevertError { - constructor(mtxCount?: Numberish, signatureCount?: Numberish) { - super( - 'InvalidMetaTransactionsArrayLengthsError', - 'InvalidMetaTransactionsArrayLengthsError(uint256 mtxCount, uint256 signatureCount)', - { - mtxCount, - signatureCount, - }, - ); - } -} - -export class MetaTransactionAlreadyExecutedError extends RevertError { - constructor(mtxHash?: string, executedBlockNumber?: Numberish) { - super( - 'MetaTransactionAlreadyExecutedError', - 'MetaTransactionAlreadyExecutedError(bytes32 mtxHash, uint256 executedBlockNumber)', - { - mtxHash, - executedBlockNumber, - }, - ); - } -} - -export class MetaTransactionUnsupportedFunctionError extends RevertError { - constructor(mtxHash?: string, selector?: string) { - super( - 'MetaTransactionUnsupportedFunctionError', - 'MetaTransactionUnsupportedFunctionError(bytes32 mtxHash, bytes4 selector)', - { - mtxHash, - selector, - }, - ); - } -} - -export class MetaTransactionWrongSenderError extends RevertError { - constructor(mtxHash?: string, sender?: string, expectedSender?: string) { - super( - 'MetaTransactionWrongSenderError', - 'MetaTransactionWrongSenderError(bytes32 mtxHash, address sender, address expectedSender)', - { - mtxHash, - sender, - expectedSender, - }, - ); - } -} - -export class MetaTransactionExpiredError extends RevertError { - constructor(mtxHash?: string, time?: Numberish, expirationTime?: Numberish) { - super( - 'MetaTransactionExpiredError', - 'MetaTransactionExpiredError(bytes32 mtxHash, uint256 time, uint256 expirationTime)', - { - mtxHash, - time, - expirationTime, - }, - ); - } -} - -export class MetaTransactionGasPriceError extends RevertError { - constructor(mtxHash?: string, gasPrice?: Numberish, minGasPrice?: Numberish, maxGasPrice?: Numberish) { - super( - 'MetaTransactionGasPriceError', - 'MetaTransactionGasPriceError(bytes32 mtxHash, uint256 gasPrice, uint256 minGasPrice, uint256 maxGasPrice)', - { - mtxHash, - gasPrice, - minGasPrice, - maxGasPrice, - }, - ); - } -} - -export class MetaTransactionInsufficientEthError extends RevertError { - constructor(mtxHash?: string, ethBalance?: Numberish, ethRequired?: Numberish) { - super( - 'MetaTransactionInsufficientEthError', - 'MetaTransactionInsufficientEthError(bytes32 mtxHash, uint256 ethBalance, uint256 ethRequired)', - { - mtxHash, - ethBalance, - ethRequired, - }, - ); - } -} - -export class MetaTransactionInvalidSignatureError extends RevertError { - constructor(mtxHash?: string, signature?: string, errData?: string) { - super( - 'MetaTransactionInvalidSignatureError', - 'MetaTransactionInvalidSignatureError(bytes32 mtxHash, bytes signature, bytes errData)', - { - mtxHash, - signature, - errData, - }, - ); - } -} - -export class MetaTransactionCallFailedError extends RevertError { - constructor(mtxHash?: string, callData?: string, returnData?: string) { - super( - 'MetaTransactionCallFailedError', - 'MetaTransactionCallFailedError(bytes32 mtxHash, bytes callData, bytes returnData)', - { - mtxHash, - callData, - returnData, - }, - ); - } -} - -const types = [ - InvalidMetaTransactionsArrayLengthsError, - MetaTransactionAlreadyExecutedError, - MetaTransactionUnsupportedFunctionError, - MetaTransactionWrongSenderError, - MetaTransactionExpiredError, - MetaTransactionGasPriceError, - MetaTransactionInsufficientEthError, - MetaTransactionInvalidSignatureError, - MetaTransactionCallFailedError, -]; - -// Register the types we've defined. -for (const type of types) { - RevertError.registerType(type); -} diff --git a/packages/utils/src/revert_errors/zero-ex/ownable_revert_errors.ts b/packages/utils/src/revert_errors/zero-ex/ownable_revert_errors.ts deleted file mode 100644 index 0810093c66..0000000000 --- a/packages/utils/src/revert_errors/zero-ex/ownable_revert_errors.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { RevertError } from '../../revert_error'; - -// tslint:disable:max-classes-per-file - -export class MigrateCallFailedError extends RevertError { - constructor(target?: string, resultData?: string) { - super('MigrateCallFailedError', 'MigrateCallFailedError(address target, bytes resultData)', { - target, - resultData, - }); - } -} - -export class OnlyOwnerError extends RevertError { - constructor(sender?: string, owner?: string) { - super('OnlyOwnerError', 'OnlyOwnerError(address sender, bytes owner)', { - sender, - owner, - }); - } -} - -// This is identical to the one in utils. -// export class TransferOwnerToZeroError extends RevertError { -// constructor() { -// super('TransferOwnerToZeroError', 'TransferOwnerToZeroError()', {}); -// } -// } - -const types = [MigrateCallFailedError, OnlyOwnerError]; - -// Register the types we've defined. -for (const type of types) { - RevertError.registerType(type); -} diff --git a/packages/utils/src/revert_errors/zero-ex/proxy_revert_errors.ts b/packages/utils/src/revert_errors/zero-ex/proxy_revert_errors.ts deleted file mode 100644 index fc5ff2c5a1..0000000000 --- a/packages/utils/src/revert_errors/zero-ex/proxy_revert_errors.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { RevertError } from '../../revert_error'; - -// tslint:disable:max-classes-per-file -export class NotImplementedError extends RevertError { - constructor(selector?: string) { - super('NotImplementedError', 'NotImplementedError(bytes4 selector)', { - selector, - }); - } -} - -export class InvalidBootstrapCallerError extends RevertError { - constructor(caller?: string, expectedCaller?: string) { - super('InvalidBootstrapCallerError', 'InvalidBootstrapCallerError(address caller, address expectedCaller)', { - caller, - expectedCaller, - }); - } -} - -export class InvalidDieCallerError extends RevertError { - constructor(caller?: string, expectedCaller?: string) { - super('InvalidDieCallerError', 'InvalidDieCallerError(address caller, address expectedCaller)', { - caller, - expectedCaller, - }); - } -} - -export class BootstrapCallFailedError extends RevertError { - constructor(target?: string, resultData?: string) { - super('BootstrapCallFailedError', 'BootstrapCallFailedError(address target, bytes resultData)', { - target, - resultData, - }); - } -} - -const types = [BootstrapCallFailedError, InvalidBootstrapCallerError, InvalidDieCallerError, NotImplementedError]; - -// Register the types we've defined. -for (const type of types) { - RevertError.registerType(type); -} diff --git a/packages/utils/src/revert_errors/zero-ex/signature_validator_revert_errors.ts b/packages/utils/src/revert_errors/zero-ex/signature_validator_revert_errors.ts deleted file mode 100644 index 69d2283f75..0000000000 --- a/packages/utils/src/revert_errors/zero-ex/signature_validator_revert_errors.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { RevertError } from '../../revert_error'; - -// tslint:disable:max-classes-per-file - -export enum SignatureValidationErrorCodes { - AlwaysInvalid = 0, - InvalidLength = 1, - Unsupported = 2, - Illegal = 3, - WrongSigner = 4, -} - -export class SignatureValidationError extends RevertError { - constructor(code?: SignatureValidationErrorCodes, hash?: string, signerAddress?: string, signature?: string) { - super( - 'SignatureValidationError', - 'SignatureValidationError(uint8 code, bytes32 hash, address signerAddress, bytes signature)', - { - code, - hash, - signerAddress, - signature, - }, - ); - } -} - -const types = [SignatureValidationError]; - -// Register the types we've defined. -for (const type of types) { - RevertError.registerType(type); -} diff --git a/packages/utils/src/revert_errors/zero-ex/simple_function_registry_revert_errors.ts b/packages/utils/src/revert_errors/zero-ex/simple_function_registry_revert_errors.ts deleted file mode 100644 index 1aa85df664..0000000000 --- a/packages/utils/src/revert_errors/zero-ex/simple_function_registry_revert_errors.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { RevertError } from '../../revert_error'; - -// tslint:disable:max-classes-per-file -export class NotInRollbackHistoryError extends RevertError { - constructor(selector?: string, targetImpl?: string) { - super('NotInRollbackHistoryError', 'NotInRollbackHistoryError(bytes4 selector, address targetImpl)', { - selector, - targetImpl, - }); - } -} - -const types = [NotInRollbackHistoryError]; - -// Register the types we've defined. -for (const type of types) { - RevertError.registerType(type); -} diff --git a/packages/utils/src/revert_errors/zero-ex/spender_revert_errors.ts b/packages/utils/src/revert_errors/zero-ex/spender_revert_errors.ts deleted file mode 100644 index 67e230b4de..0000000000 --- a/packages/utils/src/revert_errors/zero-ex/spender_revert_errors.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { RevertError } from '../../revert_error'; -import { Numberish } from '../../types'; - -// tslint:disable:max-classes-per-file -export class SpenderERC20TransferFromFailedError extends RevertError { - constructor(token?: string, owner?: string, to?: string, amount?: Numberish, errorData?: string) { - super( - 'SpenderERC20TransferFromFailedError', - 'SpenderERC20TransferFromFailedError(address token, address owner, address to, uint256 amount, bytes errorData)', - { - token, - owner, - to, - amount, - errorData, - }, - ); - } -} - -const types = [SpenderERC20TransferFromFailedError]; - -// Register the types we've defined. -for (const type of types) { - RevertError.registerType(type); -} diff --git a/packages/utils/src/revert_errors/zero-ex/transform_erc20_revert_errors.ts b/packages/utils/src/revert_errors/zero-ex/transform_erc20_revert_errors.ts deleted file mode 100644 index 780e644c47..0000000000 --- a/packages/utils/src/revert_errors/zero-ex/transform_erc20_revert_errors.ts +++ /dev/null @@ -1,199 +0,0 @@ -import { RevertError } from '../../revert_error'; -import { Numberish } from '../../types'; - -// tslint:disable:max-classes-per-file -export class InsufficientEthAttachedError extends RevertError { - constructor(ethAttached?: Numberish, ethNeeded?: Numberish) { - super('InsufficientEthAttachedError', 'InsufficientEthAttachedError(uint256 ethAttached, uint256 ethNeeded)', { - ethAttached, - ethNeeded, - }); - } -} - -export class IncompleteTransformERC20Error extends RevertError { - constructor(outputToken?: string, outputTokenAmount?: Numberish, minOutputTokenAmount?: Numberish) { - super( - 'IncompleteTransformERC20Error', - 'IncompleteTransformERC20Error(address outputToken, uint256 outputTokenAmount, uint256 minOutputTokenAmount)', - { - outputToken, - outputTokenAmount, - minOutputTokenAmount, - }, - ); - } -} - -export class NegativeTransformERC20OutputError extends RevertError { - constructor(outputToken?: string, outputTokenLostAmount?: Numberish) { - super( - 'NegativeTransformERC20OutputError', - 'NegativeTransformERC20OutputError(address outputToken, uint256 outputTokenLostAmount)', - { - outputToken, - outputTokenLostAmount, - }, - ); - } -} - -export class TransformerFailedError extends RevertError { - constructor(transformer?: string, transformerData?: string, resultData?: string) { - super( - 'TransformerFailedError', - 'TransformerFailedError(address transformer, bytes transformerData, bytes resultData)', - { - transformer, - transformerData, - resultData, - }, - ); - } -} - -export class OnlyCallableByDeployerError extends RevertError { - constructor(caller?: string, deployer?: string) { - super('OnlyCallableByDeployerError', 'OnlyCallableByDeployerError(address caller, address deployer)', { - caller, - deployer, - }); - } -} - -export class InvalidExecutionContextError extends RevertError { - constructor(actualContext?: string, expectedContext?: string) { - super( - 'InvalidExecutionContextError', - 'InvalidExecutionContextError(address actualContext, address expectedContext)', - { - actualContext, - expectedContext, - }, - ); - } -} - -export enum InvalidTransformDataErrorCode { - InvalidTokens, - InvalidArrayLength, -} - -export class InvalidTransformDataError extends RevertError { - constructor(errorCode?: InvalidTransformDataErrorCode, transformData?: string) { - super('InvalidTransformDataError', 'InvalidTransformDataError(uint8 errorCode, bytes transformData)', { - errorCode, - transformData, - }); - } -} - -export class IncompleteFillSellQuoteError extends RevertError { - constructor(sellToken?: string, soldAmount?: Numberish, sellAmount?: Numberish) { - super( - 'IncompleteFillSellQuoteError', - 'IncompleteFillSellQuoteError(address sellToken, uint256 soldAmount, uint256 sellAmount)', - { - sellToken, - soldAmount, - sellAmount, - }, - ); - } -} - -export class IncompleteFillBuyQuoteError extends RevertError { - constructor(buyToken?: string, boughtAmount?: Numberish, buyAmount?: Numberish) { - super( - 'IncompleteFillBuyQuoteError', - 'IncompleteFillBuyQuoteError(address buyToken, uint256 boughtAmount, uint256 buyAmount)', - { - buyToken, - boughtAmount, - buyAmount, - }, - ); - } -} - -export class InsufficientTakerTokenError extends RevertError { - constructor(tokenBalance?: Numberish, tokensNeeded?: Numberish) { - super( - 'InsufficientTakerTokenError', - 'InsufficientTakerTokenError(uint256 tokenBalance, uint256 tokensNeeded)', - { - tokenBalance, - tokensNeeded, - }, - ); - } -} - -export class InsufficientProtocolFeeError extends RevertError { - constructor(ethBalance?: Numberish, ethNeeded?: Numberish) { - super('InsufficientProtocolFeeError', 'InsufficientProtocolFeeError(uint256 ethBalance, uint256 ethNeeded)', { - ethBalance, - ethNeeded, - }); - } -} - -export class InvalidERC20AssetDataError extends RevertError { - constructor(assetData?: string) { - super('InvalidERC20AssetDataError', 'InvalidERC20AssetDataError(bytes assetData)', { - assetData, - }); - } -} - -export class WrongNumberOfTokensReceivedError extends RevertError { - constructor(actual?: Numberish, expected?: Numberish) { - super( - 'WrongNumberOfTokensReceivedError', - 'WrongNumberOfTokensReceivedError(uint256 actual, uint256 expected)', - { - actual, - expected, - }, - ); - } -} - -export class InvalidTokenReceivedError extends RevertError { - constructor(token?: string) { - super('InvalidTokenReceivedError', 'InvalidTokenReceivedError(address token)', { - token, - }); - } -} - -export class InvalidTakerFeeTokenError extends RevertError { - constructor(token?: string) { - super('InvalidTakerFeeTokenError', 'InvalidTakerFeeTokenError(address token)', { - token, - }); - } -} - -const types = [ - InsufficientEthAttachedError, - IncompleteTransformERC20Error, - NegativeTransformERC20OutputError, - TransformerFailedError, - IncompleteFillSellQuoteError, - IncompleteFillBuyQuoteError, - InsufficientTakerTokenError, - InsufficientProtocolFeeError, - InvalidERC20AssetDataError, - WrongNumberOfTokensReceivedError, - InvalidTokenReceivedError, - InvalidTransformDataError, - InvalidTakerFeeTokenError, - OnlyCallableByDeployerError, - InvalidExecutionContextError, -]; - -// Register the types we've defined. -for (const type of types) { - RevertError.registerType(type); -} diff --git a/packages/utils/src/revert_errors/zero-ex/wallet_revert_errors.ts b/packages/utils/src/revert_errors/zero-ex/wallet_revert_errors.ts deleted file mode 100644 index a3a47582ba..0000000000 --- a/packages/utils/src/revert_errors/zero-ex/wallet_revert_errors.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { RevertError } from '../../revert_error'; -import { Numberish } from '../../types'; - -// tslint:disable:max-classes-per-file -export class WalletExecuteCallFailedError extends RevertError { - constructor(wallet?: string, callTarget?: string, callData?: string, callValue?: Numberish, errorData?: string) { - super( - 'WalletExecuteCallFailedError', - 'WalletExecuteCallFailedError(address wallet, address callTarget, bytes callData, uint256 callValue, bytes errorData)', - { - wallet, - callTarget, - callData, - callValue, - errorData, - }, - ); - } -} - -export class WalletExecuteDelegateCallFailedError extends RevertError { - constructor(wallet?: string, callTarget?: string, callData?: string, errorData?: string) { - super( - 'WalletExecuteDelegateCallFailedError', - 'WalletExecuteDelegateCallFailedError(address wallet, address callTarget, bytes callData, bytes errorData)', - { - wallet, - callTarget, - callData, - errorData, - }, - ); - } -} - -const types = [WalletExecuteCallFailedError, WalletExecuteDelegateCallFailedError]; - -// Register the types we've defined. -for (const type of types) { - RevertError.registerType(type); -} diff --git a/packages/utils/src/sign_typed_data_utils.ts b/packages/utils/src/sign_typed_data_utils.ts deleted file mode 100644 index e2fe2ca5af..0000000000 --- a/packages/utils/src/sign_typed_data_utils.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { EIP712Object, EIP712ObjectValue, EIP712TypedData, EIP712Types } from '@0x/types'; -import * as ethUtil from 'ethereumjs-util'; -import * as ethers from 'ethers'; -import * as _ from 'lodash'; - -import { BigNumber } from './configured_bignumber'; - -export const signTypedDataUtils = { - /** - * Generates the EIP712 Typed Data hash for signing - * @param typedData An object that conforms to the EIP712TypedData interface - * @return A Buffer containing the hash of the typed data. - */ - generateTypedDataHash(typedData: EIP712TypedData): Buffer { - return ethUtil.sha3( - Buffer.concat([ - Buffer.from('1901', 'hex'), - signTypedDataUtils._structHash('EIP712Domain', typedData.domain, typedData.types), - signTypedDataUtils._structHash(typedData.primaryType, typedData.message, typedData.types), - ]), - ); - }, - /** - * Generates the EIP712 Typed Data hash for a typed data object without using the domain field. This - * makes hashing easier for non-EIP712 data. - * @param typedData An object that conforms to the EIP712TypedData interface - * @return A Buffer containing the hash of the typed data. - */ - generateTypedDataHashWithoutDomain(typedData: EIP712TypedData): Buffer { - return signTypedDataUtils._structHash(typedData.primaryType, typedData.message, typedData.types); - }, - /** - * Generates the hash of a EIP712 Domain with the default schema - * @param domain An EIP712 domain with the default schema containing a name, version, chain id, - * and verifying address. - * @return A buffer that contains the hash of the domain. - */ - generateDomainHash(domain: EIP712Object): Buffer { - return signTypedDataUtils._structHash( - 'EIP712Domain', - domain, - // HACK(jalextowle): When we consolidate our testing packages into test-utils, we can use a constant - // to eliminate code duplication. At the moment, there isn't a good way to do that because of cyclic-dependencies. - { - EIP712Domain: [ - { name: 'name', type: 'string' }, - { name: 'version', type: 'string' }, - { name: 'chainId', type: 'uint256' }, - { name: 'verifyingContract', type: 'address' }, - ], - }, - ); - }, - _findDependencies(primaryType: string, types: EIP712Types, found: string[] = []): string[] { - if (found.includes(primaryType) || types[primaryType] === undefined) { - return found; - } - found.push(primaryType); - for (const field of types[primaryType]) { - for (const dep of signTypedDataUtils._findDependencies(field.type, types, found)) { - if (!found.includes(dep)) { - found.push(dep); - } - } - } - return found; - }, - _encodeType(primaryType: string, types: EIP712Types): string { - let deps = signTypedDataUtils._findDependencies(primaryType, types); - deps = deps.filter(d => d !== primaryType); - deps = [primaryType].concat(deps.sort()); - let result = ''; - for (const dep of deps) { - result += `${dep}(${types[dep].map(({ name, type }) => `${type} ${name}`).join(',')})`; - } - return result; - }, - _encodeData(primaryType: string, data: EIP712Object, types: EIP712Types): string { - const encodedTypes = ['bytes32']; - const encodedValues: Array = [signTypedDataUtils._typeHash(primaryType, types)]; - for (const field of types[primaryType]) { - const value = data[field.name]; - if (field.type === 'string' || field.type === 'bytes') { - const hashValue = ethUtil.sha3(value as string); - encodedTypes.push('bytes32'); - encodedValues.push(hashValue); - } else if (types[field.type] !== undefined) { - encodedTypes.push('bytes32'); - const hashValue = ethUtil.sha3( - // tslint:disable-next-line:no-unnecessary-type-assertion - signTypedDataUtils._encodeData(field.type, value as EIP712Object, types), - ); - encodedValues.push(hashValue); - } else if (field.type.lastIndexOf(']') === field.type.length - 1) { - throw new Error('Arrays currently unimplemented in encodeData'); - } else { - encodedTypes.push(field.type); - const normalizedValue = signTypedDataUtils._normalizeValue(field.type, value); - encodedValues.push(normalizedValue); - } - } - return ethers.utils.defaultAbiCoder.encode(encodedTypes, encodedValues); - }, - _normalizeValue(type: string, value: any): EIP712ObjectValue { - const STRING_BASE = 10; - if (type === 'uint256') { - if (BigNumber.isBigNumber(value)) { - return value.toString(STRING_BASE); - } - return new BigNumber(value).toString(STRING_BASE); - } - return value; - }, - _typeHash(primaryType: string, types: EIP712Types): Buffer { - return ethUtil.sha3(signTypedDataUtils._encodeType(primaryType, types)); - }, - _structHash(primaryType: string, data: EIP712Object, types: EIP712Types): Buffer { - return ethUtil.sha3(signTypedDataUtils._encodeData(primaryType, data, types)); - }, -}; diff --git a/packages/utils/src/token_utils.ts b/packages/utils/src/token_utils.ts deleted file mode 100644 index d03a99c049..0000000000 --- a/packages/utils/src/token_utils.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { BigNumber } from './configured_bignumber'; -import { Numberish } from './types'; - -// tslint:disable:custom-no-magic-numbers - -/** - * Convert a token unit amount to weis. E.g., 10.1 ETH -> 10100000000000000000. - */ -export function fromTokenUnitAmount(units: Numberish, decimals: number = 18): BigNumber { - return new BigNumber(units).times(new BigNumber(10).pow(decimals)).integerValue(); -} - -/** - * Convert a wei amount to token units. E.g., 10100000000000000000 -> 10.1 ETH. - */ -export function toTokenUnitAmount(weis: Numberish, decimals: number = 18): BigNumber { - return new BigNumber(weis).div(new BigNumber(10).pow(decimals)); -} diff --git a/packages/utils/src/types.ts b/packages/utils/src/types.ts deleted file mode 100644 index 2d7fc749cd..0000000000 --- a/packages/utils/src/types.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { AbiEncoder } from '.'; -import { BigNumber } from './index'; - -export interface FunctionInfo { - functionSignature: string; - contractName?: string; - contractAddress?: string; - chainId?: number; - abiEncoder?: AbiEncoder.Method; -} - -export interface SelectorToFunctionInfo { - [index: string]: FunctionInfo[]; -} - -export interface DecodedCalldata { - functionName: string; - functionSignature: string; - functionArguments: any; -} - -export type Numberish = BigNumber | string | number; diff --git a/packages/utils/test/abi_decoder_test.ts b/packages/utils/test/abi_decoder_test.ts deleted file mode 100644 index 81fed1060e..0000000000 --- a/packages/utils/test/abi_decoder_test.ts +++ /dev/null @@ -1,50 +0,0 @@ -import * as chai from 'chai'; -import { MethodAbi } from 'ethereum-types'; -import 'mocha'; - -import { AbiDecoder, AbiEncoder } from '../src'; - -import { chaiSetup } from './utils/chai_setup'; - -chaiSetup.configure(); -const expect = chai.expect; - -describe('AbiDecoder', () => { - it('should successfully add a new ABI and decode calldata for it', async () => { - // Add new ABI - const abi: MethodAbi = { - name: 'foobar', - type: 'function', - inputs: [ - { - name: 'testAddress', - type: 'address', - }, - ], - outputs: [ - { - name: 'butter', - type: 'string', - }, - ], - constant: false, - payable: false, - stateMutability: 'pure', - }; - const contractName = 'newContract'; - const testAddress = '0x0001020304050607080900010203040506070809'; - const abiDecoder = new AbiDecoder([]); - abiDecoder.addABI([abi], contractName); - // Create some tx data - const foobarEncoder = new AbiEncoder.Method(abi); - const foobarSignature = foobarEncoder.getSignature(); - const foobarTxData = foobarEncoder.encode([testAddress]); - // Decode tx data using contract name - const decodedTxData = abiDecoder.decodeCalldataOrThrow(foobarTxData, contractName); - const expectedFunctionName = abi.name; - const expectedFunctionArguments = { testAddress }; - expect(decodedTxData.functionName).to.be.equal(expectedFunctionName); - expect(decodedTxData.functionSignature).to.be.equal(foobarSignature); - expect(decodedTxData.functionArguments).to.be.deep.equal(expectedFunctionArguments); - }); -}); diff --git a/packages/utils/test/abi_encoder/abi_samples/method_abis.ts b/packages/utils/test/abi_encoder/abi_samples/method_abis.ts deleted file mode 100644 index fc552c1275..0000000000 --- a/packages/utils/test/abi_encoder/abi_samples/method_abis.ts +++ /dev/null @@ -1,780 +0,0 @@ -/* tslint:disable max-file-line-count */ -import { MethodAbi } from 'ethereum-types'; - -export const simpleAbi: MethodAbi = { - constant: false, - inputs: [ - { - name: 'greg', - type: 'uint256', - }, - { - name: 'gregStr', - type: 'string', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const stringAbi: MethodAbi = { - constant: false, - inputs: [ - { - name: 'greg', - type: 'string[]', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const GAbi: MethodAbi = { - constant: false, - inputs: [ - { - components: [ - { - name: 'a', - type: 'uint256', - }, - { - name: 'b', - type: 'string', - }, - { - name: 'e', - type: 'bytes', - }, - { - name: 'f', - type: 'address', - }, - ], - - name: 'f', - type: 'tuple', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const typesWithDefaultWidthsAbi: MethodAbi = { - constant: false, - inputs: [ - { - name: 'someUint', - type: 'uint', - }, - { - name: 'someInt', - type: 'int', - }, - { - name: 'someByte', - type: 'byte', - }, - { - name: 'someUint', - type: 'uint[]', - }, - { - name: 'someInt', - type: 'int[]', - }, - { - name: 'someByte', - type: 'byte[]', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const multiDimensionalArraysStaticTypeAbi: MethodAbi = { - constant: false, - inputs: [ - { - name: 'a', - type: 'uint8[][][]', - }, - { - name: 'b', - type: 'uint8[][][2]', - }, - { - name: 'c', - type: 'uint8[][2][]', - }, - { - name: 'd', - type: 'uint8[2][][]', - }, - { - name: 'e', - type: 'uint8[][2][2]', - }, - { - name: 'f', - type: 'uint8[2][2][]', - }, - { - name: 'g', - type: 'uint8[2][][2]', - }, - { - name: 'h', - type: 'uint8[2][2][2]', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const multiDimensionalArraysDynamicTypeAbi: MethodAbi = { - constant: false, - inputs: [ - { - name: 'a', - type: 'string[][][]', - }, - { - name: 'b', - type: 'string[][][2]', - }, - { - name: 'c', - type: 'string[][2][]', - }, - { - name: 'h', - type: 'string[2][2][2]', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const dynamicTupleAbi: MethodAbi = { - constant: false, - inputs: [ - { - components: [ - { - name: 'someUint', - type: 'uint256', - }, - { - name: 'someStr', - type: 'string', - }, - ], - name: 'order', - type: 'tuple', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const arrayOfStaticTuplesWithDefinedLengthAbi: MethodAbi = { - constant: false, - inputs: [ - { - components: [ - { - name: 'someUint', - type: 'uint256', - }, - { - name: 'someUint2', - type: 'uint256', - }, - ], - name: 'order', - type: 'tuple[8]', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const arrayOfStaticTuplesWithDynamicLengthAbi: MethodAbi = { - constant: false, - inputs: [ - { - components: [ - { - name: 'someUint', - type: 'uint256', - }, - { - name: 'someUint2', - type: 'uint256', - }, - ], - name: 'order', - type: 'tuple[]', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const arrayOfDynamicTuplesWithDefinedLengthAbi: MethodAbi = { - constant: false, - inputs: [ - { - components: [ - { - name: 'someUint', - type: 'uint256', - }, - { - name: 'someString', - type: 'string', - }, - ], - name: 'order', - type: 'tuple[8]', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const arrayOfDynamicTuplesWithUndefinedLengthAbi: MethodAbi = { - constant: false, - inputs: [ - { - components: [ - { - name: 'someUint', - type: 'uint256', - }, - { - name: 'someString', - type: 'string', - }, - ], - name: 'order', - type: 'tuple[]', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const arrayOfDynamicTuplesAbi: MethodAbi = { - constant: false, - inputs: [ - { - components: [ - { - name: 'someUint', - type: 'uint256', - }, - { - name: 'someString', - type: 'string', - }, - ], - name: 'order', - type: 'tuple[]', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const multidimensionalArrayOfDynamicTuplesAbi: MethodAbi = { - constant: false, - inputs: [ - { - components: [ - { - name: 'someUint', - type: 'uint256', - }, - { - name: 'someString', - type: 'string', - }, - ], - name: 'order', - type: 'tuple[][2][]', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const staticTupleAbi: MethodAbi = { - constant: false, - inputs: [ - { - components: [ - { - name: 'someUint1', - type: 'uint256', - }, - { - name: 'someUint2', - type: 'uint256', - }, - { - name: 'someUint3', - type: 'uint256', - }, - { - name: 'someBool', - type: 'bool', - }, - ], - name: 'order', - type: 'tuple', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const staticArrayAbi: MethodAbi = { - constant: false, - inputs: [ - { - name: 'someStaticArray', - type: 'uint8[3]', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const staticArrayDynamicMembersAbi: MethodAbi = { - constant: false, - inputs: [ - { - name: 'someStaticArray', - type: 'string[3]', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const dynamicArrayDynamicMembersAbi: MethodAbi = { - constant: false, - inputs: [ - { - name: 'someStaticArray', - type: 'string[]', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const dynamicArrayStaticMembersAbi: MethodAbi = { - constant: false, - inputs: [ - { - name: 'someStaticArray', - type: 'uint8[]', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const largeFlatAbi: MethodAbi = { - constant: false, - inputs: [ - { - name: 'someUInt256', - type: 'uint256', - }, - { - name: 'someInt256', - type: 'int256', - }, - { - name: 'someInt32', - type: 'int32', - }, - { - name: 'someByte', - type: 'byte', - }, - { - name: 'someBytes32', - type: 'bytes32', - }, - { - name: 'someBytes', - type: 'bytes', - }, - { - name: 'someString', - type: 'string', - }, - { - name: 'someAddress', - type: 'address', - }, - { - name: 'someBool', - type: 'bool', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const largeNestedAbi: MethodAbi = { - constant: false, - inputs: [ - { - name: 'someStaticArray', - type: 'uint8[3]', - }, - { - name: 'someStaticArrayWithDynamicMembers', - type: 'string[2]', - }, - { - name: 'someDynamicArrayWithDynamicMembers', - type: 'bytes[]', - }, - { - name: 'some2DArray', - type: 'string[][]', - }, - { - name: 'someTuple', - type: 'tuple', - components: [ - { - name: 'someUint32', - type: 'uint32', - }, - { - name: 'someStr', - type: 'string', - }, - ], - }, - { - name: 'someTupleWithDynamicTypes', - type: 'tuple', - components: [ - { - name: 'someUint', - type: 'uint256', - }, - { - name: 'someStr', - type: 'string', - }, - /*{ - name: 'someStrArray', - type: 'string[]', - },*/ - { - name: 'someBytes', - type: 'bytes', - }, - { - name: 'someAddress', - type: 'address', - }, - ], - }, - { - name: 'someArrayOfTuplesWithDynamicTypes', - type: 'tuple[]', - components: [ - { - name: 'someUint', - type: 'uint256', - }, - { - name: 'someStr', - type: 'string', - }, - /*{ - name: 'someStrArray', - type: 'string[]', - },*/ - { - name: 'someBytes', - type: 'bytes', - }, - { - name: 'someAddress', - type: 'address', - }, - ], - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const nestedTuples: MethodAbi = { - constant: false, - inputs: [ - { - name: 'firstTuple', - type: 'tuple[1]', - components: [ - { - name: 'someUint32', - type: 'uint32', - }, - { - name: 'nestedTuple', - type: 'tuple', - components: [ - { - name: 'someUint', - type: 'uint256', - }, - { - name: 'someAddress', - type: 'address', - }, - ], - }, - ], - }, - { - name: 'secondTuple', - type: 'tuple[]', - components: [ - { - name: 'someUint', - type: 'uint256', - }, - { - name: 'someStr', - type: 'string', - }, - { - name: 'nestedTuple', - type: 'tuple', - components: [ - { - name: 'someUint32', - type: 'uint32', - }, - { - name: 'secondNestedTuple', - type: 'tuple', - components: [ - { - name: 'someUint', - type: 'uint256', - }, - { - name: 'someStr', - type: 'string', - }, - { - name: 'someBytes', - type: 'bytes', - }, - { - name: 'someAddress', - type: 'address', - }, - ], - }, - ], - }, - { - name: 'someBytes', - type: 'bytes', - }, - { - name: 'someAddress', - type: 'address', - }, - ], - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const simpleAbi2: MethodAbi = { - constant: false, - inputs: [ - { - name: 'someByte', - type: 'byte', - }, - { - name: 'someBytes32', - type: 'bytes32', - }, - { - name: 'someBytes', - type: 'bytes', - }, - { - name: 'someString', - type: 'string', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const fillOrderAbi: MethodAbi = { - constant: false, - inputs: [ - { - components: [ - { - name: 'makerAddress', - type: 'address', - }, - { - name: 'takerAddress', - type: 'address', - }, - { - name: 'feeRecipientAddress', - type: 'address', - }, - { - name: 'senderAddress', - type: 'address', - }, - { - name: 'makerAssetAmount', - type: 'uint256', - }, - { - name: 'takerAssetAmount', - type: 'uint256', - }, - { - name: 'makerFee', - type: 'uint256', - }, - { - name: 'takerFee', - type: 'uint256', - }, - { - name: 'expirationTimeSeconds', - type: 'uint256', - }, - { - name: 'salt', - type: 'uint256', - }, - { - name: 'makerAssetData', - type: 'bytes', - }, - { - name: 'takerAssetData', - type: 'bytes', - }, - ], - name: 'order', - type: 'tuple', - }, - { - name: 'takerAssetFillAmount', - type: 'uint256', - }, - { - name: 'salt', - type: 'uint256', - }, - { - name: 'orderSignature', - type: 'bytes', - }, - { - name: 'takerSignature', - type: 'bytes', - }, - ], - name: 'fillOrder', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; diff --git a/packages/utils/test/abi_encoder/abi_samples/optimizer_abis.ts b/packages/utils/test/abi_encoder/abi_samples/optimizer_abis.ts deleted file mode 100644 index 7cfd7a1183..0000000000 --- a/packages/utils/test/abi_encoder/abi_samples/optimizer_abis.ts +++ /dev/null @@ -1,340 +0,0 @@ -/* tslint:disable max-file-line-count */ -import { MethodAbi } from 'ethereum-types'; - -export const duplicateDynamicArraysWithStaticElements: MethodAbi = { - constant: false, - inputs: [ - { - name: 'array1', - type: 'uint[]', - }, - { - name: 'array2', - type: 'uint[]', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const duplicateDynamicArraysWithDynamicElements: MethodAbi = { - constant: false, - inputs: [ - { - name: 'array1', - type: 'string[]', - }, - { - name: 'array2', - type: 'string[]', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const duplicateStaticArraysWithStaticElements: MethodAbi = { - constant: false, - inputs: [ - { - name: 'array1', - type: 'uint[2]', - }, - { - name: 'array2', - type: 'uint[2]', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const duplicateStaticArraysWithDynamicElements: MethodAbi = { - constant: false, - inputs: [ - { - name: 'array1', - type: 'string[2]', - }, - { - name: 'array2', - type: 'string[2]', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const duplicateArrayElements: MethodAbi = { - constant: false, - inputs: [ - { - name: 'array', - type: 'string[]', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const duplicateTupleFields: MethodAbi = { - constant: false, - inputs: [ - { - components: [ - { - name: 'field1', - type: 'string', - }, - { - name: 'field2', - type: 'string', - }, - ], - name: 'Tuple', - type: 'tuple', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const duplicateStrings: MethodAbi = { - constant: false, - inputs: [ - { - name: 'string1', - type: 'string', - }, - { - name: 'string2', - type: 'string', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const duplicateBytes: MethodAbi = { - constant: false, - inputs: [ - { - name: 'bytes1', - type: 'bytes', - }, - { - name: 'bytes2', - type: 'bytes', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const duplicateTuples: MethodAbi = { - constant: false, - inputs: [ - { - components: [ - { - name: 'field1', - type: 'string', - }, - { - name: 'field2', - type: 'uint', - }, - ], - name: 'Tuple', - type: 'tuple', - }, - { - components: [ - { - name: 'field1', - type: 'string', - }, - { - name: 'field2', - type: 'uint', - }, - ], - name: 'Tuple', - type: 'tuple', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const duplicateArraysNestedInTuples: MethodAbi = { - constant: false, - inputs: [ - { - components: [ - { - name: 'field', - type: 'uint[]', - }, - ], - name: 'Tuple1', - type: 'tuple', - }, - { - components: [ - { - name: 'field', - type: 'uint[]', - }, - { - name: 'extraField', - type: 'string', - }, - ], - name: 'Tuple2', - type: 'tuple', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const duplicateTuplesNestedInTuples: MethodAbi = { - constant: false, - inputs: [ - { - components: [ - { - components: [ - { - name: 'nestedField', - type: 'string', - }, - ], - name: 'field', - type: 'tuple', - }, - ], - name: 'Tuple1', - type: 'tuple', - }, - { - components: [ - { - components: [ - { - name: 'nestedField', - type: 'string', - }, - ], - name: 'field', - type: 'tuple', - }, - { - name: 'extraField', - type: 'string', - }, - ], - name: 'Tuple1', - type: 'tuple', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const duplicateTwoDimensionalArrays: MethodAbi = { - constant: false, - inputs: [ - { - name: 'array1', - type: 'string[][]', - }, - { - name: 'array2', - type: 'string[][]', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const arrayElementsDuplicatedAsSeparateParameter: MethodAbi = { - constant: false, - inputs: [ - { - name: 'stringArray', - type: 'string[]', - }, - { - name: 'string', - type: 'string', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const arrayElementsDuplicatedAsTupleFields: MethodAbi = { - constant: false, - inputs: [ - { - name: 'uint8Array', - type: 'uint8[]', - }, - { - components: [ - { - name: 'uint', - type: 'uint', - }, - ], - name: 'uintTuple', - type: 'tuple[]', - }, - ], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; diff --git a/packages/utils/test/abi_encoder/abi_samples/return_value_abis.ts b/packages/utils/test/abi_encoder/abi_samples/return_value_abis.ts deleted file mode 100644 index ad07b3d24d..0000000000 --- a/packages/utils/test/abi_encoder/abi_samples/return_value_abis.ts +++ /dev/null @@ -1,124 +0,0 @@ -/* tslint:disable max-file-line-count */ -import { MethodAbi } from 'ethereum-types'; - -export const noReturnValues: MethodAbi = { - constant: false, - inputs: [], - name: 'simpleFunction', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const singleStaticReturnValue: MethodAbi = { - constant: false, - inputs: [], - name: 'simpleFunction', - outputs: [ - { - name: 'Bytes4', - type: 'bytes4', - }, - ], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const multipleStaticReturnValues: MethodAbi = { - constant: false, - inputs: [], - name: 'simpleFunction', - outputs: [ - { - name: 'val1', - type: 'bytes4', - }, - { - name: 'val2', - type: 'bytes4', - }, - ], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const singleDynamicReturnValue: MethodAbi = { - constant: false, - inputs: [], - name: 'simpleFunction', - outputs: [ - { - name: 'val', - type: 'bytes', - }, - ], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const multipleDynamicReturnValues: MethodAbi = { - constant: false, - inputs: [], - name: 'simpleFunction', - outputs: [ - { - name: 'val1', - type: 'bytes', - }, - { - name: 'val2', - type: 'bytes', - }, - ], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const mixedStaticAndDynamicReturnValues: MethodAbi = { - constant: false, - inputs: [], - name: 'simpleFunction', - outputs: [ - { - name: 'val1', - type: 'bytes4', - }, - { - name: 'val2', - type: 'bytes', - }, - ], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; - -export const structuredReturnValue: MethodAbi = { - constant: false, - inputs: [], - name: 'fillOrder', - outputs: [ - { - components: [ - { - name: 'makerAssetFilledAmount', - type: 'uint256', - }, - { - name: 'takerAssetFilledAmount', - type: 'uint256', - }, - ], - name: 'fillResults', - type: 'tuple', - }, - ], - payable: false, - stateMutability: 'nonpayable', - type: 'function', -}; diff --git a/packages/utils/test/abi_encoder/evm_data_types_test.ts b/packages/utils/test/abi_encoder/evm_data_types_test.ts deleted file mode 100644 index d47d49b77d..0000000000 --- a/packages/utils/test/abi_encoder/evm_data_types_test.ts +++ /dev/null @@ -1,1386 +0,0 @@ -/* tslint:disable max-file-line-count */ -import * as chai from 'chai'; -import * as ethUtil from 'ethereumjs-util'; -import 'mocha'; - -import { AbiEncoder, BigNumber } from '../../src/'; -import { chaiSetup } from '../utils/chai_setup'; - -chaiSetup.configure(); -const expect = chai.expect; - -describe('ABI Encoder: EVM Data Type Encoding/Decoding', () => { - const encodingRules: AbiEncoder.EncodingRules = { shouldOptimize: false }; // optimizer is tested separately. - const nullEncodedArgs = '0x'; - describe('Array', () => { - it('Fixed size; Static elements', async () => { - // Create DataType object - const testDataItem = { name: 'testArray', type: 'int[2]' }; - const dataType = new AbiEncoder.Array(testDataItem); - // Construct args to be encoded - const args = [new BigNumber(5), new BigNumber(6)]; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = - '0x00000000000000000000000000000000000000000000000000000000000000050000000000000000000000000000000000000000000000000000000000000006'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(false)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Dynamic size; Static elements', async () => { - // Create DataType object - const testDataItem = { name: 'testArray', type: 'int[]' }; - const dataType = new AbiEncoder.Array(testDataItem); - // Construct args to be encoded - const args = [new BigNumber(5), new BigNumber(6)]; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = - '0x000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000050000000000000000000000000000000000000000000000000000000000000006'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Fixed size; Dynamic elements', async () => { - // Create DataType object - const testDataItem = { name: 'testArray', type: 'string[2]' }; - const dataType = new AbiEncoder.Array(testDataItem); - // Construct args to be encoded - const args = ['Hello', 'world']; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = - '0x00000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000548656c6c6f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005776f726c64000000000000000000000000000000000000000000000000000000'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Dynamic size; Dynamic elements', async () => { - // Create DataType object - const testDataItem = { name: 'testArray', type: 'string[]' }; - const dataType = new AbiEncoder.Array(testDataItem); - // Construct args to be encoded - const args = ['Hello', 'world']; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = - '0x000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000548656c6c6f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005776f726c64000000000000000000000000000000000000000000000000000000'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Dynamic Size; Multidimensional; Dynamic Elements', async () => { - // Create DataType object - const testDataItem = { name: 'testArray', type: 'bytes[][]' }; - const dataType = new AbiEncoder.Array(testDataItem); - // Construct args to be encoded - const array1 = ['0x01020304', '0x05060708', '0x09101112']; - const array2 = ['0x10111213', '0x14151617']; - const array3 = ['0x18192021']; - const args = [array1, array2, array3]; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = - '0x0000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000001a000000000000000000000000000000000000000000000000000000000000002800000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000e000000000000000000000000000000000000000000000000000000000000000040102030400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000405060708000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004091011120000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000041011121300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000414151617000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000041819202100000000000000000000000000000000000000000000000000000000'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Dynamic Size; Multidimensional; Static Elements', async () => { - // Create DataType object - const testDataItem = { name: 'testArray', type: 'bytes4[][]' }; - const dataType = new AbiEncoder.Array(testDataItem); - // Construct args to be encoded - const array1 = ['0x01020304', '0x05060708', '0x09101112']; - const array2 = ['0x10111213', '0x14151617']; - const array3 = ['0x18192021']; - const args = [array1, array2, array3]; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = - '0x0000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000e00000000000000000000000000000000000000000000000000000000000000140000000000000000000000000000000000000000000000000000000000000000301020304000000000000000000000000000000000000000000000000000000000506070800000000000000000000000000000000000000000000000000000000091011120000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000021011121300000000000000000000000000000000000000000000000000000000141516170000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011819202100000000000000000000000000000000000000000000000000000000'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Static Size; Multidimensional; Static Elements', async () => { - // Create DataType object - const testDataItem = { name: 'testArray', type: 'bytes4[3][2]' }; - const dataType = new AbiEncoder.Array(testDataItem); - // Construct args to be encoded - const array1 = ['0x01020304', '0x05060708', '0x09101112']; - const array2 = ['0x10111213', '0x14151617', '0x18192021']; - const args = [array1, array2]; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = - '0x010203040000000000000000000000000000000000000000000000000000000005060708000000000000000000000000000000000000000000000000000000000910111200000000000000000000000000000000000000000000000000000000101112130000000000000000000000000000000000000000000000000000000014151617000000000000000000000000000000000000000000000000000000001819202100000000000000000000000000000000000000000000000000000000'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Static Size; Multidimensional; Dynamic Elements', async () => { - // Create DataType object - const testDataItem = { name: 'testArray', type: 'bytes[3][2]' }; - const dataType = new AbiEncoder.Array(testDataItem); - // Construct args to be encoded - const array1 = ['0x01020304', '0x05060708', '0x09101112']; - const array2 = ['0x10111213', '0x14151617', '0x18192021']; - const args = [array1, array2]; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = - '0x00000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000160000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000e0000000000000000000000000000000000000000000000000000000000000000401020304000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004050607080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040910111200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000e0000000000000000000000000000000000000000000000000000000000000000410111213000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004141516170000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000041819202100000000000000000000000000000000000000000000000000000000'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Static size; Too Few Elements', async () => { - // Create DataType object - const testDataItem = { name: 'testArray', type: 'string[3]' }; - const dataType = new AbiEncoder.Array(testDataItem); - // Construct args to be encoded - const args = ['Hello', 'world']; - // Encode Args and validate result - expect(() => { - dataType.encode(args, encodingRules); - }).to.throw('Expected array of 3 elements, but got array of length 2'); - }); - it('Static size; Too Many Elements', async () => { - // Create DataType object - const testDataItem = { name: 'testArray', type: 'string[1]' }; - const dataType = new AbiEncoder.Array(testDataItem); - // Construct args to be encoded - const args = ['Hello', 'world']; - // Encode Args and validate result - expect(() => { - dataType.encode(args, encodingRules); - }).to.throw('Expected array of 1 elements, but got array of length 2'); - }); - it('Element Type Mismatch', async () => { - // Create DataType object - const testDataItem = { name: 'testArray', type: 'uint[]' }; - const dataType = new AbiEncoder.Array(testDataItem); - // Construct args to be encoded - const args = [new BigNumber(1), 'Bad Argument']; - // Encode Args and validate result - expect(() => { - dataType.encode(args, encodingRules); - }).to.throw('Tried to assign NaN value'); - }); - it('Should decode NULL to default values (Fixed size; Static elements)', async () => { - // Create DataType object - const testDataItem = { name: 'testArray', type: 'int[2]' }; - const dataType = new AbiEncoder.Array(testDataItem); - const args = [new BigNumber(0), new BigNumber(0)]; - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(nullEncodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - }); - it('Should decode NULL to default values (Dynamic size; Static elements)', async () => { - // Create DataType object - const testDataItem = { name: 'testArray', type: 'int[]' }; - const dataType = new AbiEncoder.Array(testDataItem); - const args: BigNumber[] = []; - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(nullEncodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - }); - it('Should decode NULL to default values (Fixed size; Dynamic elements)', async () => { - // Create DataType object - const testDataItem = { name: 'testArray', type: 'string[2]' }; - const dataType = new AbiEncoder.Array(testDataItem); - const args = ['', '']; - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(nullEncodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - }); - it('Should decode NULL to default values (Dynamic size; Dynamic elements)', async () => { - // Create DataType object - const testDataItem = { name: 'testArray', type: 'string[]' }; - const dataType = new AbiEncoder.Array(testDataItem); - const args: string[] = []; - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(nullEncodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - }); - it('Should decode NULL to default values (Dynamic Size; Multidimensional; Dynamic Elements)', async () => { - // Create DataType object - const testDataItem = { name: 'testArray', type: 'bytes[][]' }; - const dataType = new AbiEncoder.Array(testDataItem); - const args: string[][] = []; - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(nullEncodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - }); - }); - - describe('Tuple', () => { - it('Static elements only', async () => { - // Create DataType object - const testDataItem = { - name: 'Tuple', - type: 'tuple', - components: [{ name: 'field_1', type: 'int32' }, { name: 'field_2', type: 'bool' }], - }; - const dataType = new AbiEncoder.Tuple(testDataItem); - // Construct args to be encoded - const args = { field_1: new BigNumber(-5), field_2: true }; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = - '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffb0000000000000000000000000000000000000000000000000000000000000001'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodingRules = { shouldConvertStructsToObjects: true }; - const decodedArgs = dataType.decode(encodedArgs, decodingRules); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args, encodingRules); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Dynamic elements only', async () => { - // Create DataType object - const testDataItem = { - name: 'Tuple', - type: 'tuple', - components: [{ name: 'field_1', type: 'string' }, { name: 'field_2', type: 'bytes' }], - }; - const dataType = new AbiEncoder.Tuple(testDataItem); - // Construct args to be encoded - const args = { field_1: 'Hello, World!', field_2: '0xabcdef0123456789' }; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = - '0x00000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000d48656c6c6f2c20576f726c6421000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008abcdef0123456789000000000000000000000000000000000000000000000000'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodingRules = { shouldConvertStructsToObjects: true }; - const decodedArgs = dataType.decode(encodedArgs, decodingRules); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Nested Static Array', async () => { - // Create DataType object - const testDataItem = { - name: 'Tuple', - type: 'tuple', - components: [{ name: 'field', type: 'uint[2]' }], - }; - const dataType = new AbiEncoder.Tuple(testDataItem); - // Construct args to be encoded - const args = { field: [new BigNumber(1), new BigNumber(2)] }; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = - '0x00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodingRules = { shouldConvertStructsToObjects: true }; - const decodedArgs = dataType.decode(encodedArgs, decodingRules); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Nested Dynamic Array', async () => { - // Create DataType object - const testDataItem = { - name: 'Tuple', - type: 'tuple', - components: [{ name: 'field', type: 'uint[]' }], - }; - const dataType = new AbiEncoder.Tuple(testDataItem); - // Construct args to be encoded - const args = { field: [new BigNumber(1), new BigNumber(2)] }; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = - '0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodingRules = { shouldConvertStructsToObjects: true }; - const decodedArgs = dataType.decode(encodedArgs, decodingRules); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Nested Static Multidimensional Array', async () => { - // Create DataType object - const testDataItem = { - name: 'Tuple', - type: 'tuple', - components: [{ name: 'field', type: 'bytes4[2][2]' }], - }; - const dataType = new AbiEncoder.Tuple(testDataItem); - // Construct args to be encoded - const array1 = ['0x01020304', '0x05060708']; - const array2 = ['0x09101112', '0x13141516']; - const args = { field: [array1, array2] }; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = - '0x0102030400000000000000000000000000000000000000000000000000000000050607080000000000000000000000000000000000000000000000000000000009101112000000000000000000000000000000000000000000000000000000001314151600000000000000000000000000000000000000000000000000000000'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodingRules = { shouldConvertStructsToObjects: true }; - const decodedArgs = dataType.decode(encodedArgs, decodingRules); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Nested Dynamic Multidimensional Array', async () => { - // Create DataType object - const testDataItem = { - name: 'Tuple', - type: 'tuple', - components: [{ name: 'field', type: 'bytes[2][2]' }], - }; - const dataType = new AbiEncoder.Tuple(testDataItem); - // Construct args to be encoded - const array1 = ['0x01020304', '0x05060708']; - const array2 = ['0x09101112', '0x13141516']; - const args = { field: [array1, array2] }; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = - '0x000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000004010203040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040506070800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000004091011120000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000041314151600000000000000000000000000000000000000000000000000000000'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodingRules = { shouldConvertStructsToObjects: true }; - const decodedArgs = dataType.decode(encodedArgs, decodingRules); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Static and dynamic elements mixed', async () => { - // Create DataType object - const testDataItem = { - name: 'Tuple', - type: 'tuple', - components: [ - { name: 'field_1', type: 'int32' }, - { name: 'field_2', type: 'string' }, - { name: 'field_3', type: 'bool' }, - { name: 'field_4', type: 'bytes' }, - ], - }; - const dataType = new AbiEncoder.Tuple(testDataItem); - // Construct args to be encoded - const args = { - field_1: new BigNumber(-5), - field_2: 'Hello, World!', - field_3: true, - field_4: '0xabcdef0123456789', - }; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = - '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffb0000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000000d48656c6c6f2c20576f726c6421000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008abcdef0123456789000000000000000000000000000000000000000000000000'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodingRules = { shouldConvertStructsToObjects: true }; - const decodedArgs = dataType.decode(encodedArgs, decodingRules); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Missing Key', async () => { - // Create DataType object - const testDataItem = { - name: 'Tuple', - type: 'tuple', - components: [{ name: 'field_1', type: 'int32' }, { name: 'field_2', type: 'bool' }], - }; - const dataType = new AbiEncoder.Tuple(testDataItem); - // Construct args to be encoded - const args = { field_1: new BigNumber(-5) }; - // Encode Args and validate result - expect(() => { - dataType.encode(args, encodingRules); - }).to.throw('Could not assign tuple to object: missing key \'field_2\' in object {"field_1":"-5"}'); - }); - it('Should decode NULL to default values (static elements only)', async () => { - // Create DataType object - const testDataItem = { - name: 'Tuple', - type: 'tuple', - components: [{ name: 'field_1', type: 'int32' }, { name: 'field_2', type: 'bool' }], - }; - const dataType = new AbiEncoder.Tuple(testDataItem); - // Construct args to be encoded - const args = { field_1: new BigNumber(0), field_2: false }; - // Decode Encoded Args and validate result - const decodingRules = { shouldConvertStructsToObjects: true }; - const decodedArgs = dataType.decode(nullEncodedArgs, decodingRules); - expect(decodedArgs).to.be.deep.equal(args); - }); - it('Should decode NULL to default values (static and dynamic elements)', async () => { - // Create DataType object - const testDataItem = { - name: 'Tuple', - type: 'tuple', - components: [ - { name: 'field_1', type: 'int32' }, - { name: 'field_2', type: 'string' }, - { name: 'field_3', type: 'bool' }, - { name: 'field_4', type: 'bytes' }, - ], - }; - const dataType = new AbiEncoder.Tuple(testDataItem); - // Construct args to be encoded - const args = { - field_1: new BigNumber(0), - field_2: '', - field_3: false, - field_4: '0x', - }; - // Decode Encoded Args and validate result - const decodingRules = { shouldConvertStructsToObjects: true }; - const decodedArgs = dataType.decode(nullEncodedArgs, decodingRules); - expect(decodedArgs).to.be.deep.equal(args); - }); - }); - - describe('Address', () => { - it('Valid Address', async () => { - // Create DataType object - const testDataItem = { name: 'Address', type: 'address' }; - const dataType = new AbiEncoder.Address(testDataItem); - // Construct args to be encoded - const args = '0xe41d2489571d322189246dafa5ebde1f4699f498'; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = '0x000000000000000000000000e41d2489571d322189246dafa5ebde1f4699f498'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Invalid Address - input is not valid hex', async () => { - // Create DataType object - const testDataItem = { name: 'Address', type: 'address' }; - const dataType = new AbiEncoder.Address(testDataItem); - // Construct args to be encoded - const args = 'e4'; - // Encode Args and validate result - expect(() => { - dataType.encode(args, encodingRules); - }).to.throw(`Invalid address: '${args}'`); - }); - it('Invalid Address - input is not 20 bytes', async () => { - // Create DataType object - const testDataItem = { name: 'Address', type: 'address' }; - const dataType = new AbiEncoder.Address(testDataItem); - // Construct args to be encoded - const args = '0xe4'; - // Encode Args and validate result - expect(() => { - dataType.encode(args, encodingRules); - }).to.throw(`Invalid address: '${args}'`); - }); - it('Should decode NULL to default value of address zero', async () => { - // Create DataType object - const testDataItem = { name: 'Address', type: 'address' }; - const dataType = new AbiEncoder.Address(testDataItem); - const args = '0x0000000000000000000000000000000000000000'; - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(nullEncodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - }); - }); - - describe('Bool', () => { - it('True', async () => { - // Create DataType object - const testDataItem = { name: 'Boolean', type: 'bool' }; - const dataType = new AbiEncoder.Bool(testDataItem); - // Construct args to be encoded - const args = true; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = '0x0000000000000000000000000000000000000000000000000000000000000001'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('False', async () => { - // Create DataType object - const testDataItem = { name: 'Boolean', type: 'bool' }; - const dataType = new AbiEncoder.Bool(testDataItem); - // Construct args to be encoded - const args = false; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = '0x0000000000000000000000000000000000000000000000000000000000000000'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Should decode NULL to default value of False', async () => { - // Create DataType object - const testDataItem = { name: 'Boolean', type: 'bool' }; - const dataType = new AbiEncoder.Bool(testDataItem); - const args = false; - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(nullEncodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - }); - }); - - describe('Integer', () => { - /* tslint:disable custom-no-magic-numbers */ - const max256BitInteger = new BigNumber(2).pow(255).minus(1); - const min256BitInteger = new BigNumber(2).pow(255).times(-1); - const max32BitInteger = new BigNumber(2).pow(31).minus(1); - const min32BitInteger = new BigNumber(2).pow(31).times(-1); - /* tslint:enable custom-no-magic-numbers */ - - it('Int256 - Positive Base Case', async () => { - // Create DataType object - const testDataItem = { name: 'Integer (256)', type: 'int' }; - const dataType = new AbiEncoder.Int(testDataItem); - // Construct args to be encoded - const args = new BigNumber(1); - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = '0x0000000000000000000000000000000000000000000000000000000000000001'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Int256 - Negative Base Case', async () => { - // Create DataType object - const testDataItem = { name: 'Integer (256)', type: 'int' }; - const dataType = new AbiEncoder.Int(testDataItem); - // Construct args to be encoded - const args = new BigNumber(-1); - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Int256 - Positive Value', async () => { - // Create DataType object - const testDataItem = { name: 'Integer (256)', type: 'int' }; - const dataType = new AbiEncoder.Int(testDataItem); - // Construct args to be encoded - const args = max256BitInteger; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Int256 - Negative Value', async () => { - // Create DataType object - const testDataItem = { name: 'Integer (256)', type: 'int' }; - const dataType = new AbiEncoder.Int(testDataItem); - // Construct args to be encoded - const args = min256BitInteger; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = `0x8000000000000000000000000000000000000000000000000000000000000000`; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Int256 - Value too large', async () => { - // Create DataType object - const testDataItem = { name: 'Integer (256)', type: 'int' }; - const dataType = new AbiEncoder.Int(testDataItem); - // Construct args to be encoded - const args = max256BitInteger.plus(1); - // Encode Args and validate result - expect(() => { - dataType.encode(args, encodingRules); - }).to.throw(); - }); - it('Int256 - Value too small', async () => { - // Create DataType object - const testDataItem = { name: 'Integer (256)', type: 'int' }; - const dataType = new AbiEncoder.Int(testDataItem); - // Construct args to be encoded - const args = min256BitInteger.minus(1); - // Encode Args and validate result - expect(() => { - dataType.encode(args, encodingRules); - }).to.throw(); - }); - it('Int32 - Positive Base Case', async () => { - // Create DataType object - const testDataItem = { name: 'Integer (32)', type: 'int32' }; - const dataType = new AbiEncoder.Int(testDataItem); - // Construct args to be encoded - const args = new BigNumber(1); - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = '0x0000000000000000000000000000000000000000000000000000000000000001'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Int32 - Negative Base Case', async () => { - // Create DataType object - const testDataItem = { name: 'Integer (32)', type: 'int32' }; - const dataType = new AbiEncoder.Int(testDataItem); - // Construct args to be encoded - const args = new BigNumber(-1); - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Int32 - Positive Value', async () => { - // Create DataType object - const testDataItem = { name: 'Integer (32)', type: 'int32' }; - const dataType = new AbiEncoder.Int(testDataItem); - // Construct args to be encoded - const args = max32BitInteger; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = '0x000000000000000000000000000000000000000000000000000000007fffffff'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Int32 - Negative Value', async () => { - // Create DataType object - const testDataItem = { name: 'Integer (32)', type: 'int32' }; - const dataType = new AbiEncoder.Int(testDataItem); - // Construct args to be encoded - const args = min32BitInteger; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = `0xffffffffffffffffffffffffffffffffffffffffffffffffffffffff80000000`; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Int32 - Value too large', async () => { - // Create DataType object - const testDataItem = { name: 'Integer (32)', type: 'int32' }; - const dataType = new AbiEncoder.Int(testDataItem); - // Construct args to be encoded - const args = max32BitInteger.plus(1); - // Encode Args and validate result - expect(() => { - dataType.encode(args, encodingRules); - }).to.throw(); - }); - it('Int32 - Value too small', async () => { - // Create DataType object - const testDataItem = { name: 'Integer (32)', type: 'int32' }; - const dataType = new AbiEncoder.Int(testDataItem); - // Construct args to be encoded - const args = min32BitInteger.minus(1); - // Encode Args and validate result - expect(() => { - dataType.encode(args, encodingRules); - }).to.throw(); - }); - it('Should decode NULL to default value of 0', async () => { - // Create DataType object - const testDataItem = { name: 'Integer (256)', type: 'int' }; - const dataType = new AbiEncoder.Int(testDataItem); - const args = new BigNumber(0); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(nullEncodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - }); - it('Should fail to decode if not enough bytes in calldata', async () => { - // Create DataType object - const testDataItem = { name: 'Integer (256)', type: 'int' }; - const dataType = new AbiEncoder.Int(testDataItem); - const args = new BigNumber(0); - const encodedArgs = dataType.encode(args, encodingRules); - const truncatedCalldataLength = 60; - const encodedArgsTruncated = encodedArgs.substr(0, truncatedCalldataLength); - // Encode Args and validate result - expect(() => { - dataType.decode(encodedArgsTruncated); - }).to.throw(); - }); - }); - - describe('Unsigned Integer', () => { - /* tslint:disable custom-no-magic-numbers */ - const max256BitUnsignedInteger = new BigNumber(2).pow(256).minus(1); - const min256BitUnsignedInteger = new BigNumber(0); - const max32BitUnsignedInteger = new BigNumber(2).pow(32).minus(1); - const min32BitUnsignedInteger = new BigNumber(0); - /* tslint:enable custom-no-magic-numbers */ - - it('UInt256 - Positive Base Case', async () => { - // Create DataType object - const testDataItem = { name: 'Unsigned Integer (256)', type: 'uint' }; - const dataType = new AbiEncoder.UInt(testDataItem); - // Construct args to be encoded - const args = new BigNumber(1); - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = '0x0000000000000000000000000000000000000000000000000000000000000001'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('UInt256 - Positive Value', async () => { - // Create DataType object - const testDataItem = { name: 'Unsigned Integer (256)', type: 'uint' }; - const dataType = new AbiEncoder.UInt(testDataItem); - // Construct args to be encoded - const args = max256BitUnsignedInteger; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('UInt256 - Zero Value', async () => { - // Create DataType object - const testDataItem = { name: 'Unsigned Integer (256)', type: 'uint' }; - const dataType = new AbiEncoder.UInt(testDataItem); - // Construct args to be encoded - const args = min256BitUnsignedInteger; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = `0x0000000000000000000000000000000000000000000000000000000000000000`; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('UInt256 - Value too large', async () => { - // Create DataType object - const testDataItem = { name: 'Unsigned Integer (256)', type: 'uint' }; - const dataType = new AbiEncoder.UInt(testDataItem); - // Construct args to be encoded - const args = max256BitUnsignedInteger.plus(1); - // Encode Args and validate result - expect(() => { - dataType.encode(args, encodingRules); - }).to.throw(); - }); - it('UInt256 - Value too small', async () => { - // Create DataType object - const testDataItem = { name: 'Unsigned Integer (256)', type: 'uint' }; - const dataType = new AbiEncoder.UInt(testDataItem); - // Construct args to be encoded - const args = min256BitUnsignedInteger.minus(1); - // Encode Args and validate result - expect(() => { - dataType.encode(args, encodingRules); - }).to.throw(); - }); - it('UInt32 - Positive Base Case', async () => { - // Create DataType object - const testDataItem = { name: 'Unsigned Integer (32)', type: 'uint32' }; - const dataType = new AbiEncoder.UInt(testDataItem); - // Construct args to be encoded - const args = new BigNumber(1); - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = '0x0000000000000000000000000000000000000000000000000000000000000001'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('UInt32 - Positive Value', async () => { - // Create DataType object - const testDataItem = { name: 'Unsigned Integer (32)', type: 'uint32' }; - const dataType = new AbiEncoder.UInt(testDataItem); - // Construct args to be encoded - const args = max32BitUnsignedInteger; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = '0x00000000000000000000000000000000000000000000000000000000ffffffff'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('UInt32 - Zero Value', async () => { - // Create DataType object - const testDataItem = { name: 'Unsigned Integer (32)', type: 'uint32' }; - const dataType = new AbiEncoder.UInt(testDataItem); - // Construct args to be encoded - const args = min32BitUnsignedInteger; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = `0x0000000000000000000000000000000000000000000000000000000000000000`; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('UInt32 - Value too large', async () => { - // Create DataType object - const testDataItem = { name: 'Unsigned Integer (32)', type: 'uint32' }; - const dataType = new AbiEncoder.UInt(testDataItem); - // Construct args to be encoded - const args = max32BitUnsignedInteger.plus(1); - // Encode Args and validate result - expect(() => { - dataType.encode(args, encodingRules); - }).to.throw(); - }); - it('UInt32 - Value too small', async () => { - // Create DataType object - const testDataItem = { name: 'Unsigned Integer (32)', type: 'uint32' }; - const dataType = new AbiEncoder.UInt(testDataItem); - // Construct args to be encoded - const args = min32BitUnsignedInteger.minus(1); - // Encode Args and validate result - expect(() => { - dataType.encode(args, encodingRules); - }).to.throw(); - }); - it('Should decode NULL to default value of 0', async () => { - // Create DataType object - const testDataItem = { name: 'Unsigned Integer (256)', type: 'uint' }; - const dataType = new AbiEncoder.UInt(testDataItem); - const args = new BigNumber(0); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(nullEncodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - }); - }); - - describe('Static Bytes', () => { - it('Single Byte (byte)', async () => { - // Create DataType object - const testDataItem = { name: 'Static Byte', type: 'byte' }; - const dataType = new AbiEncoder.StaticBytes(testDataItem); - // Construct args to be encoded - const args = '0x05'; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = '0x0500000000000000000000000000000000000000000000000000000000000000'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Single Byte (bytes1)', async () => { - // Create DataType object - const testDataItem = { name: 'Static Bytes1', type: 'bytes1' }; - const dataType = new AbiEncoder.StaticBytes(testDataItem); - // Construct args to be encoded - const args = '0x05'; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = '0x0500000000000000000000000000000000000000000000000000000000000000'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('4 Bytes (bytes4)', async () => { - // Create DataType object - const testDataItem = { name: 'Static Bytes4', type: 'bytes4' }; - const dataType = new AbiEncoder.StaticBytes(testDataItem); - // Construct args to be encoded - const args = '0x00010203'; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = '0x0001020300000000000000000000000000000000000000000000000000000000'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('4 Bytes (bytes4); Encoder must pad input', async () => { - // Create DataType object - const testDataItem = { name: 'Static Bytes4', type: 'bytes4' }; - const dataType = new AbiEncoder.StaticBytes(testDataItem); - // Construct args to be encoded - // Note: There will be padding because this is a bytes32 but we are only passing in 4 bytes. - const args = '0x1a18'; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = '0x1a18000000000000000000000000000000000000000000000000000000000000'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - const paddedArgs = '0x1a180000'; - expect(decodedArgs).to.be.deep.equal(paddedArgs); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('32 Bytes (bytes32)', async () => { - // Create DataType object - const testDataItem = { name: 'Static Bytes32', type: 'bytes32' }; - const dataType = new AbiEncoder.StaticBytes(testDataItem); - // Construct args to be encoded - const args = '0x0001020304050607080911121314151617181920212223242526272829303132'; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = '0x0001020304050607080911121314151617181920212223242526272829303132'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('32 Bytes (bytes32); Encoder must pad input', async () => { - // Create DataType object - const testDataItem = { name: 'Static Bytes32', type: 'bytes32' }; - const dataType = new AbiEncoder.StaticBytes(testDataItem); - // Construct args to be encoded - // Note: There will be padding because this is a bytes32 but we are only passing in 4 bytes. - const args = '0x1a18bf61'; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = '0x1a18bf6100000000000000000000000000000000000000000000000000000000'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - const paddedArgs = '0x1a18bf6100000000000000000000000000000000000000000000000000000000'; - expect(decodedArgs).to.be.deep.equal(paddedArgs); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Should throw when pass in too many bytes (bytes4)', async () => { - // Create DataType object - const testDataItem = { name: 'Static Bytes4', type: 'bytes4' }; - const dataType = new AbiEncoder.StaticBytes(testDataItem); - // Construct args to be encoded - const args = '0x0102030405'; - // Encode Args and validate result - expect(() => { - dataType.encode(args, encodingRules); - }).to.throw( - 'Tried to assign 0x0102030405 (5 bytes), which exceeds max bytes that can be stored in a bytes4', - ); - }); - it('Should throw when pass in too many bytes (bytes32)', async () => { - // Create DataType object - const testDataItem = { name: 'Static Bytes32', type: 'bytes32' }; - const dataType = new AbiEncoder.StaticBytes(testDataItem); - // Construct args to be encoded - const args = '0x010203040506070809101112131415161718192021222324252627282930313233'; - // Encode Args and validate result - expect(() => { - dataType.encode(args, encodingRules); - }).to.throw( - 'Tried to assign 0x010203040506070809101112131415161718192021222324252627282930313233 (33 bytes), which exceeds max bytes that can be stored in a bytes32', - ); - }); - it('Should throw when pass in bad hex (no 0x prefix)', async () => { - // Create DataType object - const testDataItem = { name: 'Static Bytes32', type: 'bytes32' }; - const dataType = new AbiEncoder.StaticBytes(testDataItem); - // Construct args to be encoded - const args = '0102030405060708091011121314151617181920212223242526272829303132'; - // Encode Args and validate result - expect(() => { - dataType.encode(args, encodingRules); - }).to.throw("Tried to encode non-hex value. Value must include '0x' prefix."); - }); - it('Should throw when pass in bad hex (include a half-byte)', async () => { - // Create DataType object - const testDataItem = { name: 'Static Bytes32', type: 'bytes32' }; - const dataType = new AbiEncoder.StaticBytes(testDataItem); - // Construct args to be encoded - const args = '0x010'; - // Encode Args and validate result - expect(() => { - dataType.encode(args, encodingRules); - }).to.throw('Tried to assign 0x010, which is contains a half-byte. Use full bytes only.'); - }); - it('Should decode NULL to default value - Single Byte (byte)', async () => { - // Create DataType object - const testDataItem = { name: 'Static Byte', type: 'byte' }; - const dataType = new AbiEncoder.StaticBytes(testDataItem); - const args = '0x00'; - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(nullEncodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - }); - it('Should decode NULL to default value - 4 Bytes (bytes4)', async () => { - // Create DataType object - const testDataItem = { name: 'Static Bytes4', type: 'bytes4' }; - const dataType = new AbiEncoder.StaticBytes(testDataItem); - const args = '0x00000000'; - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(nullEncodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - }); - it('Should decode NULL to default value - 32 Bytes (bytes32)', async () => { - // Create DataType object - const testDataItem = { name: 'Static Bytes32', type: 'bytes32' }; - const dataType = new AbiEncoder.StaticBytes(testDataItem); - const args = '0x0000000000000000000000000000000000000000000000000000000000000000'; - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(nullEncodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - }); - }); - - describe('Dynamic Bytes', () => { - it('Fits into one EVM word', async () => { - // Create DataType object - const testDataItem = { name: 'Dynamic Bytes', type: 'bytes' }; - const dataType = new AbiEncoder.DynamicBytes(testDataItem); - // Construct args to be encoded - // Note: There will be padding because this is a bytes32 but we are only passing in 4 bytes. - const args = '0x1a18bf61'; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = - '0x00000000000000000000000000000000000000000000000000000000000000041a18bf6100000000000000000000000000000000000000000000000000000000'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Spans multiple EVM words', async () => { - // Create DataType object - const testDataItem = { name: 'Dynamic Bytes', type: 'bytes' }; - const dataType = new AbiEncoder.DynamicBytes(testDataItem); - // Construct args to be encoded - // Note: There will be padding because this is a bytes32 but we are only passing in 4 bytes. - const bytesLength = 40; - const args = `0x${'61'.repeat(bytesLength)}`; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = - '0x000000000000000000000000000000000000000000000000000000000000002861616161616161616161616161616161616161616161616161616161616161616161616161616161000000000000000000000000000000000000000000000000'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Input as Buffer', async () => { - // Create DataType object - const testDataItem = { name: 'Dynamic Bytes', type: 'bytes' }; - const dataType = new AbiEncoder.DynamicBytes(testDataItem); - // Construct args to be encoded - // Note: There will be padding because this is a bytes32 but we are only passing in 4 bytes. - const args = '0x1a18bf61'; - const argsAsBuffer = ethUtil.toBuffer(args); - // Encode Args and validate result - const encodedArgs = dataType.encode(argsAsBuffer); - const expectedEncodedArgs = - '0x00000000000000000000000000000000000000000000000000000000000000041a18bf6100000000000000000000000000000000000000000000000000000000'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Should throw when pass in bad hex (no 0x prefix)', async () => { - // Create DataType object - const testDataItem = { name: 'Static Bytes', type: 'bytes' }; - const dataType = new AbiEncoder.DynamicBytes(testDataItem); - // Construct args to be encoded - const args = '01'; - // Encode Args and validate result - expect(() => { - dataType.encode(args, encodingRules); - }).to.throw("Tried to encode non-hex value. Value must include '0x' prefix."); - }); - it('Should throw when pass in bad hex (include a half-byte)', async () => { - // Create DataType object - const testDataItem = { name: 'Static Bytes', type: 'bytes' }; - const dataType = new AbiEncoder.DynamicBytes(testDataItem); - // Construct args to be encoded - const args = '0x010'; - // Encode Args and validate result - expect(() => { - dataType.encode(args, encodingRules); - }).to.throw('Tried to assign 0x010, which is contains a half-byte. Use full bytes only.'); - }); - it('Should decode NULL to empty byte array', async () => { - // Create DataType object - const testDataItem = { name: 'Dynamic Bytes', type: 'bytes' }; - const dataType = new AbiEncoder.DynamicBytes(testDataItem); - const args = '0x'; - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(nullEncodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - }); - }); - - describe('String', () => { - it('Fits into one EVM word', async () => { - // Create DataType object - const testDataItem = { name: 'String', type: 'string' }; - const dataType = new AbiEncoder.String(testDataItem); - // Construct args to be encoded - // Note: There will be padding because this is a bytes32 but we are only passing in 4 bytes. - const args = 'five'; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = - '0x00000000000000000000000000000000000000000000000000000000000000046669766500000000000000000000000000000000000000000000000000000000'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Spans multiple EVM words', async () => { - // Create DataType object - const testDataItem = { name: 'String', type: 'string' }; - const dataType = new AbiEncoder.String(testDataItem); - // Construct args to be encoded - // Note: There will be padding because this is a bytes32 but we are only passing in 4 bytes. - const bytesLength = 40; - const args = 'a'.repeat(bytesLength); - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = - '0x000000000000000000000000000000000000000000000000000000000000002861616161616161616161616161616161616161616161616161616161616161616161616161616161000000000000000000000000000000000000000000000000'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('String that begins with 0x prefix', async () => { - // Create DataType object - const testDataItem = { name: 'String', type: 'string' }; - const dataType = new AbiEncoder.String(testDataItem); - // Construct args to be encoded - // Note: There will be padding because this is a bytes32 but we are only passing in 4 bytes. - const strLength = 40; - const args = `0x${'a'.repeat(strLength)}`; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = - '0x000000000000000000000000000000000000000000000000000000000000002a30786161616161616161616161616161616161616161616161616161616161616161616161616161616100000000000000000000000000000000000000000000'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('String that has a multibyte UTF-8 character', async () => { - // Create DataType object - const testDataItem = { name: 'String', type: 'string' }; - const dataType = new AbiEncoder.String(testDataItem); - // Construct args to be encoded - const args = '👴🏼'; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = - '0x0000000000000000000000000000000000000000000000000000000000000008f09f91b4f09f8fbc000000000000000000000000000000000000000000000000'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('String that combines single and multibyte UTF-8 characters', async () => { - // Create DataType object - const testDataItem = { name: 'String', type: 'string' }; - const dataType = new AbiEncoder.String(testDataItem); - // Construct args to be encoded - const args = 'Hello 😀👴🏼😁😂😃 world!'; - // Encode Args and validate result - const encodedArgs = dataType.encode(args, encodingRules); - const expectedEncodedArgs = - '0x000000000000000000000000000000000000000000000000000000000000002548656c6c6f20f09f9880f09f91b4f09f8fbcf09f9881f09f9882f09f988320776f726c6421000000000000000000000000000000000000000000000000000000'; - expect(encodedArgs).to.be.equal(expectedEncodedArgs); - // Decode Encoded Args and validate result - const decodedArgs = dataType.decode(encodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - // Validate signature - const dataTypeFromSignature = AbiEncoder.create(dataType.getSignature(true)); - const argsEncodedFromSignature = dataTypeFromSignature.encode(args); - expect(argsEncodedFromSignature).to.be.deep.equal(expectedEncodedArgs); - }); - it('Should decode NULL to empty string', async () => { - // Create DataType object - const testDataItem = { name: 'String', type: 'string' }; - const dataType = new AbiEncoder.String(testDataItem); - // Decode Encoded Args and validate result - const args = ''; - const decodedArgs = dataType.decode(nullEncodedArgs); - expect(decodedArgs).to.be.deep.equal(args); - }); - }); -}); diff --git a/packages/utils/test/abi_encoder/methods_test.ts b/packages/utils/test/abi_encoder/methods_test.ts deleted file mode 100644 index 227ff5aa44..0000000000 --- a/packages/utils/test/abi_encoder/methods_test.ts +++ /dev/null @@ -1,301 +0,0 @@ -import * as chai from 'chai'; -import * as _ from 'lodash'; -import 'mocha'; - -import { AbiEncoder, BigNumber } from '../../src/'; -import { chaiSetup } from '../utils/chai_setup'; - -import * as AbiSamples from './abi_samples/method_abis'; - -chaiSetup.configure(); -const expect = chai.expect; - -describe('ABI Encoder: Method Encoding / Decoding', () => { - const defaultEncodingRules = { shouldOptimize: false }; // optimizer is tested separately. - const defaultDecodingRules = { shouldConvertStructsToObjects: false }; - const runTest = ( - encoder: AbiEncoder.Method, - methodArgs: any, - expectedEncoding: string, - encodingRules = defaultEncodingRules, - decodingRules = defaultDecodingRules, - ) => { - // Validate encoding - // note - the encoder takes an array of parameters as input; - // if there is only 1 parameter then we wrap it in an array (`methodArgsAsAray`) to save code. - const methodArgsAsArray = (encoder.getDataItem().components as any).length > 1 ? methodArgs : [methodArgs]; - const encoding = encoder.encode(methodArgsAsArray, encodingRules); - expect(encoding, 'testing `.encode`').to.be.equal(expectedEncoding); - // Validate decoding - const decodedValue = encoder.decode(encoding, decodingRules); - const decodedValueAsArray = _.isArray(decodedValue) ? decodedValue : _.toArray(decodedValue); - expect(decodedValueAsArray, 'testing `.decode`').to.be.deep.equal(methodArgsAsArray); - // Validate strict decoding - const strictDecodedValue = encoder.strictDecode(encoding, decodingRules); - expect(strictDecodedValue, 'testing `.strictDecode`').to.be.deep.equal(methodArgs); - }; - it('Types with default widths', async () => { - const method = new AbiEncoder.Method(AbiSamples.typesWithDefaultWidthsAbi); - const methodArgs = [ - new BigNumber(1), - new BigNumber(-1), - '0x56', - [new BigNumber(1)], - [new BigNumber(-1)], - ['0x56'], - ]; - const expectedEncoding = - '0x09f2b0c30000000000000000000000000000000000000000000000000000000000000001ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff560000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000140000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00000000000000000000000000000000000000000000000000000000000000015600000000000000000000000000000000000000000000000000000000000000'; - runTest(method, methodArgs, expectedEncoding); - }); - it('Array of Static Tuples (Array has defined length)', async () => { - const method = new AbiEncoder.Method(AbiSamples.arrayOfStaticTuplesWithDefinedLengthAbi); - let value = 0; - const methodArgs = []; - const methodArgsLength = 8; - for (let i = 0; i < methodArgsLength; ++i) { - methodArgs.push([new BigNumber(++value), new BigNumber(++value)]); - } - const expectedEncoding = - '0x9eb20969000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000050000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000700000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000009000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000b000000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000000d000000000000000000000000000000000000000000000000000000000000000e000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000000000000000000000000000000000000000000010'; - runTest(method, methodArgs, expectedEncoding); - }); - it('Array of Static Tuples (Array has dynamic length)', async () => { - const method = new AbiEncoder.Method(AbiSamples.arrayOfStaticTuplesWithDynamicLengthAbi); - let value = 0; - const methodArgs = []; - const methodArgsLength = 8; - for (let i = 0; i < methodArgsLength; ++i) { - methodArgs.push([new BigNumber(++value), new BigNumber(++value)]); - } - const expectedEncoding = - '0x63275d6e00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000050000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000700000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000009000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000b000000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000000d000000000000000000000000000000000000000000000000000000000000000e000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000000000000000000000000000000000000000000010'; - runTest(method, methodArgs, expectedEncoding); - }); - it('Array of Dynamic Tuples (Array has defined length)', async () => { - const method = new AbiEncoder.Method(AbiSamples.arrayOfDynamicTuplesWithDefinedLengthAbi); - let value = 0; - const methodArgs = []; - const methodArgsLength = 8; - for (let i = 0; i < methodArgsLength; ++i) { - methodArgs.push([new BigNumber(++value), new BigNumber(++value).toString()]); - } - const expectedEncoding = - '0xdeedb00f00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000018000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000280000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000000000000000000000000000000000003800000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000048000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000132000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000013400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000500000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000001360000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000070000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000138000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000023130000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000023132000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000d000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000023134000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000023136000000000000000000000000000000000000000000000000000000000000'; - runTest(method, methodArgs, expectedEncoding); - }); - it('Array of Dynamic Tuples (Array has dynamic length)', async () => { - const method = new AbiEncoder.Method(AbiSamples.arrayOfDynamicTuplesWithUndefinedLengthAbi); - let value = 0; - const methodArgs = []; - const methodArgsLength = 8; - for (let i = 0; i < methodArgsLength; ++i) { - methodArgs.push([new BigNumber(++value), new BigNumber(++value).toString()]); - } - const expectedEncoding = - '0x60c847fb000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000018000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000280000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000000000000000000000000000000000003800000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000048000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000132000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000013400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000500000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000001360000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000070000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000138000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000023130000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000023132000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000d000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000023134000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000023136000000000000000000000000000000000000000000000000000000000000'; - runTest(method, methodArgs, expectedEncoding); - }); - it('Multidimensional Arrays / Static Members', async () => { - const method = new AbiEncoder.Method(AbiSamples.multiDimensionalArraysStaticTypeAbi); - // Eight 3-dimensional arrays of uint8[2][2][2] - let value = 0; - const methodArgs = []; - const methodArgsLength = 8; - for (let i = 0; i < methodArgsLength; ++i) { - methodArgs.push([[[++value, ++value], [++value, ++value]], [[++value, ++value], [++value, ++value]]]); - } - // Validate calldata - const expectedEncoding = - '0xc2f47d6f00000000000000000000000000000000000000000000000000000000000001e00000000000000000000000000000000000000000000000000000000000000480000000000000000000000000000000000000000000000000000000000000070000000000000000000000000000000000000000000000000000000000000009600000000000000000000000000000000000000000000000000000000000000b000000000000000000000000000000000000000000000000000000000000000d400000000000000000000000000000000000000000000000000000000000000e600000000000000000000000000000000000000000000000000000000000000039000000000000000000000000000000000000000000000000000000000000003a000000000000000000000000000000000000000000000000000000000000003b000000000000000000000000000000000000000000000000000000000000003c000000000000000000000000000000000000000000000000000000000000003d000000000000000000000000000000000000000000000000000000000000003e000000000000000000000000000000000000000000000000000000000000003f00000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000001600000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000050000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000070000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000001600000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000009000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000b000000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000d000000000000000000000000000000000000000000000000000000000000000e0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000140000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000110000000000000000000000000000000000000000000000000000000000000012000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000130000000000000000000000000000000000000000000000000000000000000014000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000001500000000000000000000000000000000000000000000000000000000000000160000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000001700000000000000000000000000000000000000000000000000000000000000180000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000e000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000019000000000000000000000000000000000000000000000000000000000000001a000000000000000000000000000000000000000000000000000000000000001b000000000000000000000000000000000000000000000000000000000000001c0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000001d000000000000000000000000000000000000000000000000000000000000001e000000000000000000000000000000000000000000000000000000000000001f000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000140000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000210000000000000000000000000000000000000000000000000000000000000022000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000230000000000000000000000000000000000000000000000000000000000000024000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000025000000000000000000000000000000000000000000000000000000000000002600000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000027000000000000000000000000000000000000000000000000000000000000002800000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000029000000000000000000000000000000000000000000000000000000000000002a000000000000000000000000000000000000000000000000000000000000002b000000000000000000000000000000000000000000000000000000000000002c000000000000000000000000000000000000000000000000000000000000002d000000000000000000000000000000000000000000000000000000000000002e000000000000000000000000000000000000000000000000000000000000002f0000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000e00000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000003100000000000000000000000000000000000000000000000000000000000000320000000000000000000000000000000000000000000000000000000000000033000000000000000000000000000000000000000000000000000000000000003400000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000035000000000000000000000000000000000000000000000000000000000000003600000000000000000000000000000000000000000000000000000000000000370000000000000000000000000000000000000000000000000000000000000038'; - runTest(method, methodArgs, expectedEncoding); - }); - - it('Multidimensional Arrays / Dynamic Members', async () => { - const method = new AbiEncoder.Method(AbiSamples.multiDimensionalArraysDynamicTypeAbi); - // Eight 3-dimensional arrays of string[2][2][2] - let value = 0; - const methodArgs = []; - const methodArgsLength = 4; - for (let i = 0; i < methodArgsLength; ++i) { - methodArgs.push([ - [ - [new BigNumber(++value).toString(), new BigNumber(++value).toString()], - [new BigNumber(++value).toString(), new BigNumber(++value).toString()], - ], - [ - [new BigNumber(++value).toString(), new BigNumber(++value).toString()], - [new BigNumber(++value).toString(), new BigNumber(++value).toString()], - ], - ]); - } - const expectedEncoding = - '0x81534ebd0000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000052000000000000000000000000000000000000000000000000000000000000009a00000000000000000000000000000000000000000000000000000000000000e00000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000260000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000120000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000131000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001320000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000013300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000134000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000001350000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000013600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000137000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001380000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000260000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000120000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000139000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002313000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000023131000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000231320000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000002313300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000023134000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000231350000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002313600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000024000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000120000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000231370000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002313800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000023139000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000232300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000012000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000023231000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000232320000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000002323300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000023234000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000232350000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002323600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000232370000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002323800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000002323900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000023330000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000002333100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000023332000000000000000000000000000000000000000000000000000000000000'; - runTest(method, methodArgs, expectedEncoding); - }); - it('Fixed Length Array / Dynamic Members', async () => { - const method = new AbiEncoder.Method(AbiSamples.staticArrayDynamicMembersAbi); - const methodArgs = ['Brave', 'New', 'World']; - const expectedEncoding = - '0x243a6e6e0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000e00000000000000000000000000000000000000000000000000000000000000005427261766500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000034e657700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005576f726c64000000000000000000000000000000000000000000000000000000'; - runTest(method, methodArgs, expectedEncoding); - }); - it('Fixed Length Array / Dynamic Members', async () => { - const method = new AbiEncoder.Method(AbiSamples.staticArrayDynamicMembersAbi); - const methodArgs = ['Brave', 'New', 'World']; - const expectedEncoding = - '0x243a6e6e0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000e00000000000000000000000000000000000000000000000000000000000000005427261766500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000034e657700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005576f726c64000000000000000000000000000000000000000000000000000000'; - runTest(method, methodArgs, expectedEncoding); - }); - it('Unfixed Length Array / Dynamic Members ABI', async () => { - const method = new AbiEncoder.Method(AbiSamples.dynamicArrayDynamicMembersAbi); - const methodArgs = ['Brave', 'New', 'World']; - const expectedEncoding = - '0x13e751a900000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000e00000000000000000000000000000000000000000000000000000000000000005427261766500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000034e657700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005576f726c64000000000000000000000000000000000000000000000000000000'; - runTest(method, methodArgs, expectedEncoding); - }); - it('Unfixed Length Array / Static Members ABI', async () => { - const method = new AbiEncoder.Method(AbiSamples.dynamicArrayStaticMembersAbi); - // tslint:disable-next-line custom-no-magic-numbers - const methodArgs = [127, 14, 54]; - const expectedEncoding = - '0x4fc8a83300000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000007f000000000000000000000000000000000000000000000000000000000000000e0000000000000000000000000000000000000000000000000000000000000036'; - runTest(method, methodArgs, expectedEncoding); - }); - it('Fixed Length Array / Static Members ABI', async () => { - const method = new AbiEncoder.Method(AbiSamples.staticArrayAbi); - // tslint:disable-next-line custom-no-magic-numbers - const methodArgs = [127, 14, 54]; - const expectedEncoding = - '0xf68ade72000000000000000000000000000000000000000000000000000000000000007f000000000000000000000000000000000000000000000000000000000000000e0000000000000000000000000000000000000000000000000000000000000036'; - runTest(method, methodArgs, expectedEncoding); - }); - it('Array ABI', async () => { - const method = new AbiEncoder.Method(AbiSamples.stringAbi); - const methodArgs = ['five', 'six', 'seven']; - const expectedEncoding = - '0x13e751a900000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000e000000000000000000000000000000000000000000000000000000000000000046669766500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000373697800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005736576656e000000000000000000000000000000000000000000000000000000'; - runTest(method, methodArgs, expectedEncoding); - }); - it('Static Tuple', async () => { - const method = new AbiEncoder.Method(AbiSamples.staticTupleAbi); - const methodArgs = [new BigNumber(5), new BigNumber(10), new BigNumber(15), false]; - const expectedEncoding = - '0xa9125e150000000000000000000000000000000000000000000000000000000000000005000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000000000000000000000000000000000000000000000'; - runTest(method, methodArgs, expectedEncoding); - }); - it('Dynamic Tuple (Array input)', async () => { - const method = new AbiEncoder.Method(AbiSamples.dynamicTupleAbi); - const methodArgs = [new BigNumber(5), 'five']; - const expectedEncoding = - '0x5b998f3500000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000005000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000046669766500000000000000000000000000000000000000000000000000000000'; - runTest(method, methodArgs, expectedEncoding); - }); - it('Dynamic Tuple (Object input)', async () => { - const method = new AbiEncoder.Method(AbiSamples.dynamicTupleAbi); - const methodArgs = [new BigNumber(5), 'five']; - const expectedEncoding = - '0x5b998f3500000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000005000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000046669766500000000000000000000000000000000000000000000000000000000'; - runTest(method, methodArgs, expectedEncoding); - }); - it('Large, Flat ABI', async () => { - const method = new AbiEncoder.Method(AbiSamples.largeFlatAbi); - const methodArgs = [ - new BigNumber(256745454), - new BigNumber(-256745454), - new BigNumber(434244), - '0x43', - '0x0001020304050607080911121314151617181920212223242526272829303132', - '0x0001020304050607080911121314151617181920212223242526272829303132080911121314151617181920212223242526272829303132', - 'Little peter piper piped a piping pepper pot', - '0xe41d2489571d322189246dafa5ebde1f4699f498', - true, - ]; - const expectedEncoding = - '0x312d4d42000000000000000000000000000000000000000000000000000000000f4d9feefffffffffffffffffffffffffffffffffffffffffffffffffffffffff0b26012000000000000000000000000000000000000000000000000000000000006a0444300000000000000000000000000000000000000000000000000000000000000000102030405060708091112131415161718192021222324252627282930313200000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000180000000000000000000000000e41d2489571d322189246dafa5ebde1f4699f4980000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000003800010203040506070809111213141516171819202122232425262728293031320809111213141516171819202122232425262728293031320000000000000000000000000000000000000000000000000000000000000000000000000000002c4c6974746c65207065746572207069706572207069706564206120706970696e672070657070657220706f740000000000000000000000000000000000000000'; - runTest(method, methodArgs, expectedEncoding); - }); - it('Large, Nested ABI', async () => { - // Construct Calldata - const method = new AbiEncoder.Method(AbiSamples.largeNestedAbi); - // tslint:disable custom-no-magic-numbers - const someStaticArray = [127, 14, 54]; - // tslint:enable custom-no-magic-numbers - const someStaticArrayWithDynamicMembers = [ - 'the little piping piper piped a piping pipper papper', - 'the kid knows how to write poems, what can I say -- I guess theres a lot I could say to try to fill this line with a lot of text.', - ]; - const someDynamicArrayWithDynamicMembers = [ - '0x38745637834987324827439287423897238947239847', - '0x7283472398237423984723984729847248927498748974284728947239487498749847874329423743492347329847239842374892374892374892347238947289478947489374289472894738942749823743298742389472389473289472389437249823749823742893472398', - '0x283473298473248923749238742398742398472894729843278942374982374892374892743982', - ]; - const some2DArray = [ - [ - 'some string', - 'some another string', - 'there are just too many stringsup in', - 'here', - 'yall ghonna make me lose my mind', - ], - [ - 'the little piping piper piped a piping pipper papper', - 'the kid knows how to write poems, what can I say -- I guess theres a lot I could say to try to fill this line with a lot of text.', - ], - [], - ]; - const someTuple = { - someUint32: new BigNumber(4037824789), - someStr: - 'the kid knows how to write poems, what can I say -- I guess theres a lot I could say to try to fill this line with a lot of text.', - }; - const someTupleWithDynamicTypes = { - someUint: new BigNumber(4024789), - someStr: 'akdhjasjkdhasjkldshdjahdkjsahdajksdhsajkdhsajkdhadjkashdjksadhajkdhsajkdhsadjk', - someBytes: '0x29384723894723843743289742389472398473289472348927489274894738427428947389facdea', - someAddress: '0xe41d2489571d322189246dafa5ebde1f4699f498', - }; - const someTupleWithDynamicTypes2 = { - someUint: new BigNumber(9024789), - someStr: 'ksdhsajkdhsajkdhadjkashdjksadhajkdhsajkdhsadjkakdhjasjkdhasjkldshdjahdkjsahdaj', - someBytes: '0x29384723894398473289472348927489272384374328974238947274894738427428947389facde1', - someAddress: '0x746dafa5ebde1f4699f4981d3221892e41d24895', - }; - const someTupleWithDynamicTypes3 = { - someUint: new BigNumber(1024789), - someStr: 'sdhsajkdhsajkdhadjkashdjakdhjasjkdhasjkldshdjahdkjsahdajkksadhajkdhsajkdhsadjk', - someBytes: '0x38947238437432829384729742389472398473289472348927489274894738427428947389facdef', - someAddress: '0x89571d322189e415ebde1f4699f498d24246dafa', - }; - const someArrayOfTuplesWithDynamicTypes = [someTupleWithDynamicTypes2, someTupleWithDynamicTypes3]; - const methodArgs = [ - someStaticArray, - someStaticArrayWithDynamicMembers, - someDynamicArrayWithDynamicMembers, - some2DArray, - someTuple, - someTupleWithDynamicTypes, - someArrayOfTuplesWithDynamicTypes, - ]; - const expectedEncoding = - '0x4b49031c000000000000000000000000000000000000000000000000000000000000007f000000000000000000000000000000000000000000000000000000000000000e0000000000000000000000000000000000000000000000000000000000000036000000000000000000000000000000000000000000000000000000000000012000000000000000000000000000000000000000000000000000000000000002800000000000000000000000000000000000000000000000000000000000000440000000000000000000000000000000000000000000000000000000000000088000000000000000000000000000000000000000000000000000000000000009800000000000000000000000000000000000000000000000000000000000000ae0000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000034746865206c6974746c6520706970696e67207069706572207069706564206120706970696e6720706970706572207061707065720000000000000000000000000000000000000000000000000000000000000000000000000000000000000081746865206b6964206b6e6f777320686f7720746f20777269746520706f656d732c20776861742063616e204920736179202d2d2049206775657373207468657265732061206c6f74204920636f756c642073617920746f2074727920746f2066696c6c2074686973206c696e6520776974682061206c6f74206f6620746578742e000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000014000000000000000000000000000000000000000000000000000000000000000163874563783498732482743928742389723894723984700000000000000000000000000000000000000000000000000000000000000000000000000000000006e72834723982374239847239847298472489274987489742847289472394874987498478743294237434923473298472398423748923748923748923472389472894789474893742894728947389427498237432987423894723894732894723894372498237498237428934723980000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000027283473298473248923749238742398742398472894729843278942374982374892374892743982000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000002800000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000500000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000e00000000000000000000000000000000000000000000000000000000000000120000000000000000000000000000000000000000000000000000000000000018000000000000000000000000000000000000000000000000000000000000001c0000000000000000000000000000000000000000000000000000000000000000b736f6d6520737472696e670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000013736f6d6520616e6f7468657220737472696e67000000000000000000000000000000000000000000000000000000000000000000000000000000000000000024746865726520617265206a75737420746f6f206d616e7920737472696e6773757020696e0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000046865726500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002079616c6c2067686f6e6e61206d616b65206d65206c6f7365206d79206d696e640000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000034746865206c6974746c6520706970696e67207069706572207069706564206120706970696e6720706970706572207061707065720000000000000000000000000000000000000000000000000000000000000000000000000000000000000081746865206b6964206b6e6f777320686f7720746f20777269746520706f656d732c20776861742063616e204920736179202d2d2049206775657373207468657265732061206c6f74204920636f756c642073617920746f2074727920746f2066696c6c2074686973206c696e6520776974682061206c6f74206f6620746578742e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f0ac511500000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000081746865206b6964206b6e6f777320686f7720746f20777269746520706f656d732c20776861742063616e204920736179202d2d2049206775657373207468657265732061206c6f74204920636f756c642073617920746f2074727920746f2066696c6c2074686973206c696e6520776974682061206c6f74206f6620746578742e0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003d69d500000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000100000000000000000000000000e41d2489571d322189246dafa5ebde1f4699f498000000000000000000000000000000000000000000000000000000000000004e616b64686a61736a6b646861736a6b6c647368646a6168646b6a73616864616a6b73646873616a6b646873616a6b646861646a6b617368646a6b73616468616a6b646873616a6b64687361646a6b000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002829384723894723843743289742389472398473289472348927489274894738427428947389facdea0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000001a0000000000000000000000000000000000000000000000000000000000089b51500000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000100000000000000000000000000746dafa5ebde1f4699f4981d3221892e41d24895000000000000000000000000000000000000000000000000000000000000004e6b73646873616a6b646873616a6b646861646a6b617368646a6b73616468616a6b646873616a6b64687361646a6b616b64686a61736a6b646861736a6b6c647368646a6168646b6a73616864616a000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002829384723894398473289472348927489272384374328974238947274894738427428947389facde100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000fa3150000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000010000000000000000000000000089571d322189e415ebde1f4699f498d24246dafa000000000000000000000000000000000000000000000000000000000000004e73646873616a6b646873616a6b646861646a6b617368646a616b64686a61736a6b646861736a6b6c647368646a6168646b6a73616864616a6b6b73616468616a6b646873616a6b64687361646a6b000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002838947238437432829384729742389472398473289472348927489274894738427428947389facdef000000000000000000000000000000000000000000000000'; - const customDecodingRules = { shouldConvertStructsToObjects: true }; // custom to improve readability - runTest(method, methodArgs, expectedEncoding, defaultEncodingRules, customDecodingRules); - }); - it('Should throw if decoding calldata where selector does not match the method', async () => { - const method = AbiEncoder.createMethod('foobar'); - const methodSelector = method.getSelector(); - const badMethodSelector = '0x01020304'; - expect(() => method.decode(badMethodSelector)).to.throw( - `Tried to decode calldata, but it was missing the function selector. Expected prefix '${methodSelector}'. Got '${badMethodSelector}'.`, - ); - }); - it('Should throw if strict decoding calldata where selector does not match the method', async () => { - const method = AbiEncoder.createMethod('foobar'); - const methodSelector = method.getSelector(); - const badMethodSelector = '0x01020304'; - expect(() => method.strictDecode(badMethodSelector)).to.throw( - `Tried to decode calldata, but it was missing the function selector. Expected prefix '${methodSelector}'. Got '${badMethodSelector}'.`, - ); - }); -}); diff --git a/packages/utils/test/abi_encoder/optimizer_test.ts b/packages/utils/test/abi_encoder/optimizer_test.ts deleted file mode 100644 index c2881f14cc..0000000000 --- a/packages/utils/test/abi_encoder/optimizer_test.ts +++ /dev/null @@ -1,269 +0,0 @@ -import * as chai from 'chai'; -import 'mocha'; - -import { AbiEncoder, BigNumber } from '../../src/'; -import { chaiSetup } from '../utils/chai_setup'; - -import * as OptimizedAbis from './abi_samples/optimizer_abis'; - -chaiSetup.configure(); -const expect = chai.expect; - -describe('ABI Encoder: Optimized Method Encoding/Decoding', () => { - const encodingRules: AbiEncoder.EncodingRules = { shouldOptimize: true }; - it('Duplicate Dynamic Arrays with Static Elements', async () => { - // Generate calldata - const method = new AbiEncoder.Method(OptimizedAbis.duplicateDynamicArraysWithStaticElements); - const array1 = [new BigNumber(100), new BigNumber(150)]; - const array2 = array1; - const args = [array1, array2]; - // Validata calldata - const optimizedCalldata = method.encode(args, encodingRules); - const expectedOptimizedCalldata = - '0x7221063300000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000640000000000000000000000000000000000000000000000000000000000000096'; - expect(optimizedCalldata).to.be.equal(expectedOptimizedCalldata); - // Validate decoding - const decodedArgs = method.decode(optimizedCalldata, { shouldConvertStructsToObjects: false }); - expect(decodedArgs).to.be.deep.equal(args); - }); - it('Duplicate Dynamic Arrays with Dynamic Elements', async () => { - // Generate calldata - const method = new AbiEncoder.Method(OptimizedAbis.duplicateDynamicArraysWithDynamicElements); - const array1 = ['Hello', 'World']; - const array2 = array1; - const args = [array1, array2]; - // Validata calldata - const optimizedCalldata = method.encode(args, encodingRules); - const expectedOptimizedCalldata = - '0xbb4f12e300000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000548656c6c6f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005576f726c64000000000000000000000000000000000000000000000000000000'; - expect(optimizedCalldata).to.be.equal(expectedOptimizedCalldata); - // Validate decoding - const decodedArgs = method.decode(optimizedCalldata, { shouldConvertStructsToObjects: false }); - expect(decodedArgs).to.be.deep.equal(args); - }); - it('Duplicate Static Arrays with Static Elements (should not optimize)', async () => { - // Generate calldata - const method = new AbiEncoder.Method(OptimizedAbis.duplicateStaticArraysWithStaticElements); - const array1 = [new BigNumber(100), new BigNumber(150)]; - const array2 = array1; - const args = [array1, array2]; - // Validata calldata - const optimizedCalldata = method.encode(args, encodingRules); - const expectedOptimizedCalldata = - '0x7f8130430000000000000000000000000000000000000000000000000000000000000064000000000000000000000000000000000000000000000000000000000000009600000000000000000000000000000000000000000000000000000000000000640000000000000000000000000000000000000000000000000000000000000096'; - expect(optimizedCalldata).to.be.equal(expectedOptimizedCalldata); - const unoptimizedCalldata = method.encode(args); - expect(optimizedCalldata).to.be.equal(unoptimizedCalldata); - // Validate decoding - const decodedArgs = method.decode(optimizedCalldata, { shouldConvertStructsToObjects: false }); - expect(decodedArgs).to.be.deep.equal(args); - }); - it('Duplicate Static Arrays with Dynamic Elements', async () => { - // Generate calldata - const method = new AbiEncoder.Method(OptimizedAbis.duplicateStaticArraysWithDynamicElements); - const array1 = ['Hello', 'World']; - const array2 = array1; - const args = [array1, array2]; - // Validata calldata - const optimizedCalldata = method.encode(args, encodingRules); - const expectedOptimizedCalldata = - '0x9fe31f8e0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000548656c6c6f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005576f726c64000000000000000000000000000000000000000000000000000000'; - expect(optimizedCalldata).to.be.equal(expectedOptimizedCalldata); - // Validate decoding - const decodedArgs = method.decode(optimizedCalldata, { shouldConvertStructsToObjects: false }); - expect(decodedArgs).to.be.deep.equal(args); - }); - it('Duplicate Array Elements (should optimize)', async () => { - // Generate calldata - const method = new AbiEncoder.Method(OptimizedAbis.duplicateArrayElements); - const strings = ['Hello', 'World', 'Hello', 'World']; - const args = [strings]; - // Validate calldata - const optimizedCalldata = method.encode(args, encodingRules); - const expectedOptimizedCalldata = - '0x13e751a900000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000000548656c6c6f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005576f726c64000000000000000000000000000000000000000000000000000000'; - expect(optimizedCalldata).to.be.equal(expectedOptimizedCalldata); - // Validate decoding - const decodedArgs = method.decode(optimizedCalldata, { shouldConvertStructsToObjects: false }); - expect(decodedArgs).to.be.deep.equal(args); - }); - it('Duplicate Tuple Fields', async () => { - // Generate calldata - const method = new AbiEncoder.Method(OptimizedAbis.duplicateTupleFields); - const tuple = ['Hello', 'Hello']; - const args = [tuple]; - // Validata calldata - const optimizedCalldata = method.encode(args, encodingRules); - const expectedOptimizedCalldata = - '0x16780a5e000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000548656c6c6f000000000000000000000000000000000000000000000000000000'; - expect(optimizedCalldata).to.be.equal(expectedOptimizedCalldata); - // Validate decoding - const decodedArgs = method.decode(optimizedCalldata, { shouldConvertStructsToObjects: false }); - expect(decodedArgs).to.be.deep.equal(args); - }); - it('Duplicate Strings', async () => { - // Description: - // Two dynamic arrays with the same values. - // In the optimized calldata, only one set of elements should be included. - // Both arrays should point to this set. - // Generate calldata - const method = new AbiEncoder.Method(OptimizedAbis.duplicateStrings); - const args = ['Hello', 'Hello']; - // Validata calldata - const optimizedCalldata = method.encode(args, encodingRules); - const expectedOptimizedCalldata = - '0x07370bfa00000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000548656c6c6f000000000000000000000000000000000000000000000000000000'; - expect(optimizedCalldata).to.be.equal(expectedOptimizedCalldata); - // Validate decoding - const decodedArgs = method.decode(optimizedCalldata, { shouldConvertStructsToObjects: false }); - expect(decodedArgs).to.be.deep.equal(args); - }); - it('Duplicate Bytes', async () => { - // Description: - // Two dynamic arrays with the same values. - // In the optimized calldata, only one set of elements should be included. - // Both arrays should point to this set. - // Generate calldata - const method = new AbiEncoder.Method(OptimizedAbis.duplicateBytes); - const value = '0x01020304050607080910111213141516171819202122232425262728293031323334353637383940'; - const args = [value, value]; - // Validata calldata - const optimizedCalldata = method.encode(args, encodingRules); - const expectedOptimizedCalldata = - '0x6045e42900000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000002801020304050607080910111213141516171819202122232425262728293031323334353637383940000000000000000000000000000000000000000000000000'; - expect(optimizedCalldata).to.be.equal(expectedOptimizedCalldata); - // Validate decoding - const decodedArgs = method.decode(optimizedCalldata, { shouldConvertStructsToObjects: false }); - expect(decodedArgs).to.be.deep.equal(args); - }); - it('Duplicate Tuples', async () => { - // Generate calldata - const method = new AbiEncoder.Method(OptimizedAbis.duplicateTuples); - const tuple1 = ['Hello, World!', new BigNumber(424234)]; - const tuple2 = tuple1; - const args = [tuple1, tuple2]; - // Validata calldata - const optimizedCalldata = method.encode(args, encodingRules); - const expectedOptimizedCalldata = - '0x564f826d000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000006792a000000000000000000000000000000000000000000000000000000000000000d48656c6c6f2c20576f726c642100000000000000000000000000000000000000'; - expect(optimizedCalldata).to.be.equal(expectedOptimizedCalldata); - // Validate decoding - const decodedArgs = method.decode(optimizedCalldata, { shouldConvertStructsToObjects: false }); - expect(decodedArgs).to.be.deep.equal(args); - }); - it('Duplicate Fields Across Two Tuples', async () => { - // Description: - // Generate calldata - const method = new AbiEncoder.Method(OptimizedAbis.duplicateTuples); - const tuple1 = ['Hello, World!', new BigNumber(1)]; - const tuple2 = [tuple1[0], new BigNumber(2)]; - const args = [tuple1, tuple2]; - // Validata calldata - const optimizedCalldata = method.encode(args, encodingRules); - const expectedOptimizedCalldata = - '0x564f826d000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000d48656c6c6f2c20576f726c642100000000000000000000000000000000000000'; - expect(optimizedCalldata).to.be.equal(expectedOptimizedCalldata); - // Validate decoding - const decodedArgs = method.decode(optimizedCalldata, { shouldConvertStructsToObjects: false }); - expect(decodedArgs).to.be.deep.equal(args); - }); - it('Duplicate Arrays, Nested in Separate Tuples', async () => { - // Generate calldata - const method = new AbiEncoder.Method(OptimizedAbis.duplicateArraysNestedInTuples); - const array = [new BigNumber(100), new BigNumber(150), new BigNumber(200)]; - const tuple1 = [array]; - const tuple2 = [array, 'extra argument to prevent exactly matching the tuples']; - const args = [tuple1, tuple2]; - // Validata calldata - const optimizedCalldata = method.encode(args, encodingRules); - const expectedOptimizedCalldata = - '0x18970a9e000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000000000000000000000000000000000064000000000000000000000000000000000000000000000000000000000000009600000000000000000000000000000000000000000000000000000000000000c80000000000000000000000000000000000000000000000000000000000000035657874726120617267756d656e7420746f2070726576656e742065786163746c79206d61746368696e6720746865207475706c65730000000000000000000000'; - expect(optimizedCalldata).to.be.equal(expectedOptimizedCalldata); - // Validate decoding - const decodedArgs = method.decode(optimizedCalldata, { shouldConvertStructsToObjects: false }); - expect(decodedArgs).to.be.deep.equal(args); - }); - it('Duplicate Tuples, Nested in Separate Tuples', async () => { - // Generate calldata - const method = new AbiEncoder.Method(OptimizedAbis.duplicateTuplesNestedInTuples); - const nestedTuple = ['Hello, World!']; - const tuple1 = [nestedTuple]; - const tuple2 = [nestedTuple, 'extra argument to prevent exactly matching the tuples']; - const args = [tuple1, tuple2]; - // Validata calldata - const optimizedCalldata = method.encode(args, encodingRules); - const expectedOptimizedCalldata = - '0x0b4d2e6a000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000d48656c6c6f2c20576f726c6421000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000035657874726120617267756d656e7420746f2070726576656e742065786163746c79206d61746368696e6720746865207475706c65730000000000000000000000'; - expect(optimizedCalldata).to.be.equal(expectedOptimizedCalldata); - // Validate decoding - const decodedArgs = method.decode(optimizedCalldata, { shouldConvertStructsToObjects: false }); - expect(decodedArgs).to.be.deep.equal(args); - }); - it('Duplicate Two-Dimensional Arrays', async () => { - // Generate calldata - const method = new AbiEncoder.Method(OptimizedAbis.duplicateTwoDimensionalArrays); - const twoDimArray1 = [['Hello', 'World'], ['Foo', 'Bar', 'Zaa']]; - const twoDimArray2 = twoDimArray1; - const args = [twoDimArray1, twoDimArray2]; - // Validata calldata - const optimizedCalldata = method.encode(args, { shouldOptimize: false }); - const expectedOptimizedCalldata = - '0x0d28c4f9000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000002c0000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000120000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000548656c6c6f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005576f726c640000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000e00000000000000000000000000000000000000000000000000000000000000003466f6f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003426172000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000035a61610000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000120000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000548656c6c6f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005576f726c640000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000e00000000000000000000000000000000000000000000000000000000000000003466f6f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003426172000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000035a61610000000000000000000000000000000000000000000000000000000000'; - expect(optimizedCalldata).to.be.equal(expectedOptimizedCalldata); - // Validate decoding - const decodedArgs = method.decode(optimizedCalldata, { shouldConvertStructsToObjects: false }); - expect(decodedArgs).to.be.deep.equal(args); - }); - it('Duplicate Array, Nested within Separate Two-Dimensional Arrays', async () => { - // Generate calldata - const method = new AbiEncoder.Method(OptimizedAbis.duplicateTwoDimensionalArrays); - const twoDimArray1 = [['Hello', 'World'], ['Foo']]; - const twoDimArray2 = [['Hello', 'World'], ['Bar']]; - const args = [twoDimArray1, twoDimArray2]; - // Validata calldata - const optimizedCalldata = method.encode(args, encodingRules); - const expectedOptimizedCalldata = - '0x0d28c4f900000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000120000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000003466f6f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000120000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000548656c6c6f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005576f726c640000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000034261720000000000000000000000000000000000000000000000000000000000'; - expect(optimizedCalldata).to.be.equal(expectedOptimizedCalldata); - // Validate decoding - const decodedArgs = method.decode(optimizedCalldata, { shouldConvertStructsToObjects: false }); - expect(decodedArgs).to.be.deep.equal(args); - }); - it('Array Elements Duplicated as Tuple Fields', async () => { - // Generate calldata - const method = new AbiEncoder.Method(OptimizedAbis.arrayElementsDuplicatedAsTupleFields); - // tslint:disable custom-no-magic-numbers - const array = [100, 150, 200, 225]; - // tslint:enable custom-no-magic-numbers - const tuple = [ - [new BigNumber(array[0])], - [new BigNumber(array[1])], - [new BigNumber(array[2])], - [new BigNumber(array[3])], - ]; - const args = [array, tuple]; - // Validata calldata - const optimizedCalldata = method.encode(args, encodingRules); - const expectedOptimizedCalldata = - '0x5b5c78fd0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000064000000000000000000000000000000000000000000000000000000000000009600000000000000000000000000000000000000000000000000000000000000c800000000000000000000000000000000000000000000000000000000000000e1'; - expect(optimizedCalldata).to.be.equal(expectedOptimizedCalldata); - // Validate decoding - const decodedArgs = method.decode(optimizedCalldata, { shouldConvertStructsToObjects: false }); - expect(decodedArgs).to.be.deep.equal(args); - }); - it('Array Elements Duplicated as Separate Parameter', async () => { - // Generate calldata - const method = new AbiEncoder.Method(OptimizedAbis.arrayElementsDuplicatedAsSeparateParameter); - const array = ['Hello', 'Hello', 'Hello', 'World']; - const str = 'Hello'; - const args = [array, str]; - // Validate calldata - const optimizedCalldata = method.encode(args, encodingRules); - const expectedOptimizedCalldata = - '0xe0e0d34900000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000120000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000005576f726c64000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000548656c6c6f000000000000000000000000000000000000000000000000000000'; - expect(optimizedCalldata).to.be.equal(expectedOptimizedCalldata); - // Validate decoding - const decodedArgs = method.decode(optimizedCalldata, { shouldConvertStructsToObjects: false }); - expect(decodedArgs).to.be.deep.equal(args); - }); -}); diff --git a/packages/utils/test/abi_encoder/return_values_test.ts b/packages/utils/test/abi_encoder/return_values_test.ts deleted file mode 100644 index e36e65fbf9..0000000000 --- a/packages/utils/test/abi_encoder/return_values_test.ts +++ /dev/null @@ -1,202 +0,0 @@ -import * as chai from 'chai'; -import 'mocha'; - -import { AbiEncoder, BigNumber } from '../../src/'; -import { chaiSetup } from '../utils/chai_setup'; - -import * as ReturnValueAbis from './abi_samples/return_value_abis'; - -chaiSetup.configure(); -const expect = chai.expect; - -describe('ABI Encoder: Return Value Encoding/Decoding', () => { - const DECODE_BEYOND_CALL_DATA_ERROR = 'Tried to decode beyond the end of calldata'; - const encodingRules: AbiEncoder.EncodingRules = { shouldOptimize: false }; // optimizer is tested separately. - const nullEncodedReturnValue = '0x'; - describe('Standard encoding/decoding', () => { - it('No Return Value', async () => { - // Decode return value - const method = new AbiEncoder.Method(ReturnValueAbis.noReturnValues); - const returnValue = '0x'; - const decodedReturnValue = method.decodeReturnValues(returnValue, { shouldConvertStructsToObjects: false }); - const expectedDecodedReturnValue: any[] = []; - expect(decodedReturnValue).to.be.deep.equal(expectedDecodedReturnValue); - }); - it('Single static return value', async () => { - // Generate Return Value - const method = new AbiEncoder.Method(ReturnValueAbis.singleStaticReturnValue); - const returnValue = ['0x01020304']; - const encodedReturnValue = method.encodeReturnValues(returnValue, encodingRules); - const decodedReturnValue = method.decodeReturnValues(encodedReturnValue, { - shouldConvertStructsToObjects: false, - }); - // Validate decoded return value - expect(decodedReturnValue).to.be.deep.equal(returnValue); - }); - it('Multiple static return values', async () => { - // Generate Return Value - const method = new AbiEncoder.Method(ReturnValueAbis.multipleStaticReturnValues); - const returnValue = ['0x01020304', '0x05060708']; - const encodedReturnValue = method.encodeReturnValues(returnValue, encodingRules); - const decodedReturnValue = method.decodeReturnValues(encodedReturnValue, { - shouldConvertStructsToObjects: false, - }); - // Validate decoded return value - expect(decodedReturnValue).to.be.deep.equal(returnValue); - }); - it('Single dynamic return value', async () => { - // Generate Return Value - const method = new AbiEncoder.Method(ReturnValueAbis.singleDynamicReturnValue); - const returnValue = ['0x01020304']; - const encodedReturnValue = method.encodeReturnValues(returnValue, encodingRules); - const decodedReturnValue = method.decodeReturnValues(encodedReturnValue, { - shouldConvertStructsToObjects: false, - }); - // Validate decoded return value - expect(decodedReturnValue).to.be.deep.equal(returnValue); - }); - it('Multiple dynamic return values', async () => { - // Generate Return Value - const method = new AbiEncoder.Method(ReturnValueAbis.multipleDynamicReturnValues); - const returnValue = ['0x01020304', '0x05060708']; - const encodedReturnValue = method.encodeReturnValues(returnValue, encodingRules); - const decodedReturnValue = method.decodeReturnValues(encodedReturnValue, { - shouldConvertStructsToObjects: false, - }); - // Validate decoded return value - expect(decodedReturnValue).to.be.deep.equal(returnValue); - }); - it('Mixed static/dynamic return values', async () => { - // Generate Return Value - const method = new AbiEncoder.Method(ReturnValueAbis.mixedStaticAndDynamicReturnValues); - const returnValue = ['0x01020304', '0x05060708']; - const encodedReturnValue = method.encodeReturnValues(returnValue, encodingRules); - const decodedReturnValue = method.decodeReturnValues(encodedReturnValue, { - shouldConvertStructsToObjects: false, - }); - // Validate decoded return value - expect(decodedReturnValue).to.be.deep.equal(returnValue); - }); - it('Should decode NULL as default value (single; static)', async () => { - // Generate Return Value - const method = new AbiEncoder.Method(ReturnValueAbis.singleStaticReturnValue); - const returnValue = ['0x00000000']; - - const decodedReturnValue = method.decodeReturnValues(nullEncodedReturnValue, { - shouldConvertStructsToObjects: false, - }); - // Validate decoded return value - expect(decodedReturnValue).to.be.deep.equal(returnValue); - }); - it('Should decode NULL as default value (multiple; static)', async () => { - // Generate Return Value - const method = new AbiEncoder.Method(ReturnValueAbis.multipleStaticReturnValues); - const returnValue = ['0x00000000', '0x00000000']; - const decodedReturnValue = method.decodeReturnValues(nullEncodedReturnValue, { - shouldConvertStructsToObjects: false, - }); - // Validate decoded return value - expect(decodedReturnValue).to.be.deep.equal(returnValue); - }); - it('Should decode NULL as default value (single; dynamic)', async () => { - // Generate Return Value - const method = new AbiEncoder.Method(ReturnValueAbis.singleDynamicReturnValue); - const returnValue = ['0x']; - const decodedReturnValue = method.decodeReturnValues(nullEncodedReturnValue, { - shouldConvertStructsToObjects: false, - }); - // Validate decoded return value - expect(decodedReturnValue).to.be.deep.equal(returnValue); - }); - }); - - describe('Strict encoding/decoding', () => { - it('No Return Value', async () => { - // Decode return value - const method = new AbiEncoder.Method(ReturnValueAbis.noReturnValues); - const returnValue = '0x'; - const decodedReturnValue = method.strictDecodeReturnValue(returnValue); - const expectedDecodedReturnValue = undefined; - expect(decodedReturnValue).to.be.deep.equal(expectedDecodedReturnValue); - }); - it('Single static return value', async () => { - // Generate Return Value - const method = new AbiEncoder.Method(ReturnValueAbis.singleStaticReturnValue); - const returnValue = ['0x01020304']; - const encodedReturnValue = method.encodeReturnValues(returnValue, encodingRules); - const decodedReturnValue = method.strictDecodeReturnValue(encodedReturnValue); - // Validate decoded return value - expect(decodedReturnValue).to.be.deep.equal(returnValue[0]); - }); - it('Multiple static return values', async () => { - // Generate Return Value - const method = new AbiEncoder.Method(ReturnValueAbis.multipleStaticReturnValues); - const returnValue = ['0x01020304', '0x05060708']; - const encodedReturnValue = method.encodeReturnValues(returnValue, encodingRules); - const decodedReturnValue = method.strictDecodeReturnValue<[string, string]>(encodedReturnValue); - // Validate decoded return value - expect(decodedReturnValue).to.be.deep.equal(returnValue); - }); - it('Single dynamic return value', async () => { - // Generate Return Value - const method = new AbiEncoder.Method(ReturnValueAbis.singleDynamicReturnValue); - const returnValue = ['0x01020304']; - const encodedReturnValue = method.encodeReturnValues(returnValue, encodingRules); - const decodedReturnValue = method.strictDecodeReturnValue(encodedReturnValue); - // Validate decoded return value - expect(decodedReturnValue).to.be.deep.equal(returnValue[0]); - }); - it('Multiple dynamic return values', async () => { - // Generate Return Value - const method = new AbiEncoder.Method(ReturnValueAbis.multipleDynamicReturnValues); - const returnValue = ['0x01020304', '0x05060708']; - const encodedReturnValue = method.encodeReturnValues(returnValue, encodingRules); - const decodedReturnValue = method.strictDecodeReturnValue<[string, string]>(encodedReturnValue); - // Validate decoded return value - expect(decodedReturnValue).to.be.deep.equal(returnValue); - }); - it('Struct should include fields', async () => { - // Generate Return Value - const method = new AbiEncoder.Method(ReturnValueAbis.structuredReturnValue); - const returnValue = { - fillResults: { - makerAssetFilledAmount: new BigNumber(50), - takerAssetFilledAmount: new BigNumber(40), - }, - }; - const encodedReturnValue = method.encodeReturnValues(returnValue, encodingRules); - const decodedReturnValue = method.strictDecodeReturnValue<{ - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - }>(encodedReturnValue); - // Validate decoded return value - // Note that only the contents of `fillResults`, not the key itself, is decoded. - // This is by design, as only a struct's contents are encoded and returned by a funciton call. - expect(decodedReturnValue).to.be.deep.equal(returnValue.fillResults); - }); - it('Should fail to decode NULL (single; static)', async () => { - // Generate Return Value - const method = new AbiEncoder.Method(ReturnValueAbis.singleStaticReturnValue); - const encodedReturnValue = '0x'; - const decodeReturnValue = () => method.strictDecodeReturnValue(encodedReturnValue); - // Validate decoded return value - expect(decodeReturnValue).to.throws(DECODE_BEYOND_CALL_DATA_ERROR); - }); - it('Should fail to decode NULL (multiple; static)', async () => { - // Generate Return Value - const method = new AbiEncoder.Method(ReturnValueAbis.multipleStaticReturnValues); - const encodedReturnValue = '0x'; - const decodeReturnValue = () => method.strictDecodeReturnValue<[string, string]>(encodedReturnValue); - // Validate decoded return value - expect(decodeReturnValue).to.throws(DECODE_BEYOND_CALL_DATA_ERROR); - }); - it('Should fail to decode NULL (single; dynamic)', async () => { - // Generate Return Value - const method = new AbiEncoder.Method(ReturnValueAbis.singleDynamicReturnValue); - const encodedReturnValue = '0x'; - const decodeReturnValue = () => method.strictDecodeReturnValue(encodedReturnValue); - // Validate decoded return value - expect(decodeReturnValue).to.throws(DECODE_BEYOND_CALL_DATA_ERROR); - }); - }); -}); diff --git a/packages/utils/test/abi_encoder/signature_test.ts b/packages/utils/test/abi_encoder/signature_test.ts deleted file mode 100644 index cee6fa5e57..0000000000 --- a/packages/utils/test/abi_encoder/signature_test.ts +++ /dev/null @@ -1,393 +0,0 @@ -import * as chai from 'chai'; -import 'mocha'; - -import { AbiEncoder } from '../../src'; -import { chaiSetup } from '../utils/chai_setup'; - -chaiSetup.configure(); -const expect = chai.expect; - -describe('ABI Encoder: Signatures', () => { - describe('Single type', () => { - it('Elementary', async () => { - const signature = 'uint256'; - const dataType = AbiEncoder.create(signature); - const dataTypeId = dataType.getDataItem().type; - expect(dataTypeId).to.be.equal('uint256'); - expect(dataType.getSignature()).to.be.equal(signature); - }); - it('Array', async () => { - const signature = 'string[]'; - const dataType = AbiEncoder.create(signature); - const dataItem = dataType.getDataItem(); - const expectedDataItem = { - name: '', - type: 'string[]', - }; - expect(dataItem).to.be.deep.equal(expectedDataItem); - expect(dataType.getSignature()).to.be.equal(signature); - }); - it('Multidimensional Array', async () => { - // Decode return value - const signature = 'uint256[4][][5]'; - const dataType = AbiEncoder.create(signature); - const dataTypeId = dataType.getDataItem().type; - expect(dataTypeId).to.be.equal(signature); - expect(dataType.getSignature()).to.be.equal(signature); - }); - it('Tuple with single element', async () => { - const signature = '(uint256)'; - const dataType = AbiEncoder.create(signature); - const dataItem = dataType.getDataItem(); - const expectedDataItem = { - name: '', - type: 'tuple', - components: [ - { - name: '', - type: 'uint256', - }, - ], - }; - expect(dataItem).to.be.deep.equal(expectedDataItem); - expect(dataType.getSignature()).to.be.equal(signature); - }); - it('Tuple with multiple elements', async () => { - const signature = '(uint256,string,bytes4)'; - const dataType = AbiEncoder.create(signature); - const dataItem = dataType.getDataItem(); - const expectedDataItem = { - name: '', - type: 'tuple', - components: [ - { - name: '', - type: 'uint256', - }, - { - name: '', - type: 'string', - }, - { - name: '', - type: 'bytes4', - }, - ], - }; - expect(dataItem).to.be.deep.equal(expectedDataItem); - expect(dataType.getSignature()).to.be.equal(signature); - }); - it('Tuple with nested array and nested tuple', async () => { - const signature = '(uint256[],(bytes),string[4],bytes4)'; - const dataType = AbiEncoder.create(signature); - const dataItem = dataType.getDataItem(); - const expectedDataItem = { - name: '', - type: 'tuple', - components: [ - { - name: '', - type: 'uint256[]', - }, - { - name: '', - type: 'tuple', - components: [ - { - name: '', - type: 'bytes', - }, - ], - }, - { - name: '', - type: 'string[4]', - }, - { - name: '', - type: 'bytes4', - }, - ], - }; - expect(dataItem).to.be.deep.equal(expectedDataItem); - expect(dataType.getSignature()).to.be.equal(signature); - }); - it('Array of complex tuples', async () => { - const signature = '(uint256[],(bytes),string[4],bytes4)[5][4][]'; - const dataType = AbiEncoder.create(signature); - const dataItem = dataType.getDataItem(); - const expectedDataItem = { - name: '', - type: 'tuple[5][4][]', - components: [ - { - name: '', - type: 'uint256[]', - }, - { - name: '', - type: 'tuple', - components: [ - { - name: '', - type: 'bytes', - }, - ], - }, - { - name: '', - type: 'string[4]', - }, - { - name: '', - type: 'bytes4', - }, - ], - }; - expect(dataItem).to.be.deep.equal(expectedDataItem); - expect(dataType.getSignature()).to.be.equal(signature); - }); - }); - - describe('Function', () => { - it('No inputs and no outputs', async () => { - // create encoder - const functionName = 'foo'; - const dataType = AbiEncoder.createMethod(functionName); - // create expected values - const expectedSignature = 'foo()'; - const expectedInputDataItem = { - name: 'foo', - type: 'method', - components: [], - }; - const expectedOutputDataItem = { - name: 'foo', - type: 'tuple', - components: [], - }; - // check expected values - expect(dataType.getSignature()).to.be.equal(expectedSignature); - expect(dataType.getDataItem()).to.be.deep.equal(expectedInputDataItem); - expect(dataType.getReturnValueDataItem()).to.be.deep.equal(expectedOutputDataItem); - }); - it('No inputs and no outputs (empty arrays as input)', async () => { - // create encoder - const functionName = 'foo'; - const dataType = AbiEncoder.createMethod(functionName, [], []); - // create expected values - const expectedSignature = 'foo()'; - const expectedInputDataItem = { - name: 'foo', - type: 'method', - components: [], - }; - const expectedOutputDataItem = { - name: 'foo', - type: 'tuple', - components: [], - }; - // check expected values - expect(dataType.getSignature()).to.be.equal(expectedSignature); - expect(dataType.getDataItem()).to.be.deep.equal(expectedInputDataItem); - expect(dataType.getReturnValueDataItem()).to.be.deep.equal(expectedOutputDataItem); - }); - it('Single DataItem input and single DataItem output', async () => { - // create encoder - const functionName = 'foo'; - const inputDataItem = { - name: 'input', - type: 'uint256', - }; - const outputDataItem = { - name: 'output', - type: 'string', - }; - const dataType = AbiEncoder.createMethod(functionName, inputDataItem, outputDataItem); - // create expected values - const expectedSignature = 'foo(uint256)'; - const expectedInputDataItem = { - name: 'foo', - type: 'method', - components: [inputDataItem], - }; - const expectedOutputDataItem = { - name: 'foo', - type: 'tuple', - components: [outputDataItem], - }; - // check expected values - expect(dataType.getSignature()).to.be.equal(expectedSignature); - expect(dataType.getDataItem()).to.be.deep.equal(expectedInputDataItem); - expect(dataType.getReturnValueDataItem()).to.be.deep.equal(expectedOutputDataItem); - }); - it('Single signature input and single signature output', async () => { - // create encoder - const functionName = 'foo'; - const inputSignature = 'uint256'; - const outputSignature = 'string'; - const dataType = AbiEncoder.createMethod(functionName, inputSignature, outputSignature); - // create expected values - const expectedSignature = 'foo(uint256)'; - const expectedInputDataItem = { - name: 'foo', - type: 'method', - components: [ - { - name: '', - type: 'uint256', - }, - ], - }; - const expectedOutputDataItem = { - name: 'foo', - type: 'tuple', - components: [ - { - name: '', - type: 'string', - }, - ], - }; - // check expected values - expect(dataType.getSignature()).to.be.equal(expectedSignature); - expect(dataType.getDataItem()).to.be.deep.equal(expectedInputDataItem); - expect(dataType.getReturnValueDataItem()).to.be.deep.equal(expectedOutputDataItem); - }); - it('Single signature tuple input and single signature tuple output', async () => { - // create encoder - const functionName = 'foo'; - const inputSignature = '(uint256,bytes[][4])'; - const outputSignature = '(string,uint32)'; - const dataType = AbiEncoder.createMethod(functionName, inputSignature, outputSignature); - // create expected values - const expectedSignature = 'foo((uint256,bytes[][4]))'; - const expectedInputDataItem = { - name: 'foo', - type: 'method', - components: [ - { - name: '', - type: 'tuple', - components: [ - { - name: '', - type: 'uint256', - }, - { - name: '', - type: 'bytes[][4]', - }, - ], - }, - ], - }; - const expectedOutputDataItem = { - name: 'foo', - type: 'tuple', - components: [ - { - name: '', - type: 'tuple', - components: [ - { - name: '', - type: 'string', - }, - { - name: '', - type: 'uint32', - }, - ], - }, - ], - }; - // check expected values - expect(dataType.getSignature()).to.be.equal(expectedSignature); - expect(dataType.getDataItem()).to.be.deep.equal(expectedInputDataItem); - expect(dataType.getReturnValueDataItem()).to.be.deep.equal(expectedOutputDataItem); - }); - it('Mutiple DataItem input and multiple DataItem output', async () => { - // create encoder - const functionName = 'foo'; - const inputDataItems = [ - { - name: '', - type: 'uint256', - }, - { - name: '', - type: 'bytes[][4]', - }, - ]; - const outputDataItems = [ - { - name: '', - type: 'string', - }, - { - name: '', - type: 'uint32', - }, - ]; - const dataType = AbiEncoder.createMethod(functionName, inputDataItems, outputDataItems); - // create expected values - const expectedSignature = 'foo(uint256,bytes[][4])'; - const expectedInputDataItem = { - name: 'foo', - type: 'method', - components: inputDataItems, - }; - const expectedOutputDataItem = { - name: 'foo', - type: 'tuple', - components: outputDataItems, - }; - // check expected values - expect(dataType.getSignature()).to.be.equal(expectedSignature); - expect(dataType.getDataItem()).to.be.deep.equal(expectedInputDataItem); - expect(dataType.getReturnValueDataItem()).to.be.deep.equal(expectedOutputDataItem); - }); - it('Multiple signature input and multiple signature output', async () => { - // create encoder - const functionName = 'foo'; - const inputSignatures = ['uint256', 'bytes[][4]']; - const outputSignatures = ['string', 'uint32']; - const dataType = AbiEncoder.createMethod(functionName, inputSignatures, outputSignatures); - // create expected values - const expectedSignature = 'foo(uint256,bytes[][4])'; - const expectedInputDataItem = { - name: 'foo', - type: 'method', - components: [ - { - name: '', - type: 'uint256', - }, - { - name: '', - type: 'bytes[][4]', - }, - ], - }; - const expectedOutputDataItem = { - name: 'foo', - type: 'tuple', - components: [ - { - name: '', - type: 'string', - }, - { - name: '', - type: 'uint32', - }, - ], - }; - // check expected values - expect(dataType.getSignature()).to.be.equal(expectedSignature); - expect(dataType.getDataItem()).to.be.deep.equal(expectedInputDataItem); - expect(dataType.getReturnValueDataItem()).to.be.deep.equal(expectedOutputDataItem); - }); - }); -}); diff --git a/packages/utils/test/abi_utils_test.ts b/packages/utils/test/abi_utils_test.ts deleted file mode 100644 index 0ebee64c48..0000000000 --- a/packages/utils/test/abi_utils_test.ts +++ /dev/null @@ -1,19 +0,0 @@ -import * as chai from 'chai'; -import 'mocha'; - -import { abiUtils } from '../src'; - -const expect = chai.expect; - -describe('abiUtils', () => { - describe('splitTupleTypes', () => { - it('handles basic types', () => { - const got = abiUtils.splitTupleTypes('tuple(bytes,uint256,address)'); - expect(got).to.deep.equal(['bytes', 'uint256', 'address']); - }); - it('handles nested tuple types', () => { - const got = abiUtils.splitTupleTypes('tuple(tuple(bytes,uint256),address)'); - expect(got).to.deep.equal(['tuple(bytes,uint256)', 'address']); - }); - }); -}); diff --git a/packages/utils/test/revert_error_test.ts b/packages/utils/test/revert_error_test.ts deleted file mode 100644 index 2f2796bea2..0000000000 --- a/packages/utils/test/revert_error_test.ts +++ /dev/null @@ -1,201 +0,0 @@ -import * as chai from 'chai'; -import * as _ from 'lodash'; - -import { - AnyRevertError, - getThrownErrorRevertErrorBytes, - RawRevertError, - RevertError, - StringRevertError, -} from '../src/revert_error'; - -import { chaiSetup } from './utils/chai_setup'; - -chaiSetup.configure(); -const expect = chai.expect; - -// tslint:disable: max-classes-per-file -class DescendantRevertError extends StringRevertError { - public constructor(message: string) { - super(message); - } -} - -class CustomRevertError extends RevertError { - public constructor(message?: string) { - super('CustomRevertError', 'CustomRevertError(string message)', { message }); - } -} - -class ArrayRevertError extends RevertError { - public constructor(strings?: string[]) { - super('ArrayRevertError', 'ArrayRevertError(string[] strings)', { strings }); - } -} - -class FixedSizeArrayRevertError extends RevertError { - public constructor(strings?: string[]) { - super('FixedArrayRevertError', 'FixedArrayRevertError(string[2] strings)', { strings }); - } -} - -class ParentRevertError extends RevertError { - public constructor(nestedError?: string) { - super('ParentRevertError', 'ParentRevertError(bytes nestedError)', { nestedError }); - } -} - -RevertError.registerType(CustomRevertError); -RevertError.registerType(ParentRevertError); - -describe('RevertError', () => { - describe('equality', () => { - const message = 'foo'; - it('should equate two identical RevertErrors', () => { - const revert1 = new StringRevertError(message); - const revert2 = new StringRevertError(message); - expect(revert1.equals(revert2)).to.be.true(); - }); - it('should equate two RevertErrors with missing fields', () => { - const revert1 = new StringRevertError(message); - const revert2 = new StringRevertError(); - expect(revert1.equals(revert2)).to.be.true(); - }); - it('should equate AnyRevertError with a real RevertError', () => { - const revert1 = new StringRevertError(message); - const revert2 = new AnyRevertError(); - expect(revert1.equals(revert2)).to.be.true(); - }); - it('should equate two revert errors with identical array fields', () => { - const strings = ['foo', 'bar']; - const revert1 = new ArrayRevertError(strings); - const revert2 = new ArrayRevertError(strings); - expect(revert1.equals(revert2)).to.be.true(); - }); - it('should not equate two revert errors with different sized array fields', () => { - const strings = ['foo', 'bar']; - const revert1 = new ArrayRevertError(strings); - const revert2 = new ArrayRevertError(strings.slice(0, 1)); - expect(revert1.equals(revert2)).to.be.false(); - }); - it('should not equate two revert errors with different array field values', () => { - const strings1 = ['foo', 'bar']; - const strings2 = ['foo', 'baz']; - const revert1 = new ArrayRevertError(strings1); - const revert2 = new ArrayRevertError(strings2); - expect(revert1.equals(revert2)).to.be.false(); - }); - it('should equate two revert errors with identical fixed-size array fields', () => { - const strings = ['foo', 'bar']; - const revert1 = new FixedSizeArrayRevertError(strings); - const revert2 = new FixedSizeArrayRevertError(strings); - expect(revert1.equals(revert2)).to.be.true(); - }); - it('should not equate two revert errors with different sized fixed-size array fields', () => { - const strings = ['foo', 'bar']; - const revert1 = new FixedSizeArrayRevertError(strings); - const revert2 = new FixedSizeArrayRevertError(strings.slice(0, 1)); - expect(revert1.equals(revert2)).to.be.false(); - }); - it('should not equate two revert errors with the wrong sized fixed-size array fields', () => { - const strings = ['foo', 'bar', 'baz']; - const revert1 = new FixedSizeArrayRevertError(strings); - const revert2 = new FixedSizeArrayRevertError(strings); - expect(revert1.equals(revert2)).to.be.false(); - }); - it('should not equate two revert errors with different fixed-size array field values', () => { - const strings1 = ['foo', 'bar']; - const strings2 = ['foo', 'baz']; - const revert1 = new FixedSizeArrayRevertError(strings1); - const revert2 = new FixedSizeArrayRevertError(strings2); - expect(revert1.equals(revert2)).to.be.false(); - }); - it('should not equate a the same RevertError type with different values', () => { - const revert1 = new StringRevertError(message); - const revert2 = new StringRevertError(`${message}1`); - expect(revert1.equals(revert2)).to.be.false(); - }); - it('should not equate different RevertError types', () => { - const revert1 = new StringRevertError(message); - const revert2 = new DescendantRevertError(message); - expect(revert1.equals(revert2)).to.be.false(); - }); - it('should equate two `RawRevertError` types with the same raw data', () => { - const revert1 = new RawRevertError('0x0123456789'); - const revert2 = new RawRevertError(revert1.encode()); - expect(revert1.equals(revert2)).to.be.true(); - }); - it('should not equate two `RawRevertError` types with the different raw data', () => { - const revert1 = new RawRevertError('0x0123456789'); - const revert2 = new RawRevertError(`${revert1.encode()}00`); - expect(revert1.equals(revert2)).to.be.false(); - }); - }); - describe('registering', () => { - it('should throw when registering an already registered signature', () => { - class CustomRevertError2 extends RevertError { - public constructor() { - super('CustomRevertError2', new CustomRevertError().signature, {}); - } - } - expect(() => RevertError.registerType(CustomRevertError2)).to.throw(); - }); - }); - describe('decoding', () => { - // tslint:disable: prefer-template custom-no-magic-numbers - const message = 'foobar'; - const encoded = - '0x08c379a0' + - '0000000000000000000000000000000000000000000000000000000000000020' + - '0000000000000000000000000000000000000000000000000000000000000006' + - Buffer.from(message).toString('hex') + - _.repeat('00', 32 - 6); - - it('should decode an ABI encoded revert error', () => { - const expected = new StringRevertError(message); - const decoded = RevertError.decode(encoded); - expect(decoded.equals(expected)).to.be.true(); - }); - it('should decode an unknown selector as a `RawRevertError`', () => { - const _encoded = encoded.substr(0, 2) + '00' + encoded.substr(4); - const decoded = RevertError.decode(_encoded, true); - expect(decoded).is.instanceof(RawRevertError); - }); - it('should fail to decode a malformed ABI encoded revert error', () => { - const _encoded = encoded.substr(0, encoded.length - 1); - const decode = () => RevertError.decode(_encoded); - expect(decode).to.throw(); - }); - it('should decode a nested revert error', () => { - const nested = new StringRevertError(message); - const parent = new ParentRevertError(nested.encode()); - const decoded = RevertError.decode(parent.encode()); - expect(decoded.encode()).to.equal(new ParentRevertError(nested.encode()).encode()); - }); - }); - describe('getThrownErrorRevertErrorBytes', () => { - it('should decode Parity revert errors', () => { - const revertAbi = '0x1234'; - const parityError = { code: 1234, message: 'VM execution error.', data: `Reverted ${revertAbi}`, name: '' }; - const revertError = getThrownErrorRevertErrorBytes(parityError); - expect(revertError).to.be.eq(revertAbi); - }); - }); - describe('encoding', () => { - const message = 'foobar'; - it('should be able to encode', () => { - const expected = - '0x08c379a0' + - '0000000000000000000000000000000000000000000000000000000000000020' + - '0000000000000000000000000000000000000000000000000000000000000006' + - Buffer.from(message).toString('hex') + - _.repeat('00', 32 - 6); - const revert = new StringRevertError(message); - expect(revert.encode()).to.equal(expected); - }); - it('should throw if missing parameter values', () => { - const revert = new StringRevertError(); - expect(() => revert.encode()).to.throw(); - }); - }); -}); diff --git a/packages/utils/test/sign_typed_data_utils_test.ts b/packages/utils/test/sign_typed_data_utils_test.ts deleted file mode 100644 index 9a3c5b01a2..0000000000 --- a/packages/utils/test/sign_typed_data_utils_test.ts +++ /dev/null @@ -1,166 +0,0 @@ -import * as chai from 'chai'; -import 'mocha'; - -import { signTypedDataUtils } from '../src/sign_typed_data_utils'; - -const expect = chai.expect; - -describe('signTypedDataUtils', () => { - describe('signTypedDataHash', () => { - const simpleSignTypedDataHashHex = '0xb460d69ca60383293877cd765c0f97bd832d66bca720f7e32222ce1118832493'; - const simpleSignTypedData = { - types: { - EIP712Domain: [ - { - name: 'name', - type: 'string', - }, - ], - Test: [ - { - name: 'testAddress', - type: 'address', - }, - { - name: 'testNumber', - type: 'uint256', - }, - ], - }, - domain: { - name: 'Test', - }, - message: { - testAddress: '0x0000000000000000000000000000000000000000', - testNumber: '12345', - }, - primaryType: 'Test', - }; - const orderSignTypedDataHashHex = '0x78772b297e1b0b31089589a6608930cceba855af9d3ccf7b92cf47fa881e21f7'; - const orderSignTypedData = { - types: { - EIP712Domain: [ - { - name: 'name', - type: 'string', - }, - { - name: 'version', - type: 'string', - }, - { - name: 'chainId', - type: 'uint256', - }, - { - name: 'verifyingContract', - type: 'address', - }, - ], - Order: [ - { - name: 'makerAddress', - type: 'address', - }, - { - name: 'takerAddress', - type: 'address', - }, - { - name: 'feeRecipientAddress', - type: 'address', - }, - { - name: 'senderAddress', - type: 'address', - }, - { - name: 'makerAssetAmount', - type: 'uint256', - }, - { - name: 'takerAssetAmount', - type: 'uint256', - }, - { - name: 'makerFee', - type: 'uint256', - }, - { - name: 'takerFee', - type: 'uint256', - }, - { - name: 'expirationTimeSeconds', - type: 'uint256', - }, - { - name: 'salt', - type: 'uint256', - }, - { - name: 'makerAssetData', - type: 'bytes', - }, - { - name: 'takerAssetData', - type: 'bytes', - }, - ], - }, - domain: { - name: '0x Protocol', - version: '2', - chainId: 1337, - verifyingContract: '0x0000000000000000000000000000000000000000', - }, - message: { - makerAddress: '0x0000000000000000000000000000000000000000', - takerAddress: '0x0000000000000000000000000000000000000000', - makerAssetAmount: '1000000000000000000', - takerAssetAmount: '1000000000000000000', - expirationTimeSeconds: '12345', - makerFee: '0', - takerFee: '0', - feeRecipientAddress: '0x0000000000000000000000000000000000000000', - senderAddress: '0x0000000000000000000000000000000000000000', - salt: '12345', - makerAssetData: '0x0000000000000000000000000000000000000000', - takerAssetData: '0x0000000000000000000000000000000000000000', - }, - primaryType: 'Order', - }; - it('creates a hash of the test sign typed data', () => { - const hash = signTypedDataUtils.generateTypedDataHash(simpleSignTypedData).toString('hex'); - const hashHex = `0x${hash}`; - expect(hashHex).to.be.eq(simpleSignTypedDataHashHex); - }); - it('creates a hash of the order sign typed data', () => { - const hash = signTypedDataUtils.generateTypedDataHash(orderSignTypedData).toString('hex'); - const hashHex = `0x${hash}`; - expect(hashHex).to.be.eq(orderSignTypedDataHashHex); - }); - it('creates a hash of an uninitialized order', () => { - const uninitializedOrder = { - ...orderSignTypedData, - message: { - makerAddress: '0x0000000000000000000000000000000000000000', - takerAddress: '0x0000000000000000000000000000000000000000', - makerAssetAmount: 0, - takerAssetAmount: 0, - expirationTimeSeconds: 0, - makerFee: 0, - takerFee: 0, - feeRecipientAddress: '0x0000000000000000000000000000000000000000', - senderAddress: '0x0000000000000000000000000000000000000000', - salt: 0, - makerAssetData: '0x0000000000000000000000000000000000000000', - takerAssetData: '0x0000000000000000000000000000000000000000', - }, - }; - const hash = signTypedDataUtils.generateTypedDataHash(uninitializedOrder).toString('hex'); - const hashHex = `0x${hash}`; - expect(hashHex).to.be.eq('0x510449a190415c4770080d857a1c654b653a0c054c94a7a8e9f08f623f9e824f'); - }); - }); -}); diff --git a/packages/utils/test/utils/chai_setup.ts b/packages/utils/test/utils/chai_setup.ts deleted file mode 100644 index 1a87330932..0000000000 --- a/packages/utils/test/utils/chai_setup.ts +++ /dev/null @@ -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); - }, -}; diff --git a/packages/utils/tsconfig.json b/packages/utils/tsconfig.json deleted file mode 100644 index 718e623c74..0000000000 --- a/packages/utils/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../tsconfig", - "compilerOptions": { - "outDir": "lib", - "rootDir": "." - }, - "include": ["src/**/*", "test/**/*"] -} diff --git a/packages/utils/tslint.json b/packages/utils/tslint.json deleted file mode 100644 index dd9053357e..0000000000 --- a/packages/utils/tslint.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": ["@0x/tslint-config"] -} diff --git a/packages/verdaccio/Dockerfile b/packages/verdaccio/Dockerfile deleted file mode 100644 index 6a6a64abf5..0000000000 --- a/packages/verdaccio/Dockerfile +++ /dev/null @@ -1,3 +0,0 @@ -FROM verdaccio/verdaccio - -ADD conf.yaml /verdaccio/conf/config.yaml diff --git a/packages/verdaccio/README.md b/packages/verdaccio/README.md deleted file mode 100644 index 340cd55124..0000000000 --- a/packages/verdaccio/README.md +++ /dev/null @@ -1,18 +0,0 @@ -## 0x Verdaccio - -This package contains a Dockerfile and conf.yaml file for configuring our own -Docker image for Verdaccio. - -See https://verdaccio.org/docs/en/configuration for more information. - -## Build - -In the root directory for _this package_, run: - -`sudo docker build . -t 0x-verdaccio` - -## Run - -To start Verdaccio run: - -`sudo docker run --rm -i -p 4873:4873 0x-verdaccio` diff --git a/packages/verdaccio/conf.yaml b/packages/verdaccio/conf.yaml deleted file mode 100644 index 24e0369328..0000000000 --- a/packages/verdaccio/conf.yaml +++ /dev/null @@ -1,71 +0,0 @@ -# -# Copied from https://github.com/verdaccio/verdaccio/blob/90fc216649ecd8df31d3706b5c17555fa0a35e4a/conf/docker.yaml -# Only the uplinks section has been modified. -# -# This is the config file used for the docker images. -# It allows all users to do anything, so don't use it on production systems. -# -# Do not configure host and port under `listen` in this file -# as it will be ignored when using docker. -# see https://github.com/verdaccio/verdaccio/blob/master/wiki/docker.md#docker-and-custom-port-configuration -# -# Look here for more config file examples: -# https://github.com/verdaccio/verdaccio/tree/master/conf -# - -# path to a directory with all packages -storage: /verdaccio/storage -# path to a directory with plugins to include -plugins: /verdaccio/plugins - -web: - # WebUI is enabled as default, if you want disable it, just uncomment this line - enable: false - -auth: - htpasswd: - file: /verdaccio/conf/htpasswd - # Maximum amount of users allowed to register, defaults to "+infinity". - # You can set this to -1 to disable registration. - #max_users: 1000 - -# a list of other known repositories we can talk to -uplinks: - npmjs: - url: https://registry.npmjs.org/ - cache: true - max_fails: 5 - -packages: - '@*/*': - # scoped packages - access: $all - publish: $authenticated - proxy: npmjs - - '**': - # allow all users (including non-authenticated users) to read and - # publish all packages - # - # you can specify usernames/groupnames (depending on your auth plugin) - # and three keywords: "$all", "$anonymous", "$authenticated" - access: $all - - # allow all known users to publish packages - # (anyone can register by default, remember?) - publish: $authenticated - - # if package is not available locally, proxy requests to 'npmjs' registry - proxy: npmjs - -# To use `npm audit` uncomment the following section -# middlewares: -# audit: -# enabled: true - -# log settings -logs: - - {type: stdout, format: pretty, level: http} - #- {type: file, path: verdaccio.log, level: info} - -max_body_size: 100mb diff --git a/packages/web3-wrapper/.npmignore b/packages/web3-wrapper/.npmignore deleted file mode 100644 index ea588d4859..0000000000 --- a/packages/web3-wrapper/.npmignore +++ /dev/null @@ -1,9 +0,0 @@ -# Blacklist all files -.* -* -# Whitelist lib -!lib/**/* -# Blacklist tests and publish scripts -/lib/test/* -/lib/monorepo_scripts/ -# Package specific ignore diff --git a/packages/web3-wrapper/CHANGELOG.json b/packages/web3-wrapper/CHANGELOG.json deleted file mode 100644 index a984c0c1de..0000000000 --- a/packages/web3-wrapper/CHANGELOG.json +++ /dev/null @@ -1,789 +0,0 @@ -[ - { - "version": "7.2.0", - "changes": [ - { - "note": "Add geth eth_call support", - "pr": 2620 - }, - { - "note": "Remove duplicate overrides data from the eth_call rpc call", - "pr": 2629 - } - ], - "timestamp": 1594788383 - }, - { - "version": "7.1.0", - "changes": [ - { - "note": "Add `getAccountNonce()` to `Web3Wrapper`", - "pr": 2545 - }, - { - "note": "Update ganache-core", - "pr": 2545 - } - ], - "timestamp": 1592969527 - }, - { - "timestamp": 1582623685, - "version": "7.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1581204851, - "version": "7.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1580988106, - "version": "7.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1579682890, - "version": "7.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1578272714, - "version": "7.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1576540892, - "version": "7.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1575931811, - "version": "7.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "7.0.0", - "changes": [ - { - "note": "Let `toBaseUnitAmount()` accept a `number`", - "pr": 1819 - } - ], - "timestamp": 1575296764 - }, - { - "version": "6.1.0-beta.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1575290197 - }, - { - "version": "6.1.0-beta.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1574030254 - }, - { - "version": "6.1.0-beta.1", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1573159180 - }, - { - "version": "6.1.0-beta.0", - "changes": [ - { - "note": "Let `toBaseUnitAmount()` accept a `number`", - "pr": 1819 - } - ], - "timestamp": 1570135330 - }, - { - "timestamp": 1568744790, - "version": "6.0.13", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1567521715, - "version": "6.0.12", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1566446343, - "version": "6.0.11", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1565296576, - "version": "6.0.10", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1564604963, - "version": "6.0.9", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "6.0.8", - "changes": [ - { - "note": "re-export new ethereum-types types, TupleDataItem", - "pr": 1919 - } - ], - "timestamp": 1563957393 - }, - { - "timestamp": 1563006338, - "version": "6.0.7", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1557507213, - "version": "6.0.6", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "6.0.5", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1554997931 - }, - { - "timestamp": 1553183790, - "version": "6.0.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "6.0.3", - "changes": [ - { - "note": "Update ganache-core to 2.5.3", - "pr": 1707 - } - ], - "timestamp": 1553091633 - }, - { - "timestamp": 1551479279, - "version": "6.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1551220833, - "version": "6.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "6.0.0", - "changes": [ - { - "note": "Add support for EIP1193 providers & Web3.js providers >= 1.0-beta.38", - "pr": 1627 - }, - { - "note": "Update provider params to type SupportedProvider which outlines all supported providers", - "pr": 1627 - } - ], - "timestamp": 1551130135 - }, - { - "version": "5.0.0", - "changes": [ - { - "note": "Export `DecodedCalldata` from @0x/utils", - "pr": 1569 - } - ], - "timestamp": 1549733923 - }, - { - "version": "4.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1549547375 - }, - { - "timestamp": 1549452781, - "version": "4.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "4.0.0", - "changes": [ - { - "note": "Upgrade the bignumber.js to v8.0.2", - "pr": 1517 - }, - { - "note": "Update ganache-core to v2.3.3", - "pr": 1518 - } - ], - "timestamp": 1549373905 - }, - { - "timestamp": 1547561734, - "version": "3.2.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547225310, - "version": "3.2.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1547040760, - "version": "3.2.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.2.1", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1544739608 - }, - { - "version": "3.2.0", - "changes": [ - { - "note": "Return `value` and `gasPrice` as BigNumbers to avoid loss of precision errors", - "pr": 1402 - } - ], - "timestamp": 1544570656 - }, - { - "version": "3.1.6", - "changes": [ - { - "note": "Unmarshall mined transaction receipts", - "pr": 1308 - } - ], - "timestamp": 1543401373 - }, - { - "version": "3.1.5", - "changes": [ - { - "note": "Add unmarshalling of transaction receipts", - "pr": 1291 - }, - { - "note": "Return `undefined` instead of `null` if transaction receipt not found", - "pr": 1291 - } - ], - "timestamp": 1542821676 - }, - { - "timestamp": 1542208198, - "version": "3.1.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542134075, - "version": "3.1.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1542028948, - "version": "3.1.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.1.1", - "changes": [ - { - "note": "Fix bug in `getTransactionByHashAsync` which was causing the return value to have the wrong type (raw fields instead of unmarshalled fields).", - "pr": 1177 - } - ], - "timestamp": 1541740904 - }, - { - "version": "3.1.0", - "changes": [ - { - "note": "Add `signTypedData` to perform EIP712 `eth_signTypedData`.", - "pr": 1102 - }, - { - "note": "Web3Wrapper now throws when an RPC request contains an error field in the response. Previously errors could be swallowed and undefined returned.", - "pr": 1102 - } - ], - "timestamp": 1539871071 - }, - { - "version": "3.0.3", - "changes": [ - { - "note": "Dependencies updated" - } - ], - "timestamp": 1538693146 - }, - { - "timestamp": 1538157789, - "version": "3.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1537907159, - "version": "3.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "3.0.0", - "changes": [ - { - "note": "Rename `getBlockAsync` to `getBlockIfExistsAsync` and rather then throw if the requested block wasn't found, return undefined.", - "pr": 1082 - }, - { - "note": "Expose `sendRawPayloadAsync` so one can easily extend `Web3Wrapper` with their own custom JSON RPC calls", - "pr": 1080 - } - ], - "timestamp": 1537875740 - }, - { - "version": "2.0.3", - "changes": [ - { - "note": "Fixes issue #1076 where Parity now returns a placeholder transactionReceipt before the transaction is mined.", - "pr": 1079 - } - ], - "timestamp": 1537541580 - }, - { - "timestamp": 1536142250, - "version": "2.0.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1535377027, - "version": "2.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "2.0.0", - "changes": [ - { - "note": "Export types: `BlockParam`, `TxData`, `Provider`, `TransactionReceipt`, `Transaction`, `TraceParams`, `TransactionTrace``, BlockWithoutTransactionDat`a, `LogEntry`, `FilterObject`, `CallData`, `TransactionReceiptWithDecodedLogs`, `BlockWithTransactionData``, LogTopi`c, `JSONRPCRequestPayload`, `TransactionReceiptStatus`, `DecodedLogArgs`, `StructLog`, `JSONRPCErrorCallback``, BlockParamLitera`l, `ContractEventArg`, `DecodedLogEntry`, `LogEntryEvent`, `OpCode`, `TxDataPayable`, `JSONRPCResponsePayload``, RawLogEntr`y, `DecodedLogEntryEvent`, `LogWithDecodedArgs`, `AbiDefinition`, `RawLog`, `FunctionAbi`, `EventAbi`, `EventParameter``, MethodAb`i, `ConstructorAbi`, `FallbackAbi`, `DataItem`, `ConstructorStateMutability` and `StateMutability`", - "pr": 924 - }, - { - "note": "Stop exporting types: `CallTxDataBaseRPC` and `AbstractBlockRPC`", - "pr": 924 - }, - { - "note": "Export `AbiDecoder` class", - "pr": 924 - } - ], - "timestamp": 1535133899 - }, - { - "version": "1.2.0", - "changes": [ - { - "note": "Export marshaller to convert between RPC and user-space data formats", - "pr": 938 - }, - { - "note": "Export RPC types", - "pr": 938 - } - ], - "timestamp": 1534210131 - }, - { - "timestamp": 1532619515, - "version": "1.1.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532614997, - "version": "1.1.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "1.1.0", - "changes": [ - { - "note": "Add `getTransactionByHashAsync` method", - "pr": 847 - } - ], - "timestamp": 1532605697 - }, - { - "timestamp": 1532357734, - "version": "1.0.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1532043000, - "version": "1.0.0", - "changes": [ - { - "note": "Stop exporting `marshaller` utility file.", - "pr": 902 - }, - { - "note": "Export `marshaller` utility file.", - "pr": 829 - }, - { - "note": "Add `getNodeTypeAsync` method", - "pr": 812 - }, - { - "note": "Stop exporting uniqueVersionIds object", - "pr": 897 - } - ] - }, - { - "timestamp": 1531919263, - "version": "0.7.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1531149657, - "version": "0.7.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1529397769, - "version": "0.7.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1528070400, - "version": "0.7.0", - "changes": [ - { - "note": "Add `web3Wrapper.getContractCodeAsync`", - "pr": 675 - }, - { - "note": "Add `web3Wrapper.getTransactionTraceAsync`", - "pr": 675 - }, - { - "note": "Add `web3Wrapper.getBlockWithTransactionDataAsync`", - "pr": 675 - }, - { - "note": "Add exported uniqueVersionIds object", - "pr": 622 - }, - { - "note": "Update increaseTimeAsync to work with Geth", - "pr": 622 - }, - { - "note": "Make callAsync throw if raw call result is 0x (null)", - "pr": 622 - }, - { - "note": "Add new setHeadAsync method", - "pr": 622 - }, - { - "note": "Improve performance of awaitTransactionMinedAsync by immediately checking if the transaction was already mined instead of waiting for the first interval.", - "pr": 688 - } - ] - }, - { - "timestamp": 1527009133, - "version": "0.6.4", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1525477860, - "version": "0.6.3", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1525428773, - "version": "0.6.2", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "timestamp": 1524044013, - "version": "0.6.1", - "changes": [ - { - "note": "Dependencies updated" - } - ] - }, - { - "version": "0.6.0", - "changes": [ - { - "note": "Make `isAddress` and `toWei` static", - "pr": 501 - }, - { - "note": "Add static methods `toUnitAmount` and `toBaseUnitAmount`", - "pr": 501 - } - ], - "timestamp": 1523462196 - }, - { - "version": "0.5.0", - "changes": [ - { - "note": "Add `web3Wrapper.awaitTransactionMinedAsync`", - "pr": 485 - }, - { - "note": "Add a public field `abiDecoder: AbiDecoder` which allows you to add your ABIs that are later used to decode logs", - "pr": 485 - }, - { - "note": "Export enum `Web3WrapperErrors` with a single value so far: `TransactionMiningTimeout`", - "pr": 485 - } - ], - "timestamp": 1522673609 - }, - { - "version": "0.4.0", - "changes": [ - { - "note": "Rename `signTransactionAsync` to `signMessageAsync` for clarity", - "pr": 465 - } - ], - "timestamp": 1522658513 - }, - { - "version": "0.3.0", - "changes": [ - { - "note": "Add `web3Wrapper.takeSnapshotAsync`, `web3Wrapper.revertSnapshotAsync`, `web3Wrapper.mineBlockAsync`, `web3Wrapper.increaseTimeAsync`", - "pr": 426 - }, - { - "note": "Add `web3Wrapper.isZeroExWeb3Wrapper` for runtime instanceOf checks", - "pr": 426 - }, - { - "note": "Add a `getProvider` method", - "pr": 444 - } - ], - "timestamp": 1521298800 - }, - { - "version": "0.2.0", - "changes": [ - { - "note": "Ensure all returned user addresses are lowercase", - "pr": 373 - }, - { - "note": "Add `web3Wrapper.callAsync`", - "pr": 413 - }, - { - "note": "Make `web3Wrapper.estimateGas` accept whole `txData` instead of `data`", - "pr": 413 - }, - { - "note": "Remove `web3Wrapper.getContractInstance`", - "pr": 413 - } - ], - "timestamp": 1520089200 - }, - { - "version": "0.1.12", - "changes": [ - { - "note": "Fix publishing issue where .npmignore was not properly excluding undesired content", - "pr": 389 - } - ], - "timestamp": 1518102000 - } -] diff --git a/packages/web3-wrapper/CHANGELOG.md b/packages/web3-wrapper/CHANGELOG.md deleted file mode 100644 index f44f67bf31..0000000000 --- a/packages/web3-wrapper/CHANGELOG.md +++ /dev/null @@ -1,322 +0,0 @@ - - -CHANGELOG - -## v7.2.0 - _July 15, 2020_ - - * Add geth eth_call support (#2620) - * Remove duplicate overrides data from the eth_call rpc call (#2629) - -## v7.1.0 - _June 24, 2020_ - - * Add `getAccountNonce()` to `Web3Wrapper` (#2545) - * Update ganache-core (#2545) - -## v7.0.7 - _February 25, 2020_ - - * Dependencies updated - -## v7.0.6 - _February 8, 2020_ - - * Dependencies updated - -## v7.0.5 - _February 6, 2020_ - - * Dependencies updated - -## v7.0.4 - _January 22, 2020_ - - * Dependencies updated - -## v7.0.3 - _January 6, 2020_ - - * Dependencies updated - -## v7.0.2 - _December 17, 2019_ - - * Dependencies updated - -## v7.0.1 - _December 9, 2019_ - - * Dependencies updated - -## v7.0.0 - _December 2, 2019_ - - * Let `toBaseUnitAmount()` accept a `number` (#1819) - -## v6.1.0-beta.3 - _December 2, 2019_ - - * Dependencies updated - -## v6.1.0-beta.2 - _November 17, 2019_ - - * Dependencies updated - -## v6.1.0-beta.1 - _November 7, 2019_ - - * Dependencies updated - -## v6.1.0-beta.0 - _October 3, 2019_ - - * Let `toBaseUnitAmount()` accept a `number` (#1819) - -## v6.0.13 - _September 17, 2019_ - - * Dependencies updated - -## v6.0.12 - _September 3, 2019_ - - * Dependencies updated - -## v6.0.11 - _August 22, 2019_ - - * Dependencies updated - -## v6.0.10 - _August 8, 2019_ - - * Dependencies updated - -## v6.0.9 - _July 31, 2019_ - - * Dependencies updated - -## v6.0.8 - _July 24, 2019_ - - * re-export new ethereum-types types, TupleDataItem (#1919) - -## v6.0.7 - _July 13, 2019_ - - * Dependencies updated - -## v6.0.6 - _May 10, 2019_ - - * Dependencies updated - -## v6.0.5 - _April 11, 2019_ - - * Dependencies updated - -## v6.0.4 - _March 21, 2019_ - - * Dependencies updated - -## v6.0.3 - _March 20, 2019_ - - * Update ganache-core to 2.5.3 (#1707) - -## v6.0.2 - _March 1, 2019_ - - * Dependencies updated - -## v6.0.1 - _February 26, 2019_ - - * Dependencies updated - -## v6.0.0 - _February 25, 2019_ - - * Add support for EIP1193 providers & Web3.js providers >= 1.0-beta.38 (#1627) - * Update provider params to type SupportedProvider which outlines all supported providers (#1627) - -## v5.0.0 - _February 9, 2019_ - - * Export `DecodedCalldata` from @0x/utils (#1569) - -## v4.0.2 - _February 7, 2019_ - - * Dependencies updated - -## v4.0.1 - _February 6, 2019_ - - * Dependencies updated - -## v4.0.0 - _February 5, 2019_ - - * Upgrade the bignumber.js to v8.0.2 (#1517) - * Update ganache-core to v2.3.3 (#1518) - -## v3.2.4 - _January 15, 2019_ - - * Dependencies updated - -## v3.2.3 - _January 11, 2019_ - - * Dependencies updated - -## v3.2.2 - _January 9, 2019_ - - * Dependencies updated - -## v3.2.1 - _December 13, 2018_ - - * Dependencies updated - -## v3.2.0 - _December 11, 2018_ - - * Return `value` and `gasPrice` as BigNumbers to avoid loss of precision errors (#1402) - -## v3.1.6 - _November 28, 2018_ - - * Unmarshall mined transaction receipts (#1308) - -## v3.1.5 - _November 21, 2018_ - - * Add unmarshalling of transaction receipts (#1291) - * Return `undefined` instead of `null` if transaction receipt not found (#1291) - -## v3.1.4 - _November 14, 2018_ - - * Dependencies updated - -## v3.1.3 - _November 13, 2018_ - - * Dependencies updated - -## v3.1.2 - _November 12, 2018_ - - * Dependencies updated - -## v3.1.1 - _November 9, 2018_ - - * Fix bug in `getTransactionByHashAsync` which was causing the return value to have the wrong type (raw fields instead of unmarshalled fields). (#1177) - -## v3.1.0 - _October 18, 2018_ - - * Add `signTypedData` to perform EIP712 `eth_signTypedData`. (#1102) - * Web3Wrapper now throws when an RPC request contains an error field in the response. Previously errors could be swallowed and undefined returned. (#1102) - -## v3.0.3 - _October 4, 2018_ - - * Dependencies updated - -## v3.0.2 - _September 28, 2018_ - - * Dependencies updated - -## v3.0.1 - _September 25, 2018_ - - * Dependencies updated - -## v3.0.0 - _September 25, 2018_ - - * Rename `getBlockAsync` to `getBlockIfExistsAsync` and rather then throw if the requested block wasn't found, return undefined. (#1082) - * Expose `sendRawPayloadAsync` so one can easily extend `Web3Wrapper` with their own custom JSON RPC calls (#1080) - -## v2.0.3 - _September 21, 2018_ - - * Fixes issue #1076 where Parity now returns a placeholder transactionReceipt before the transaction is mined. (#1079) - -## v2.0.2 - _September 5, 2018_ - - * Dependencies updated - -## v2.0.1 - _August 27, 2018_ - - * Dependencies updated - -## v2.0.0 - _August 24, 2018_ - - * Export types: `BlockParam`, `TxData`, `Provider`, `TransactionReceipt`, `Transaction`, `TraceParams`, `TransactionTrace``, BlockWithoutTransactionDat`a, `LogEntry`, `FilterObject`, `CallData`, `TransactionReceiptWithDecodedLogs`, `BlockWithTransactionData``, LogTopi`c, `JSONRPCRequestPayload`, `TransactionReceiptStatus`, `DecodedLogArgs`, `StructLog`, `JSONRPCErrorCallback``, BlockParamLitera`l, `ContractEventArg`, `DecodedLogEntry`, `LogEntryEvent`, `OpCode`, `TxDataPayable`, `JSONRPCResponsePayload``, RawLogEntr`y, `DecodedLogEntryEvent`, `LogWithDecodedArgs`, `AbiDefinition`, `RawLog`, `FunctionAbi`, `EventAbi`, `EventParameter``, MethodAb`i, `ConstructorAbi`, `FallbackAbi`, `DataItem`, `ConstructorStateMutability` and `StateMutability` (#924) - * Stop exporting types: `CallTxDataBaseRPC` and `AbstractBlockRPC` (#924) - * Export `AbiDecoder` class (#924) - -## v1.2.0 - _August 14, 2018_ - - * Export marshaller to convert between RPC and user-space data formats (#938) - * Export RPC types (#938) - -## v1.1.2 - _July 26, 2018_ - - * Dependencies updated - -## v1.1.1 - _July 26, 2018_ - - * Dependencies updated - -## v1.1.0 - _July 26, 2018_ - - * Add `getTransactionByHashAsync` method (#847) - -## v1.0.1 - _July 23, 2018_ - - * Dependencies updated - -## v1.0.0 - _July 19, 2018_ - - * Stop exporting `marshaller` utility file. (#902) - * Export `marshaller` utility file. (#829) - * Add `getNodeTypeAsync` method (#812) - * Stop exporting uniqueVersionIds object (#897) - -## v0.7.3 - _July 18, 2018_ - - * Dependencies updated - -## v0.7.2 - _July 9, 2018_ - - * Dependencies updated - -## v0.7.1 - _June 19, 2018_ - - * Dependencies updated - -## v0.7.0 - _June 4, 2018_ - - * Add `web3Wrapper.getContractCodeAsync` (#675) - * Add `web3Wrapper.getTransactionTraceAsync` (#675) - * Add `web3Wrapper.getBlockWithTransactionDataAsync` (#675) - * Add exported uniqueVersionIds object (#622) - * Update increaseTimeAsync to work with Geth (#622) - * Make callAsync throw if raw call result is 0x (null) (#622) - * Add new setHeadAsync method (#622) - * Improve performance of awaitTransactionMinedAsync by immediately checking if the transaction was already mined instead of waiting for the first interval. (#688) - -## v0.6.4 - _May 22, 2018_ - - * Dependencies updated - -## v0.6.3 - _May 4, 2018_ - - * Dependencies updated - -## v0.6.2 - _May 4, 2018_ - - * Dependencies updated - -## v0.6.1 - _April 18, 2018_ - - * Dependencies updated - -## v0.6.0 - _April 11, 2018_ - - * Make `isAddress` and `toWei` static (#501) - * Add static methods `toUnitAmount` and `toBaseUnitAmount` (#501) - -## v0.5.0 - _April 2, 2018_ - - * Add `web3Wrapper.awaitTransactionMinedAsync` (#485) - * Add a public field `abiDecoder: AbiDecoder` which allows you to add your ABIs that are later used to decode logs (#485) - * Export enum `Web3WrapperErrors` with a single value so far: `TransactionMiningTimeout` (#485) - -## v0.4.0 - _April 2, 2018_ - - * Rename `signTransactionAsync` to `signMessageAsync` for clarity (#465) - -## v0.3.0 - _March 17, 2018_ - - * Add `web3Wrapper.takeSnapshotAsync`, `web3Wrapper.revertSnapshotAsync`, `web3Wrapper.mineBlockAsync`, `web3Wrapper.increaseTimeAsync` (#426) - * Add `web3Wrapper.isZeroExWeb3Wrapper` for runtime instanceOf checks (#426) - * Add a `getProvider` method (#444) - -## v0.2.0 - _March 3, 2018_ - - * Ensure all returned user addresses are lowercase (#373) - * Add `web3Wrapper.callAsync` (#413) - * Make `web3Wrapper.estimateGas` accept whole `txData` instead of `data` (#413) - * Remove `web3Wrapper.getContractInstance` (#413) - -## v0.1.12 - _February 8, 2018_ - - * Fix publishing issue where .npmignore was not properly excluding undesired content (#389) diff --git a/packages/web3-wrapper/README.md b/packages/web3-wrapper/README.md deleted file mode 100644 index c50ac8dffb..0000000000 --- a/packages/web3-wrapper/README.md +++ /dev/null @@ -1,71 +0,0 @@ -## @0x/web3-wrapper - -Web3-wrapper is a JSON-RPC client for Ethereum nodes. It is a type-safe alternative to [Web3.js](https://github.com/ethereum/web3.js/) written in TypeScript. - -### Read the [Documentation](https://github.com/0xProject/0x-monorepo/blob/development/packages/web3-wrapper/docs/reference.mdx). - -## Installation - -```bash -yarn add @0x/web3-wrapper -``` - -If your project is in [TypeScript](https://www.typescriptlang.org/), add the following to your `tsconfig.json`: - -```json -"compilerOptions": { - "typeRoots": ["node_modules/@0x/typescript-typings/types", "node_modules/@types"], -} -``` - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install dependencies - -If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: - -```bash -yarn config set workspaces-experimental true -``` - -Then install dependencies - -```bash -yarn install -``` - -### Build - -To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory: - -```bash -PKG=@0x/web3-wrapper yarn build -``` - -Or continuously rebuild on change: - -```bash -PKG=@0x/web3-wrapper yarn watch -``` - -### Clean - -```bash -yarn clean -``` - -### Lint - -```bash -yarn lint -``` - -### Run Tests - -```bash -yarn test -``` diff --git a/packages/web3-wrapper/coverage/.gitkeep b/packages/web3-wrapper/coverage/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/web3-wrapper/docs/reference.mdx b/packages/web3-wrapper/docs/reference.mdx deleted file mode 100644 index 781c71af3a..0000000000 --- a/packages/web3-wrapper/docs/reference.mdx +++ /dev/null @@ -1,5485 +0,0 @@ -# Interface: JSONRPCResponsePayload - - -## Properties - -### `Optional` error - -• **error**? : *[JSONRPCResponseError](#class-jsonrpcresponseerror)* - -*Defined in [ethereum-types/src/index.ts:344](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L344)* - -___ - -### id - -• **id**: *number* - -*Defined in [ethereum-types/src/index.ts:342](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L342)* - -___ - -### jsonrpc - -• **jsonrpc**: *string* - -*Defined in [ethereum-types/src/index.ts:343](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L343)* - -___ - -### result - -• **result**: *any* - -*Defined in [ethereum-types/src/index.ts:341](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L341)* - -
- -# Class: Web3Wrapper - -An alternative to the Web3.js library that provides a consistent, clean, promise-based interface. - - -## Constructors - - - -\+ **new Web3Wrapper**(`supportedProvider`: [SupportedProvider](#supportedprovider), `callAndTxnDefaults`: `Partial`): *[Web3Wrapper](#class-web3wrapper)* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:144](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L144)* - -Instantiates a new Web3Wrapper. - -**Parameters:** - -Name | Type | Default | Description | ------- | ------ | ------ | ------ | -`supportedProvider` | [SupportedProvider](#supportedprovider) | - | - | -`callAndTxnDefaults` | `Partial` | {} | Override Call and Txn Data defaults sent with RPC requests to the backing Ethereum node. | - -**Returns:** *[Web3Wrapper](#class-web3wrapper)* - -An instance of the Web3Wrapper class. - -## Properties - -### abiDecoder - -• **abiDecoder**: *`AbiDecoder`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:54](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L54)* - -___ - -### isZeroExWeb3Wrapper - -• **isZeroExWeb3Wrapper**: *boolean* = true - -*Defined in [web3-wrapper/src/web3_wrapper.ts:53](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L53)* - -Flag to check if this instance is of type Web3Wrapper - -## Methods - -### awaitTransactionMinedAsync - -▸ **awaitTransactionMinedAsync**(`txHash`: string, `pollingIntervalMs`: number, `timeoutMs?`: undefined | number): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:576](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L576)* - -Waits for a transaction to be mined and returns the transaction receipt. -Note that just because a transaction was mined does not mean it was -successful. You need to check the status code of the transaction receipt -to find out if it was successful, or use the helper method -awaitTransactionSuccessAsync. - -**Parameters:** - -Name | Type | Default | Description | ------- | ------ | ------ | ------ | -`txHash` | string | - | Transaction hash | -`pollingIntervalMs` | number | 1000 | How often (in ms) should we check if the transaction is mined. | -`timeoutMs?` | undefined \| number | - | How long (in ms) to poll for transaction mined until aborting. | - -**Returns:** *`Promise`* - -Transaction receipt with decoded log args. - -___ - -### awaitTransactionSuccessAsync - -▸ **awaitTransactionSuccessAsync**(`txHash`: string, `pollingIntervalMs`: number, `timeoutMs?`: undefined | number): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:651](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L651)* - -Waits for a transaction to be mined and returns the transaction receipt. -Unlike awaitTransactionMinedAsync, it will throw if the receipt has a -status that is not equal to 1. A status of 0 or null indicates that the -transaction was mined, but failed. See: -https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethgettransactionreceipt - -**Parameters:** - -Name | Type | Default | Description | ------- | ------ | ------ | ------ | -`txHash` | string | - | Transaction hash | -`pollingIntervalMs` | number | 1000 | How often (in ms) should we check if the transaction is mined. | -`timeoutMs?` | undefined \| number | - | How long (in ms) to poll for transaction mined until aborting. | - -**Returns:** *`Promise`* - -Transaction receipt with decoded log args. - -___ - -### callAsync - -▸ **callAsync**(`callData`: `CallData`, `defaultBlock?`: [BlockParam](#blockparam)): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:533](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L533)* - -Call a smart contract method at a given block height - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`callData` | `CallData` | Call data | -`defaultBlock?` | [BlockParam](#blockparam) | Block height at which to make the call. Defaults to `latest` | - -**Returns:** *`Promise`* - -The raw call result - -___ - -### doesContractExistAtAddressAsync - -▸ **doesContractExistAtAddressAsync**(`address`: string): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:281](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L281)* - -Check if a contract exists at a given address - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`address` | string | Address to which to check | - -**Returns:** *`Promise`* - -Whether or not contract code was found at the supplied address - -___ - -### estimateGasAsync - -▸ **estimateGasAsync**(`txData`: `Partial`): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:516](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L516)* - -Calculate the estimated gas cost for a given transaction - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`txData` | `Partial` | Transaction data | - -**Returns:** *`Promise`* - -Estimated gas cost - -___ - -### getAvailableAddressesAsync - -▸ **getAvailableAddressesAsync**(): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:429](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L429)* - -Retrieve the user addresses available through the backing provider - -**Returns:** *`Promise`* - -Available user addresses - -___ - -### getBalanceInWeiAsync - -▸ **getBalanceInWeiAsync**(`owner`: string, `defaultBlock?`: [BlockParam](#blockparam)): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:262](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L262)* - -Retrieves an accounts Ether balance in wei - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`owner` | string | Account whose balance you wish to check | -`defaultBlock?` | [BlockParam](#blockparam) | The block depth at which to fetch the balance (default=latest) | - -**Returns:** *`Promise`* - -Balance in wei - -___ - -### getBlockIfExistsAsync - -▸ **getBlockIfExistsAsync**(`blockParam`: string | [BlockParam](#blockparam)): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:369](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L369)* - -Fetch a specific Ethereum block without transaction data - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`blockParam` | string \| [BlockParam](#blockparam) | The block you wish to fetch (blockHash, blockNumber or blockLiteral) | - -**Returns:** *`Promise`* - -The requested block without transaction data, or undefined if block was not found -(e.g the node isn't fully synced, there was a block re-org and the requested block was uncles, etc...) - -___ - -### getBlockNumberAsync - -▸ **getBlockNumberAsync**(): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:355](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L355)* - -Fetches the latest block number - -**Returns:** *`Promise`* - -Block number - -___ - -### getBlockTimestampAsync - -▸ **getBlockTimestampAsync**(`blockParam`: string | [BlockParam](#blockparam)): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:417](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L417)* - -Fetch a block's timestamp - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`blockParam` | string \| [BlockParam](#blockparam) | The block you wish to fetch (blockHash, blockNumber or blockLiteral) | - -**Returns:** *`Promise`* - -The block's timestamp - -___ - -### getBlockWithTransactionDataAsync - -▸ **getBlockWithTransactionDataAsync**(`blockParam`: string | [BlockParam](#blockparam)): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:395](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L395)* - -Fetch a specific Ethereum block with transaction data - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`blockParam` | string \| [BlockParam](#blockparam) | The block you wish to fetch (blockHash, blockNumber or blockLiteral) | - -**Returns:** *`Promise`* - -The requested block with transaction data - -___ - -### getChainIdAsync - -▸ **getChainIdAsync**(): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:215](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L215)* - -Fetches the chainId of the backing Ethereum node - -**Returns:** *`Promise`* - -The chain id - -___ - -### getContractCodeAsync - -▸ **getContractCodeAsync**(`address`: string, `defaultBlock?`: [BlockParam](#blockparam)): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:294](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L294)* - -Gets the contract code by address - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`address` | string | Address of the contract | -`defaultBlock?` | [BlockParam](#blockparam) | Block height at which to make the call. Defaults to `latest` | - -**Returns:** *`Promise`* - -Code of the contract - -___ - -### getContractDefaults - -▸ **getContractDefaults**(): *`Partial` | undefined* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:163](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L163)* - -Get the contract defaults set to the Web3Wrapper instance - -**Returns:** *`Partial` | undefined* - -CallAndTxnData defaults (e.g gas, gasPrice, nonce, etc...) - -___ - -### getLogsAsync - -▸ **getLogsAsync**(`filter`: `FilterObject`): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:483](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L483)* - -Retrieve smart contract logs for a given filter - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`filter` | `FilterObject` | Parameters by which to filter which logs to retrieve | - -**Returns:** *`Promise`* - -The corresponding log entries - -___ - -### getNetworkIdAsync - -▸ **getNetworkIdAsync**(): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:206](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L206)* - -Fetches the networkId of the backing Ethereum node - -**Returns:** *`Promise`* - -The network id - -___ - -### getNodeTypeAsync - -▸ **getNodeTypeAsync**(): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:698](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L698)* - -Returns either NodeType.Geth or NodeType.Ganache depending on the type of -the backing Ethereum node. Throws for any other type of node. - -**Returns:** *`Promise`* - -___ - -### getNodeVersionAsync - -▸ **getNodeVersionAsync**(): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:198](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L198)* - -Fetch the backing Ethereum node's version string (e.g `MetaMask/v4.2.0`) - -**Returns:** *`Promise`* - -Ethereum node's version string - -___ - -### getProvider - -▸ **getProvider**(): *[SupportedProvider](#supportedprovider)* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:170](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L170)* - -Retrieve the Web3 provider - -**Returns:** *[SupportedProvider](#supportedprovider)* - -Web3 provider instance - -___ - -### getTransactionByHashAsync - -▸ **getTransactionByHashAsync**(`txHash`: string): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:247](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L247)* - -Retrieves the transaction data for a given transaction - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`txHash` | string | Transaction hash | - -**Returns:** *`Promise`* - -The raw transaction data - -___ - -### getTransactionReceiptIfExistsAsync - -▸ **getTransactionReceiptIfExistsAsync**(`txHash`: string): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:225](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L225)* - -Retrieves the transaction receipt for a given transaction hash if found - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`txHash` | string | Transaction hash | - -**Returns:** *`Promise`* - -The transaction receipt, including it's status (0: failed, 1: succeeded). Returns undefined if transaction not found. - -___ - -### getTransactionTraceAsync - -▸ **getTransactionTraceAsync**(`txHash`: string, `traceParams`: `TraceParams`): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:313](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L313)* - -Gets the debug trace of a transaction - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`txHash` | string | Hash of the transactuon to get a trace for | -`traceParams` | `TraceParams` | Config object allowing you to specify if you need memory/storage/stack traces. | - -**Returns:** *`Promise`* - -Transaction trace - -___ - -### increaseTimeAsync - -▸ **increaseTimeAsync**(`timeDelta`: number): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:466](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L466)* - -Increase the next blocks timestamp on TestRPC/Ganache or Geth local node. -Will throw if provider is neither TestRPC/Ganache or Geth. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`timeDelta` | number | Amount of time to add in seconds | - -**Returns:** *`Promise`* - -___ - -### isSenderAddressAvailableAsync - -▸ **isSenderAddressAvailableAsync**(`senderAddress`: string): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:188](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L188)* - -Check whether an address is available through the backing provider. This can be -useful if you want to know whether a user can sign messages or transactions from -a given Ethereum address. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`senderAddress` | string | Address to check availability for | - -**Returns:** *`Promise`* - -Whether the address is available through the provider. - -___ - -### mineBlockAsync - -▸ **mineBlockAsync**(): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:458](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L458)* - -Mine a block on a TestRPC/Ganache local node - -**Returns:** *`Promise`* - -___ - -### revertSnapshotAsync - -▸ **revertSnapshotAsync**(`snapshotId`: number): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:450](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L450)* - -Revert the blockchain state to a previous snapshot state on TestRPC/Ganache local node - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`snapshotId` | number | snapshot id to revert to | - -**Returns:** *`Promise`* - -Whether the revert was successful - -___ - -### sendRawPayloadAsync - -▸ **sendRawPayloadAsync**<**A**>(`payload`: `Partial`): *`Promise
`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:679](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L679)* - -Sends a raw Ethereum JSON RPC payload and returns the response's `result` key - -**Type parameters:** - -▪ **A** - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`payload` | `Partial` | A partial JSON RPC payload. No need to include version, id, params (if none needed) | - -**Returns:** *`Promise`* - -The contents nested under the result key of the response body - -___ - -### sendTransactionAsync - -▸ **sendTransactionAsync**(`txData`: `TxData`): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:555](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L555)* - -Send a transaction - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`txData` | `TxData` | Transaction data | - -**Returns:** *`Promise`* - -Transaction hash - -___ - -### setHeadAsync - -▸ **setHeadAsync**(`blockNumber`: number): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:670](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L670)* - -Calls the 'debug_setHead' JSON RPC method, which sets the current head of -the local chain by block number. Note, this is a destructive action and -may severely damage your chain. Use with extreme caution. As of now, this -is only supported by Geth. It sill throw if the 'debug_setHead' method is -not supported. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`blockNumber` | number | The block number to reset to. | - -**Returns:** *`Promise`* - -___ - -### setProvider - -▸ **setProvider**(`supportedProvider`: [SupportedProvider](#supportedprovider)): *void* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:177](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L177)* - -Update the used Web3 provider - -**Parameters:** - -Name | Type | ------- | ------ | -`supportedProvider` | [SupportedProvider](#supportedprovider) | - -**Returns:** *void* - -___ - -### signMessageAsync - -▸ **signMessageAsync**(`address`: string, `message`: string): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:327](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L327)* - -Sign a message with a specific address's private key (`eth_sign`) - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`address` | string | Address of signer | -`message` | string | Message to sign | - -**Returns:** *`Promise`* - -Signature string (might be VRS or RSV depending on the Signer) - -___ - -### signTypedDataAsync - -▸ **signTypedDataAsync**(`address`: string, `typedData`: any): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:342](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L342)* - -Sign an EIP712 typed data message with a specific address's private key (`eth_signTypedData`) - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`address` | string | Address of signer | -`typedData` | any | Typed data message to sign | - -**Returns:** *`Promise`* - -Signature string (as RSV) - -___ - -### takeSnapshotAsync - -▸ **takeSnapshotAsync**(): *`Promise`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:441](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L441)* - -Take a snapshot of the blockchain state on a TestRPC/Ganache local node - -**Returns:** *`Promise`* - -The snapshot id. This can be used to revert to this snapshot - -___ - -### `Static` isAddress - -▸ **isAddress**(`address`: string): *boolean* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:65](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L65)* - -Check if an address is a valid Ethereum address - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`address` | string | Address to check | - -**Returns:** *boolean* - -Whether the address is a valid Ethereum address - -___ - -### `Static` toBaseUnitAmount - -▸ **toBaseUnitAmount**(`amount`: `BigNumber` | number, `decimals`: number): *`BigNumber`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:91](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L91)* - -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 - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`amount` | `BigNumber` \| number | The amount of units that you would like converted to baseUnits. | -`decimals` | number | The number of decimal places the unit amount has. | - -**Returns:** *`BigNumber`* - -The amount in baseUnits. - -___ - -### `Static` toUnitAmount - -▸ **toUnitAmount**(`amount`: `BigNumber`, `decimals`: number): *`BigNumber`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:76](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L76)* - -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. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`amount` | `BigNumber` | The amount in baseUnits that you would like converted to units. | -`decimals` | number | The number of decimal places the unit amount has. | - -**Returns:** *`BigNumber`* - -The amount in units. - -___ - -### `Static` toWei - -▸ **toWei**(`ethAmount`: `BigNumber`): *`BigNumber`* - -*Defined in [web3-wrapper/src/web3_wrapper.ts:106](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/web3_wrapper.ts#L106)* - -Convert an Ether amount from ETH to Wei - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`ethAmount` | `BigNumber` | Amount of Ether to convert to wei | - -**Returns:** *`BigNumber`* - -Amount in wei - -
- - - -# Enumeration: BlockParamLiteral - - -## Enumeration members - -### Earliest - -• **Earliest**: = "earliest" - -*Defined in [ethereum-types/src/index.ts:479](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L479)* - -___ - -### Latest - -• **Latest**: = "latest" - -*Defined in [ethereum-types/src/index.ts:480](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L480)* - -___ - -### Pending - -• **Pending**: = "pending" - -*Defined in [ethereum-types/src/index.ts:481](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L481)* - -
- -# Enumeration: OpCode - - -## Enumeration members - -### Add - -• **Add**: = "ADD" - -*Defined in [ethereum-types/src/index.ts:148](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L148)* - -___ - -### AddMod - -• **AddMod**: = "ADDMOD" - -*Defined in [ethereum-types/src/index.ts:155](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L155)* - -___ - -### Address - -• **Address**: = "ADDRESS" - -*Defined in [ethereum-types/src/index.ts:174](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L174)* - -___ - -### And - -• **And**: = "AND" - -*Defined in [ethereum-types/src/index.ts:166](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L166)* - -___ - -### Balance - -• **Balance**: = "BALANCE" - -*Defined in [ethereum-types/src/index.ts:175](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L175)* - -___ - -### BlockHash - -• **BlockHash**: = "BLOCKHASH" - -*Defined in [ethereum-types/src/index.ts:190](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L190)* - -___ - -### Byte - -• **Byte**: = "BYTE" - -*Defined in [ethereum-types/src/index.ts:170](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L170)* - -___ - -### Call - -• **Call**: = "CALL" - -*Defined in [ethereum-types/src/index.ts:283](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L283)* - -___ - -### CallCode - -• **CallCode**: = "CALLCODE" - -*Defined in [ethereum-types/src/index.ts:284](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L284)* - -___ - -### CallDataCopy - -• **CallDataCopy**: = "CALLDATACOPY" - -*Defined in [ethereum-types/src/index.ts:181](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L181)* - -___ - -### CallDataLoad - -• **CallDataLoad**: = "CALLDATALOAD" - -*Defined in [ethereum-types/src/index.ts:179](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L179)* - -___ - -### CallDataSize - -• **CallDataSize**: = "CALLDATASIZE" - -*Defined in [ethereum-types/src/index.ts:180](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L180)* - -___ - -### CallValue - -• **CallValue**: = "CALLVALUE" - -*Defined in [ethereum-types/src/index.ts:178](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L178)* - -___ - -### Caller - -• **Caller**: = "CALLER" - -*Defined in [ethereum-types/src/index.ts:177](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L177)* - -___ - -### CodeCopy - -• **CodeCopy**: = "CODECOPY" - -*Defined in [ethereum-types/src/index.ts:183](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L183)* - -___ - -### CodeSize - -• **CodeSize**: = "CODESIZE" - -*Defined in [ethereum-types/src/index.ts:182](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L182)* - -___ - -### Coinbase - -• **Coinbase**: = "COINBASE" - -*Defined in [ethereum-types/src/index.ts:191](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L191)* - -___ - -### Create - -• **Create**: = "CREATE" - -*Defined in [ethereum-types/src/index.ts:282](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L282)* - -___ - -### DelegateCall - -• **DelegateCall**: = "DELEGATECALL" - -*Defined in [ethereum-types/src/index.ts:286](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L286)* - -___ - -### Difficulty - -• **Difficulty**: = "DIFFICULTY" - -*Defined in [ethereum-types/src/index.ts:194](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L194)* - -___ - -### Div - -• **Div**: = "DIV" - -*Defined in [ethereum-types/src/index.ts:151](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L151)* - -___ - -### Dup1 - -• **Dup1**: = "DUP1" - -*Defined in [ethereum-types/src/index.ts:243](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L243)* - -___ - -### Dup10 - -• **Dup10**: = "DUP10" - -*Defined in [ethereum-types/src/index.ts:252](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L252)* - -___ - -### Dup11 - -• **Dup11**: = "DUP11" - -*Defined in [ethereum-types/src/index.ts:253](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L253)* - -___ - -### Dup12 - -• **Dup12**: = "DUP12" - -*Defined in [ethereum-types/src/index.ts:254](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L254)* - -___ - -### Dup13 - -• **Dup13**: = "DUP13" - -*Defined in [ethereum-types/src/index.ts:255](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L255)* - -___ - -### Dup14 - -• **Dup14**: = "DUP14" - -*Defined in [ethereum-types/src/index.ts:256](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L256)* - -___ - -### Dup15 - -• **Dup15**: = "DUP15" - -*Defined in [ethereum-types/src/index.ts:257](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L257)* - -___ - -### Dup16 - -• **Dup16**: = "DUP16" - -*Defined in [ethereum-types/src/index.ts:258](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L258)* - -___ - -### Dup2 - -• **Dup2**: = "DUP2" - -*Defined in [ethereum-types/src/index.ts:244](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L244)* - -___ - -### Dup3 - -• **Dup3**: = "DUP3" - -*Defined in [ethereum-types/src/index.ts:245](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L245)* - -___ - -### Dup4 - -• **Dup4**: = "DUP4" - -*Defined in [ethereum-types/src/index.ts:246](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L246)* - -___ - -### Dup5 - -• **Dup5**: = "DUP5" - -*Defined in [ethereum-types/src/index.ts:247](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L247)* - -___ - -### Dup6 - -• **Dup6**: = "DUP6" - -*Defined in [ethereum-types/src/index.ts:248](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L248)* - -___ - -### Dup7 - -• **Dup7**: = "DUP7" - -*Defined in [ethereum-types/src/index.ts:249](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L249)* - -___ - -### Dup8 - -• **Dup8**: = "DUP8" - -*Defined in [ethereum-types/src/index.ts:250](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L250)* - -___ - -### Dup9 - -• **Dup9**: = "DUP9" - -*Defined in [ethereum-types/src/index.ts:251](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L251)* - -___ - -### Eq - -• **Eq**: = "EQ" - -*Defined in [ethereum-types/src/index.ts:164](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L164)* - -___ - -### Exp - -• **Exp**: = "EXP" - -*Defined in [ethereum-types/src/index.ts:157](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L157)* - -___ - -### ExtCodeCopy - -• **ExtCodeCopy**: = "EXTCODECOPY" - -*Defined in [ethereum-types/src/index.ts:186](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L186)* - -___ - -### ExtCodeSize - -• **ExtCodeSize**: = "EXTCODESIZE" - -*Defined in [ethereum-types/src/index.ts:185](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L185)* - -___ - -### Gas - -• **Gas**: = "GAS" - -*Defined in [ethereum-types/src/index.ts:207](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L207)* - -___ - -### GasPrice - -• **GasPrice**: = "GASPRICE" - -*Defined in [ethereum-types/src/index.ts:184](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L184)* - -___ - -### Gaslimit - -• **Gaslimit**: = "GASLIMIT" - -*Defined in [ethereum-types/src/index.ts:195](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L195)* - -___ - -### Gt - -• **Gt**: = "GT" - -*Defined in [ethereum-types/src/index.ts:161](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L161)* - -___ - -### Invalid - -• **Invalid**: = "INVALID" - -*Defined in [ethereum-types/src/index.ts:289](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L289)* - -___ - -### IsZero - -• **IsZero**: = "ISZERO" - -*Defined in [ethereum-types/src/index.ts:165](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L165)* - -___ - -### Jump - -• **Jump**: = "JUMP" - -*Defined in [ethereum-types/src/index.ts:203](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L203)* - -___ - -### JumpDest - -• **JumpDest**: = "JUMPDEST" - -*Defined in [ethereum-types/src/index.ts:208](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L208)* - -___ - -### Jumpi - -• **Jumpi**: = "JUMPI" - -*Defined in [ethereum-types/src/index.ts:204](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L204)* - -___ - -### Log1 - -• **Log1**: = "LOG1" - -*Defined in [ethereum-types/src/index.ts:277](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L277)* - -___ - -### Log2 - -• **Log2**: = "LOG2" - -*Defined in [ethereum-types/src/index.ts:278](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L278)* - -___ - -### Log3 - -• **Log3**: = "LOG3" - -*Defined in [ethereum-types/src/index.ts:279](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L279)* - -___ - -### Log4 - -• **Log4**: = "LOG4" - -*Defined in [ethereum-types/src/index.ts:280](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L280)* - -___ - -### Lt - -• **Lt**: = "LT" - -*Defined in [ethereum-types/src/index.ts:160](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L160)* - -___ - -### MLoad - -• **MLoad**: = "MLOAD" - -*Defined in [ethereum-types/src/index.ts:198](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L198)* - -___ - -### MSize - -• **MSize**: = "MSIZE" - -*Defined in [ethereum-types/src/index.ts:206](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L206)* - -___ - -### MStore - -• **MStore**: = "MSTORE" - -*Defined in [ethereum-types/src/index.ts:199](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L199)* - -___ - -### MStore8 - -• **MStore8**: = "MSTORE8" - -*Defined in [ethereum-types/src/index.ts:200](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L200)* - -___ - -### Mod - -• **Mod**: = "MOD" - -*Defined in [ethereum-types/src/index.ts:153](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L153)* - -___ - -### Mul - -• **Mul**: = "MUL" - -*Defined in [ethereum-types/src/index.ts:149](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L149)* - -___ - -### MulMod - -• **MulMod**: = "MULMOD" - -*Defined in [ethereum-types/src/index.ts:156](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L156)* - -___ - -### Not - -• **Not**: = "NOT" - -*Defined in [ethereum-types/src/index.ts:169](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L169)* - -___ - -### Number - -• **Number**: = "NUMBER" - -*Defined in [ethereum-types/src/index.ts:193](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L193)* - -___ - -### Or - -• **Or**: = "OR" - -*Defined in [ethereum-types/src/index.ts:167](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L167)* - -___ - -### Origin - -• **Origin**: = "ORIGIN" - -*Defined in [ethereum-types/src/index.ts:176](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L176)* - -___ - -### Pc - -• **Pc**: = "PC" - -*Defined in [ethereum-types/src/index.ts:205](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L205)* - -___ - -### Pop - -• **Pop**: = "POP" - -*Defined in [ethereum-types/src/index.ts:197](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L197)* - -___ - -### Push1 - -• **Push1**: = "PUSH1" - -*Defined in [ethereum-types/src/index.ts:210](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L210)* - -___ - -### Push10 - -• **Push10**: = "PUSH10" - -*Defined in [ethereum-types/src/index.ts:219](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L219)* - -___ - -### Push11 - -• **Push11**: = "PUSH11" - -*Defined in [ethereum-types/src/index.ts:220](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L220)* - -___ - -### Push12 - -• **Push12**: = "PUSH12" - -*Defined in [ethereum-types/src/index.ts:221](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L221)* - -___ - -### Push13 - -• **Push13**: = "PUSH13" - -*Defined in [ethereum-types/src/index.ts:222](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L222)* - -___ - -### Push14 - -• **Push14**: = "PUSH14" - -*Defined in [ethereum-types/src/index.ts:223](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L223)* - -___ - -### Push15 - -• **Push15**: = "PUSH15" - -*Defined in [ethereum-types/src/index.ts:224](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L224)* - -___ - -### Push16 - -• **Push16**: = "PUSH16" - -*Defined in [ethereum-types/src/index.ts:225](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L225)* - -___ - -### Push17 - -• **Push17**: = "PUSH17" - -*Defined in [ethereum-types/src/index.ts:226](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L226)* - -___ - -### Push18 - -• **Push18**: = "PUSH18" - -*Defined in [ethereum-types/src/index.ts:227](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L227)* - -___ - -### Push19 - -• **Push19**: = "PUSH19" - -*Defined in [ethereum-types/src/index.ts:228](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L228)* - -___ - -### Push2 - -• **Push2**: = "PUSH2" - -*Defined in [ethereum-types/src/index.ts:211](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L211)* - -___ - -### Push20 - -• **Push20**: = "PUSH20" - -*Defined in [ethereum-types/src/index.ts:229](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L229)* - -___ - -### Push21 - -• **Push21**: = "PUSH21" - -*Defined in [ethereum-types/src/index.ts:230](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L230)* - -___ - -### Push22 - -• **Push22**: = "PUSH22" - -*Defined in [ethereum-types/src/index.ts:231](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L231)* - -___ - -### Push23 - -• **Push23**: = "PUSH23" - -*Defined in [ethereum-types/src/index.ts:232](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L232)* - -___ - -### Push24 - -• **Push24**: = "PUSH24" - -*Defined in [ethereum-types/src/index.ts:233](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L233)* - -___ - -### Push25 - -• **Push25**: = "PUSH25" - -*Defined in [ethereum-types/src/index.ts:234](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L234)* - -___ - -### Push26 - -• **Push26**: = "PUSH26" - -*Defined in [ethereum-types/src/index.ts:235](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L235)* - -___ - -### Push27 - -• **Push27**: = "PUSH27" - -*Defined in [ethereum-types/src/index.ts:236](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L236)* - -___ - -### Push28 - -• **Push28**: = "PUSH28" - -*Defined in [ethereum-types/src/index.ts:237](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L237)* - -___ - -### Push29 - -• **Push29**: = "PUSH29" - -*Defined in [ethereum-types/src/index.ts:238](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L238)* - -___ - -### Push3 - -• **Push3**: = "PUSH3" - -*Defined in [ethereum-types/src/index.ts:212](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L212)* - -___ - -### Push30 - -• **Push30**: = "PUSH30" - -*Defined in [ethereum-types/src/index.ts:239](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L239)* - -___ - -### Push31 - -• **Push31**: = "PUSH31" - -*Defined in [ethereum-types/src/index.ts:240](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L240)* - -___ - -### Push32 - -• **Push32**: = "PUSH32" - -*Defined in [ethereum-types/src/index.ts:241](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L241)* - -___ - -### Push4 - -• **Push4**: = "PUSH4" - -*Defined in [ethereum-types/src/index.ts:213](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L213)* - -___ - -### Push5 - -• **Push5**: = "PUSH5" - -*Defined in [ethereum-types/src/index.ts:214](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L214)* - -___ - -### Push6 - -• **Push6**: = "PUSH6" - -*Defined in [ethereum-types/src/index.ts:215](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L215)* - -___ - -### Push7 - -• **Push7**: = "PUSH7" - -*Defined in [ethereum-types/src/index.ts:216](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L216)* - -___ - -### Push8 - -• **Push8**: = "PUSH8" - -*Defined in [ethereum-types/src/index.ts:217](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L217)* - -___ - -### Push9 - -• **Push9**: = "PUSH9" - -*Defined in [ethereum-types/src/index.ts:218](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L218)* - -___ - -### Return - -• **Return**: = "RETURN" - -*Defined in [ethereum-types/src/index.ts:285](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L285)* - -___ - -### ReturnDataCopy - -• **ReturnDataCopy**: = "RETURNDATACOPY" - -*Defined in [ethereum-types/src/index.ts:188](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L188)* - -___ - -### ReturnDataSize - -• **ReturnDataSize**: = "RETURNDATASIZE" - -*Defined in [ethereum-types/src/index.ts:187](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L187)* - -___ - -### Revert - -• **Revert**: = "REVERT" - -*Defined in [ethereum-types/src/index.ts:288](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L288)* - -___ - -### SDiv - -• **SDiv**: = "SDIV" - -*Defined in [ethereum-types/src/index.ts:152](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L152)* - -___ - -### SGt - -• **SGt**: = "SGT" - -*Defined in [ethereum-types/src/index.ts:163](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L163)* - -___ - -### SLoad - -• **SLoad**: = "SLOAD" - -*Defined in [ethereum-types/src/index.ts:201](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L201)* - -___ - -### SLt - -• **SLt**: = "SLT" - -*Defined in [ethereum-types/src/index.ts:162](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L162)* - -___ - -### SMod - -• **SMod**: = "SMOD" - -*Defined in [ethereum-types/src/index.ts:154](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L154)* - -___ - -### SStore - -• **SStore**: = "SSTORE" - -*Defined in [ethereum-types/src/index.ts:202](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L202)* - -___ - -### SelfDestruct - -• **SelfDestruct**: = "SELFDESTRUCT" - -*Defined in [ethereum-types/src/index.ts:290](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L290)* - -___ - -### Sha3 - -• **Sha3**: = "SHA3" - -*Defined in [ethereum-types/src/index.ts:172](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L172)* - -___ - -### SignExtend - -• **SignExtend**: = "SIGNEXTEND" - -*Defined in [ethereum-types/src/index.ts:158](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L158)* - -___ - -### StaticCall - -• **StaticCall**: = "STATICCALL" - -*Defined in [ethereum-types/src/index.ts:287](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L287)* - -___ - -### Stop - -• **Stop**: = "STOP" - -*Defined in [ethereum-types/src/index.ts:147](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L147)* - -___ - -### Sub - -• **Sub**: = "SUB" - -*Defined in [ethereum-types/src/index.ts:150](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L150)* - -___ - -### Swap1 - -• **Swap1**: = "SWAP1" - -*Defined in [ethereum-types/src/index.ts:260](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L260)* - -___ - -### Swap10 - -• **Swap10**: = "SWAP10" - -*Defined in [ethereum-types/src/index.ts:269](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L269)* - -___ - -### Swap11 - -• **Swap11**: = "SWAP11" - -*Defined in [ethereum-types/src/index.ts:270](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L270)* - -___ - -### Swap12 - -• **Swap12**: = "SWAP12" - -*Defined in [ethereum-types/src/index.ts:271](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L271)* - -___ - -### Swap13 - -• **Swap13**: = "SWAP13" - -*Defined in [ethereum-types/src/index.ts:272](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L272)* - -___ - -### Swap14 - -• **Swap14**: = "SWAP14" - -*Defined in [ethereum-types/src/index.ts:273](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L273)* - -___ - -### Swap15 - -• **Swap15**: = "SWAP15" - -*Defined in [ethereum-types/src/index.ts:274](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L274)* - -___ - -### Swap16 - -• **Swap16**: = "SWAP16" - -*Defined in [ethereum-types/src/index.ts:275](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L275)* - -___ - -### Swap2 - -• **Swap2**: = "SWAP2" - -*Defined in [ethereum-types/src/index.ts:261](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L261)* - -___ - -### Swap3 - -• **Swap3**: = "SWAP3" - -*Defined in [ethereum-types/src/index.ts:262](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L262)* - -___ - -### Swap4 - -• **Swap4**: = "SWAP4" - -*Defined in [ethereum-types/src/index.ts:263](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L263)* - -___ - -### Swap5 - -• **Swap5**: = "SWAP5" - -*Defined in [ethereum-types/src/index.ts:264](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L264)* - -___ - -### Swap6 - -• **Swap6**: = "SWAP6" - -*Defined in [ethereum-types/src/index.ts:265](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L265)* - -___ - -### Swap7 - -• **Swap7**: = "SWAP7" - -*Defined in [ethereum-types/src/index.ts:266](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L266)* - -___ - -### Swap8 - -• **Swap8**: = "SWAP8" - -*Defined in [ethereum-types/src/index.ts:267](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L267)* - -___ - -### Swap9 - -• **Swap9**: = "SWAP9" - -*Defined in [ethereum-types/src/index.ts:268](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L268)* - -___ - -### TimeStamp - -• **TimeStamp**: = "TimeStamp" - -*Defined in [ethereum-types/src/index.ts:192](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L192)* - -___ - -### Xor - -• **Xor**: = "XOR" - -*Defined in [ethereum-types/src/index.ts:168](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L168)* - -
- - - -# Enumeration: NodeType - - -## Enumeration members - -### Ganache - -• **Ganache**: = "GANACHE" - -*Defined in [web3-wrapper/src/types.ts:91](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L91)* - -___ - -### Geth - -• **Geth**: = "GETH" - -*Defined in [web3-wrapper/src/types.ts:90](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L90)* - -
- -# Enumeration: Web3WrapperErrors - - -## Enumeration members - -### TransactionMiningTimeout - -• **TransactionMiningTimeout**: = "TRANSACTION_MINING_TIMEOUT" - -*Defined in [web3-wrapper/src/types.ts:2](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L2)* - -
- - - -
- - - - - -# Interface: BlockWithoutTransactionData - - -## Properties - -### difficulty - -• **difficulty**: *`BigNumber`* - -*Inherited from [AbstractBlock](#interface-abstractblock).[difficulty](#difficulty)* - -*Defined in [ethereum-types/src/index.ts:357](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L357)* - -___ - -### extraData - -• **extraData**: *string* - -*Inherited from [AbstractBlock](#interface-abstractblock).[extraData](#extradata)* - -*Defined in [ethereum-types/src/index.ts:359](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L359)* - -___ - -### gasLimit - -• **gasLimit**: *number* - -*Inherited from [AbstractBlock](#interface-abstractblock).[gasLimit](#gaslimit)* - -*Defined in [ethereum-types/src/index.ts:361](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L361)* - -___ - -### gasUsed - -• **gasUsed**: *number* - -*Inherited from [AbstractBlock](#interface-abstractblock).[gasUsed](#gasused)* - -*Defined in [ethereum-types/src/index.ts:362](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L362)* - -___ - -### hash - -• **hash**: *string | null* - -*Inherited from [AbstractBlock](#interface-abstractblock).[hash](#hash)* - -*Defined in [ethereum-types/src/index.ts:349](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L349)* - -___ - -### logsBloom - -• **logsBloom**: *string | null* - -*Inherited from [AbstractBlock](#interface-abstractblock).[logsBloom](#logsbloom)* - -*Defined in [ethereum-types/src/index.ts:353](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L353)* - -___ - -### miner - -• **miner**: *string* - -*Inherited from [AbstractBlock](#interface-abstractblock).[miner](#miner)* - -*Defined in [ethereum-types/src/index.ts:356](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L356)* - -___ - -### nonce - -• **nonce**: *string | null* - -*Inherited from [AbstractBlock](#interface-abstractblock).[nonce](#nonce)* - -*Defined in [ethereum-types/src/index.ts:351](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L351)* - -___ - -### number - -• **number**: *number | null* - -*Inherited from [AbstractBlock](#interface-abstractblock).[number](#number)* - -*Defined in [ethereum-types/src/index.ts:348](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L348)* - -___ - -### parentHash - -• **parentHash**: *string* - -*Inherited from [AbstractBlock](#interface-abstractblock).[parentHash](#parenthash)* - -*Defined in [ethereum-types/src/index.ts:350](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L350)* - -___ - -### sha3Uncles - -• **sha3Uncles**: *string* - -*Inherited from [AbstractBlock](#interface-abstractblock).[sha3Uncles](#sha3uncles)* - -*Defined in [ethereum-types/src/index.ts:352](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L352)* - -___ - -### size - -• **size**: *number* - -*Inherited from [AbstractBlock](#interface-abstractblock).[size](#size)* - -*Defined in [ethereum-types/src/index.ts:360](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L360)* - -___ - -### stateRoot - -• **stateRoot**: *string* - -*Inherited from [AbstractBlock](#interface-abstractblock).[stateRoot](#stateroot)* - -*Defined in [ethereum-types/src/index.ts:355](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L355)* - -___ - -### timestamp - -• **timestamp**: *number* - -*Inherited from [AbstractBlock](#interface-abstractblock).[timestamp](#timestamp)* - -*Defined in [ethereum-types/src/index.ts:363](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L363)* - -___ - -### totalDifficulty - -• **totalDifficulty**: *`BigNumber`* - -*Inherited from [AbstractBlock](#interface-abstractblock).[totalDifficulty](#totaldifficulty)* - -*Defined in [ethereum-types/src/index.ts:358](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L358)* - -___ - -### transactions - -• **transactions**: *string[]* - -*Defined in [ethereum-types/src/index.ts:368](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L368)* - -___ - -### transactionsRoot - -• **transactionsRoot**: *string* - -*Inherited from [AbstractBlock](#interface-abstractblock).[transactionsRoot](#transactionsroot)* - -*Defined in [ethereum-types/src/index.ts:354](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L354)* - -___ - -### uncles - -• **uncles**: *string[]* - -*Inherited from [AbstractBlock](#interface-abstractblock).[uncles](#uncles)* - -*Defined in [ethereum-types/src/index.ts:364](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L364)* - -
- -# Interface: BlockWithTransactionData - - -## Properties - -### difficulty - -• **difficulty**: *`BigNumber`* - -*Inherited from [AbstractBlock](#interface-abstractblock).[difficulty](#difficulty)* - -*Defined in [ethereum-types/src/index.ts:357](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L357)* - -___ - -### extraData - -• **extraData**: *string* - -*Inherited from [AbstractBlock](#interface-abstractblock).[extraData](#extradata)* - -*Defined in [ethereum-types/src/index.ts:359](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L359)* - -___ - -### gasLimit - -• **gasLimit**: *number* - -*Inherited from [AbstractBlock](#interface-abstractblock).[gasLimit](#gaslimit)* - -*Defined in [ethereum-types/src/index.ts:361](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L361)* - -___ - -### gasUsed - -• **gasUsed**: *number* - -*Inherited from [AbstractBlock](#interface-abstractblock).[gasUsed](#gasused)* - -*Defined in [ethereum-types/src/index.ts:362](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L362)* - -___ - -### hash - -• **hash**: *string | null* - -*Inherited from [AbstractBlock](#interface-abstractblock).[hash](#hash)* - -*Defined in [ethereum-types/src/index.ts:349](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L349)* - -___ - -### logsBloom - -• **logsBloom**: *string | null* - -*Inherited from [AbstractBlock](#interface-abstractblock).[logsBloom](#logsbloom)* - -*Defined in [ethereum-types/src/index.ts:353](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L353)* - -___ - -### miner - -• **miner**: *string* - -*Inherited from [AbstractBlock](#interface-abstractblock).[miner](#miner)* - -*Defined in [ethereum-types/src/index.ts:356](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L356)* - -___ - -### nonce - -• **nonce**: *string | null* - -*Inherited from [AbstractBlock](#interface-abstractblock).[nonce](#nonce)* - -*Defined in [ethereum-types/src/index.ts:351](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L351)* - -___ - -### number - -• **number**: *number | null* - -*Inherited from [AbstractBlock](#interface-abstractblock).[number](#number)* - -*Defined in [ethereum-types/src/index.ts:348](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L348)* - -___ - -### parentHash - -• **parentHash**: *string* - -*Inherited from [AbstractBlock](#interface-abstractblock).[parentHash](#parenthash)* - -*Defined in [ethereum-types/src/index.ts:350](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L350)* - -___ - -### sha3Uncles - -• **sha3Uncles**: *string* - -*Inherited from [AbstractBlock](#interface-abstractblock).[sha3Uncles](#sha3uncles)* - -*Defined in [ethereum-types/src/index.ts:352](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L352)* - -___ - -### size - -• **size**: *number* - -*Inherited from [AbstractBlock](#interface-abstractblock).[size](#size)* - -*Defined in [ethereum-types/src/index.ts:360](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L360)* - -___ - -### stateRoot - -• **stateRoot**: *string* - -*Inherited from [AbstractBlock](#interface-abstractblock).[stateRoot](#stateroot)* - -*Defined in [ethereum-types/src/index.ts:355](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L355)* - -___ - -### timestamp - -• **timestamp**: *number* - -*Inherited from [AbstractBlock](#interface-abstractblock).[timestamp](#timestamp)* - -*Defined in [ethereum-types/src/index.ts:363](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L363)* - -___ - -### totalDifficulty - -• **totalDifficulty**: *`BigNumber`* - -*Inherited from [AbstractBlock](#interface-abstractblock).[totalDifficulty](#totaldifficulty)* - -*Defined in [ethereum-types/src/index.ts:358](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L358)* - -___ - -### transactions - -• **transactions**: *[Transaction](#class-transaction)[]* - -*Defined in [ethereum-types/src/index.ts:372](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L372)* - -___ - -### transactionsRoot - -• **transactionsRoot**: *string* - -*Inherited from [AbstractBlock](#interface-abstractblock).[transactionsRoot](#transactionsroot)* - -*Defined in [ethereum-types/src/index.ts:354](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L354)* - -___ - -### uncles - -• **uncles**: *string[]* - -*Inherited from [AbstractBlock](#interface-abstractblock).[uncles](#uncles)* - -*Defined in [ethereum-types/src/index.ts:364](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L364)* - -
- -# Interface: CallData - - -## Properties - -### `Optional` data - -• **data**? : *undefined | string* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[data](#optional-data)* - -*Defined in [ethereum-types/src/index.ts:394](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L394)* - -___ - -### `Optional` from - -• **from**? : *undefined | string* - -*Defined in [ethereum-types/src/index.ts:403](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L403)* - -___ - -### `Optional` gas - -• **gas**? : *number | string | `BigNumber`* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[gas](#optional-gas)* - -*Defined in [ethereum-types/src/index.ts:392](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L392)* - -___ - -### `Optional` gasPrice - -• **gasPrice**? : *number | string | `BigNumber`* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[gasPrice](#optional-gasprice)* - -*Defined in [ethereum-types/src/index.ts:393](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L393)* - -___ - -### `Optional` nonce - -• **nonce**? : *undefined | number* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[nonce](#optional-nonce)* - -*Defined in [ethereum-types/src/index.ts:395](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L395)* - -___ - -### `Optional` to - -• **to**? : *undefined | string* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[to](#optional-to)* - -*Defined in [ethereum-types/src/index.ts:390](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L390)* - -___ - -### `Optional` value - -• **value**? : *number | string | `BigNumber`* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[value](#optional-value)* - -*Defined in [ethereum-types/src/index.ts:391](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L391)* - -
- - - - - - - - - - - -# Interface: ConstructorAbi - - -## Properties - -### inputs - -• **inputs**: *[DataItem](#class-dataitem)[]* - -*Defined in [ethereum-types/src/index.ts:103](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L103)* - -___ - -### payable - -• **payable**: *boolean* - -*Defined in [ethereum-types/src/index.ts:104](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L104)* - -___ - -### stateMutability - -• **stateMutability**: *[ConstructorStateMutability](#constructorstatemutability)* - -*Defined in [ethereum-types/src/index.ts:105](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L105)* - -___ - -### type - -• **type**: *string* - -*Defined in [ethereum-types/src/index.ts:102](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L102)* - -
- - - - - - - -# Interface: DataItem - - -## Properties - -### `Optional` components - -• **components**? : *[DataItem](#class-dataitem)[]* - -*Defined in [ethereum-types/src/index.ts:138](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L138)* - -___ - -### `Optional` internalType - -• **internalType**? : *undefined | string* - -*Defined in [ethereum-types/src/index.ts:137](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L137)* - -___ - -### name - -• **name**: *string* - -*Defined in [ethereum-types/src/index.ts:135](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L135)* - -___ - -### type - -• **type**: *string* - -*Defined in [ethereum-types/src/index.ts:136](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L136)* - -
- -# Interface: DecodedLogArgs - - -## Type parameters - -▪ **A** - - -## Properties - -### address - -• **address**: *string* - -*Inherited from [LogEntry](#interface-logentry).[address](#address)* - -*Defined in [ethereum-types/src/index.ts:435](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L435)* - -___ - -### args - -• **args**: *`A`* - -*Defined in [ethereum-types/src/index.ts:418](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L418)* - -___ - -### blockHash - -• **blockHash**: *string | null* - -*Inherited from [LogEntry](#interface-logentry).[blockHash](#blockhash)* - -*Defined in [ethereum-types/src/index.ts:433](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L433)* - -___ - -### blockNumber - -• **blockNumber**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[blockNumber](#blocknumber)* - -*Defined in [ethereum-types/src/index.ts:434](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L434)* - -___ - -### data - -• **data**: *string* - -*Inherited from [LogEntry](#interface-logentry).[data](#data)* - -*Defined in [ethereum-types/src/index.ts:436](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L436)* - -___ - -### event - -• **event**: *string* - -*Defined in [ethereum-types/src/index.ts:417](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L417)* - -___ - -### logIndex - -• **logIndex**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[logIndex](#logindex)* - -*Defined in [ethereum-types/src/index.ts:430](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L430)* - -___ - -### topics - -• **topics**: *string[]* - -*Inherited from [LogEntry](#interface-logentry).[topics](#topics)* - -*Defined in [ethereum-types/src/index.ts:437](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L437)* - -___ - -### transactionHash - -• **transactionHash**: *string* - -*Inherited from [LogEntry](#interface-logentry).[transactionHash](#transactionhash)* - -*Defined in [ethereum-types/src/index.ts:432](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L432)* - -___ - -### transactionIndex - -• **transactionIndex**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[transactionIndex](#transactionindex)* - -*Defined in [ethereum-types/src/index.ts:431](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L431)* - -
- -# Interface: DecodedLogEntryEvent <**A**> - -## Type parameters - -▪ **A** - - -## Properties - -### address - -• **address**: *string* - -*Inherited from [LogEntry](#interface-logentry).[address](#address)* - -*Defined in [ethereum-types/src/index.ts:435](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L435)* - -___ - -### args - -• **args**: *`A`* - -*Inherited from [DecodedLogEntry](#interface-decodedlogentry).[args](#args)* - -*Defined in [ethereum-types/src/index.ts:418](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L418)* - -___ - -### blockHash - -• **blockHash**: *string | null* - -*Inherited from [LogEntry](#interface-logentry).[blockHash](#blockhash)* - -*Defined in [ethereum-types/src/index.ts:433](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L433)* - -___ - -### blockNumber - -• **blockNumber**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[blockNumber](#blocknumber)* - -*Defined in [ethereum-types/src/index.ts:434](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L434)* - -___ - -### data - -• **data**: *string* - -*Inherited from [LogEntry](#interface-logentry).[data](#data)* - -*Defined in [ethereum-types/src/index.ts:436](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L436)* - -___ - -### event - -• **event**: *string* - -*Inherited from [DecodedLogEntry](#interface-decodedlogentry).[event](#event)* - -*Defined in [ethereum-types/src/index.ts:417](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L417)* - -___ - -### logIndex - -• **logIndex**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[logIndex](#logindex)* - -*Defined in [ethereum-types/src/index.ts:430](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L430)* - -___ - -### removed - -• **removed**: *boolean* - -*Defined in [ethereum-types/src/index.ts:422](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L422)* - -___ - -### topics - -• **topics**: *string[]* - -*Inherited from [LogEntry](#interface-logentry).[topics](#topics)* - -*Defined in [ethereum-types/src/index.ts:437](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L437)* - -___ - -### transactionHash - -• **transactionHash**: *string* - -*Inherited from [LogEntry](#interface-logentry).[transactionHash](#transactionhash)* - -*Defined in [ethereum-types/src/index.ts:432](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L432)* - -___ - -### transactionIndex - -• **transactionIndex**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[transactionIndex](#transactionindex)* - -*Defined in [ethereum-types/src/index.ts:431](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L431)* - -
- - - -# Interface: EIP1193Provider - - -## Properties - -### isEIP1193 - -• **isEIP1193**: *boolean* - -*Defined in [ethereum-types/src/index.ts:73](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L73)* - -## Methods - -### on - -▸ **on**(`event`: [EIP1193Event](#eip1193event), `listener`: function): *this* - -*Defined in [ethereum-types/src/index.ts:75](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L75)* - -**Parameters:** - -▪ **event**: *[EIP1193Event](#eip1193event)* - -▪ **listener**: *function* - -▸ (`result`: any): *void* - -**Parameters:** - -Name | Type | ------- | ------ | -`result` | any | - -**Returns:** *this* - -___ - -### send - -▸ **send**(`method`: string, `params?`: any[]): *`Promise`* - -*Defined in [ethereum-types/src/index.ts:74](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L74)* - -**Parameters:** - -Name | Type | ------- | ------ | -`method` | string | -`params?` | any[] | - -**Returns:** *`Promise`* - -
- -# Interface: EventAbi - - -## Properties - -### anonymous - -• **anonymous**: *boolean* - -*Defined in [ethereum-types/src/index.ts:131](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L131)* - -___ - -### inputs - -• **inputs**: *[EventParameter](#class-eventparameter)[]* - -*Defined in [ethereum-types/src/index.ts:130](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L130)* - -___ - -### name - -• **name**: *string* - -*Defined in [ethereum-types/src/index.ts:129](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L129)* - -___ - -### type - -• **type**: *string* - -*Defined in [ethereum-types/src/index.ts:128](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L128)* - -
- -# Interface: EventParameter - - -## Properties - -### `Optional` components - -• **components**? : *[DataItem](#class-dataitem)[]* - -*Inherited from [DataItem](#interface-dataitem).[components](#optional-components)* - -*Defined in [ethereum-types/src/index.ts:138](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L138)* - -___ - -### indexed - -• **indexed**: *boolean* - -*Defined in [ethereum-types/src/index.ts:116](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L116)* - -___ - -### `Optional` internalType - -• **internalType**? : *undefined | string* - -*Inherited from [DataItem](#interface-dataitem).[internalType](#optional-internaltype)* - -*Defined in [ethereum-types/src/index.ts:137](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L137)* - -___ - -### name - -• **name**: *string* - -*Inherited from [DataItem](#interface-dataitem).[name](#name)* - -*Defined in [ethereum-types/src/index.ts:135](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L135)* - -___ - -### type - -• **type**: *string* - -*Inherited from [DataItem](#interface-dataitem).[type](#type)* - -*Defined in [ethereum-types/src/index.ts:136](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L136)* - -
- - - - - -# Interface: FallbackAbi - - -## Properties - -### payable - -• **payable**: *boolean* - -*Defined in [ethereum-types/src/index.ts:112](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L112)* - -___ - -### type - -• **type**: *string* - -*Defined in [ethereum-types/src/index.ts:111](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L111)* - -
- -# Interface: FilterObject - - -## Properties - -### `Optional` address - -• **address**? : *undefined | string* - -*Defined in [ethereum-types/src/index.ts:410](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L410)* - -___ - -### `Optional` blockHash - -• **blockHash**? : *undefined | string* - -*Defined in [ethereum-types/src/index.ts:409](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L409)* - -___ - -### `Optional` fromBlock - -• **fromBlock**? : *number | string* - -*Defined in [ethereum-types/src/index.ts:407](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L407)* - -___ - -### `Optional` toBlock - -• **toBlock**? : *number | string* - -*Defined in [ethereum-types/src/index.ts:408](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L408)* - -___ - -### `Optional` topics - -• **topics**? : *[LogTopic](#logtopic)[]* - -*Defined in [ethereum-types/src/index.ts:411](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L411)* - -
- -# Interface: GanacheProvider - - -## Methods - -### sendAsync - -▸ **sendAsync**(`payload`: [JSONRPCRequestPayload](_ethereum_types_src_index_.jsonrpcrequestpayload.md), `callback`: [JSONRPCErrorCallback](#jsonrpcerrorcallback)): *void* - -*Defined in [ethereum-types/src/index.ts:14](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L14)* - -**Parameters:** - -Name | Type | ------- | ------ | -`payload` | [JSONRPCRequestPayload](#class-jsonrpcrequestpayload) | -`callback` | [JSONRPCErrorCallback](#jsonrpcerrorcallback) | - -**Returns:** *void* - -
- - - -# Interface: JSONRPCRequestPayload - - -## Properties - -### id - -• **id**: *number* - -*Defined in [ethereum-types/src/index.ts:331](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L331)* - -___ - -### jsonrpc - -• **jsonrpc**: *string* - -*Defined in [ethereum-types/src/index.ts:332](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L332)* - -___ - -### method - -• **method**: *string* - -*Defined in [ethereum-types/src/index.ts:330](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L330)* - -___ - -### params - -• **params**: *any[]* - -*Defined in [ethereum-types/src/index.ts:329](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L329)* - -
- -# Interface: JSONRPCResponseError - - -## Properties - -### code - -• **code**: *number* - -*Defined in [ethereum-types/src/index.ts:337](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L337)* - -___ - -### message - -• **message**: *string* - -*Defined in [ethereum-types/src/index.ts:336](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L336)* - -
- -# Class: AbiDecoder - -AbiDecoder allows you to decode event logs given a set of supplied contract ABI's. It takes the contract's event -signature from the ABI and attempts to decode the logs using it. - - -## Constructors - - - -\+ **new AbiDecoder**(`abiArrays`: [AbiDefinition](#abidefinition)[][]): *[AbiDecoder](#class-abidecoder)* - -*Defined in [utils/src/abi_decoder.ts:42](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/utils/src/abi_decoder.ts#L42)* - -Instantiate an AbiDecoder - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`abiArrays` | [AbiDefinition](#abidefinition)[][] | An array of contract ABI's | - -**Returns:** *[AbiDecoder](#class-abidecoder)* - -AbiDecoder instance - -## Methods - -### addABI - -▸ **addABI**(`abiArray`: [AbiDefinition](#abidefinition)[], `contractName?`: undefined | string): *void* - -*Defined in [utils/src/abi_decoder.ts:158](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/utils/src/abi_decoder.ts#L158)* - -Adds a set of ABI definitions, after which calldata and logs targeting these ABI's can be decoded. -Additional properties can be included to disambiguate similar ABI's. For example, if two functions -have the same signature but different parameter names, then their ABI definitions can be disambiguated -by specifying a contract name. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`abiArray` | [AbiDefinition](#abidefinition)[] | - | -`contractName?` | undefined \| string | Name of contract that encapsulates the ABI definitions (optional). This can be used when decoding calldata to disambiguate methods with the same signature but different parameter names. | - -**Returns:** *void* - -___ - -### decodeCalldataOrThrow - -▸ **decodeCalldataOrThrow**(`calldata`: string, `contractName?`: undefined | string): *`DecodedCalldata`* - -*Defined in [utils/src/abi_decoder.ts:118](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/utils/src/abi_decoder.ts#L118)* - -Decodes calldata for a known ABI. - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`calldata` | string | hex-encoded calldata. | -`contractName?` | undefined \| string | used to disambiguate similar ABI's (optional). | - -**Returns:** *`DecodedCalldata`* - -Decoded calldata. Includes: function name and signature, along with the decoded arguments. - -___ - -### tryToDecodeLogOrNoop - -▸ **tryToDecodeLogOrNoop**<**ArgsType**>(`log`: `LogEntry`): *`LogWithDecodedArgs` | [RawLog](#rawlog)* - -*Defined in [utils/src/abi_decoder.ts:58](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/utils/src/abi_decoder.ts#L58)* - -Attempt to decode a log given the ABI's the AbiDecoder knows about. - -**Type parameters:** - -▪ **ArgsType**: *`DecodedLogArgs`* - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`log` | `LogEntry` | The log to attempt to decode | - -**Returns:** *`LogWithDecodedArgs` | [RawLog](#rawlog)* - -The decoded log if the requisite ABI was available. Otherwise the log unaltered. - -
- -# Interface: LogEntry - - -## Properties - -### address - -• **address**: *string* - -*Defined in [ethereum-types/src/index.ts:435](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L435)* - -___ - -### blockHash - -• **blockHash**: *string | null* - -*Defined in [ethereum-types/src/index.ts:433](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L433)* - -___ - -### blockNumber - -• **blockNumber**: *number | null* - -*Defined in [ethereum-types/src/index.ts:434](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L434)* - -___ - -### data - -• **data**: *string* - -*Defined in [ethereum-types/src/index.ts:436](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L436)* - -___ - -### logIndex - -• **logIndex**: *number | null* - -*Defined in [ethereum-types/src/index.ts:430](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L430)* - -___ - -### topics - -• **topics**: *string[]* - -*Defined in [ethereum-types/src/index.ts:437](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L437)* - -___ - -### transactionHash - -• **transactionHash**: *string* - -*Defined in [ethereum-types/src/index.ts:432](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L432)* - -___ - -### transactionIndex - -• **transactionIndex**: *number | null* - -*Defined in [ethereum-types/src/index.ts:431](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L431)* - -
- -# Interface: LogEntryEvent - - -## Properties - -### address - -• **address**: *string* - -*Inherited from [LogEntry](#interface-logentry).[address](#address)* - -*Defined in [ethereum-types/src/index.ts:435](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L435)* - -___ - -### blockHash - -• **blockHash**: *string | null* - -*Inherited from [LogEntry](#interface-logentry).[blockHash](#blockhash)* - -*Defined in [ethereum-types/src/index.ts:433](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L433)* - -___ - -### blockNumber - -• **blockNumber**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[blockNumber](#blocknumber)* - -*Defined in [ethereum-types/src/index.ts:434](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L434)* - -___ - -### data - -• **data**: *string* - -*Inherited from [LogEntry](#interface-logentry).[data](#data)* - -*Defined in [ethereum-types/src/index.ts:436](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L436)* - -___ - -### logIndex - -• **logIndex**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[logIndex](#logindex)* - -*Defined in [ethereum-types/src/index.ts:430](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L430)* - -___ - -### removed - -• **removed**: *boolean* - -*Defined in [ethereum-types/src/index.ts:426](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L426)* - -___ - -### topics - -• **topics**: *string[]* - -*Inherited from [LogEntry](#interface-logentry).[topics](#topics)* - -*Defined in [ethereum-types/src/index.ts:437](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L437)* - -___ - -### transactionHash - -• **transactionHash**: *string* - -*Inherited from [LogEntry](#interface-logentry).[transactionHash](#transactionhash)* - -*Defined in [ethereum-types/src/index.ts:432](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L432)* - -___ - -### transactionIndex - -• **transactionIndex**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[transactionIndex](#transactionindex)* - -*Defined in [ethereum-types/src/index.ts:431](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L431)* - -
- -# Interface: LogWithDecodedArgs <**ArgsType**> - -## Type parameters - -▪ **ArgsType**: *[DecodedLogArgs](#class-decodedlogargs)* - - -## Properties - -### address - -• **address**: *string* - -*Inherited from [LogEntry](#interface-logentry).[address](#address)* - -*Defined in [ethereum-types/src/index.ts:435](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L435)* - -___ - -### args - -• **args**: *`ArgsType`* - -*Inherited from [DecodedLogEntry](#interface-decodedlogentry).[args](#args)* - -*Defined in [ethereum-types/src/index.ts:418](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L418)* - -___ - -### blockHash - -• **blockHash**: *string | null* - -*Inherited from [LogEntry](#interface-logentry).[blockHash](#blockhash)* - -*Defined in [ethereum-types/src/index.ts:433](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L433)* - -___ - -### blockNumber - -• **blockNumber**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[blockNumber](#blocknumber)* - -*Defined in [ethereum-types/src/index.ts:434](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L434)* - -___ - -### data - -• **data**: *string* - -*Inherited from [LogEntry](#interface-logentry).[data](#data)* - -*Defined in [ethereum-types/src/index.ts:436](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L436)* - -___ - -### event - -• **event**: *string* - -*Inherited from [DecodedLogEntry](#interface-decodedlogentry).[event](#event)* - -*Defined in [ethereum-types/src/index.ts:417](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L417)* - -___ - -### logIndex - -• **logIndex**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[logIndex](#logindex)* - -*Defined in [ethereum-types/src/index.ts:430](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L430)* - -___ - -### topics - -• **topics**: *string[]* - -*Inherited from [LogEntry](#interface-logentry).[topics](#topics)* - -*Defined in [ethereum-types/src/index.ts:437](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L437)* - -___ - -### transactionHash - -• **transactionHash**: *string* - -*Inherited from [LogEntry](#interface-logentry).[transactionHash](#transactionhash)* - -*Defined in [ethereum-types/src/index.ts:432](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L432)* - -___ - -### transactionIndex - -• **transactionIndex**: *number | null* - -*Inherited from [LogEntry](#interface-logentry).[transactionIndex](#transactionindex)* - -*Defined in [ethereum-types/src/index.ts:431](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L431)* - -
- -# Interface: MethodAbi - - -## Properties - -### constant - -• **constant**: *boolean* - -*Defined in [ethereum-types/src/index.ts:94](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L94)* - -___ - -### inputs - -• **inputs**: *[DataItem](#class-dataitem)[]* - -*Defined in [ethereum-types/src/index.ts:92](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L92)* - -___ - -### name - -• **name**: *string* - -*Defined in [ethereum-types/src/index.ts:91](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L91)* - -___ - -### outputs - -• **outputs**: *[DataItem](#class-dataitem)[]* - -*Defined in [ethereum-types/src/index.ts:93](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L93)* - -___ - -### payable - -• **payable**: *boolean* - -*Defined in [ethereum-types/src/index.ts:96](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L96)* - -___ - -### stateMutability - -• **stateMutability**: *[StateMutability](#statemutability)* - -*Defined in [ethereum-types/src/index.ts:95](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L95)* - -___ - -### type - -• **type**: *string* - -*Defined in [ethereum-types/src/index.ts:90](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L90)* - -
- - - - - -# Interface: RawLogEntry - - -## Properties - -### address - -• **address**: *string* - -*Defined in [ethereum-types/src/index.ts:492](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L492)* - -___ - -### blockHash - -• **blockHash**: *string | null* - -*Defined in [ethereum-types/src/index.ts:490](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L490)* - -___ - -### blockNumber - -• **blockNumber**: *string | null* - -*Defined in [ethereum-types/src/index.ts:491](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L491)* - -___ - -### data - -• **data**: *string* - -*Defined in [ethereum-types/src/index.ts:493](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L493)* - -___ - -### logIndex - -• **logIndex**: *string | null* - -*Defined in [ethereum-types/src/index.ts:487](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L487)* - -___ - -### topics - -• **topics**: *string[]* - -*Defined in [ethereum-types/src/index.ts:494](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L494)* - -___ - -### transactionHash - -• **transactionHash**: *string* - -*Defined in [ethereum-types/src/index.ts:489](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L489)* - -___ - -### transactionIndex - -• **transactionIndex**: *string | null* - -*Defined in [ethereum-types/src/index.ts:488](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L488)* - -
- -# Interface: RevertErrorAbi - - -## Properties - -### `Optional` arguments - -• **arguments**? : *[DataItem](#class-dataitem)[]* - -*Defined in [ethereum-types/src/index.ts:122](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L122)* - -___ - -### name - -• **name**: *string* - -*Defined in [ethereum-types/src/index.ts:121](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L121)* - -___ - -### type - -• **type**: *"error"* - -*Defined in [ethereum-types/src/index.ts:120](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L120)* - -
- - - - - - - - - - - -# Interface: StructLog - - -## Properties - -### depth - -• **depth**: *number* - -*Defined in [ethereum-types/src/index.ts:294](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L294)* - -___ - -### error - -• **error**: *string* - -*Defined in [ethereum-types/src/index.ts:295](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L295)* - -___ - -### gas - -• **gas**: *number* - -*Defined in [ethereum-types/src/index.ts:296](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L296)* - -___ - -### gasCost - -• **gasCost**: *number* - -*Defined in [ethereum-types/src/index.ts:297](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L297)* - -___ - -### memory - -• **memory**: *string[]* - -*Defined in [ethereum-types/src/index.ts:298](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L298)* - -___ - -### op - -• **op**: *[OpCode](#enumeration-opcode)* - -*Defined in [ethereum-types/src/index.ts:299](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L299)* - -___ - -### pc - -• **pc**: *number* - -*Defined in [ethereum-types/src/index.ts:300](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L300)* - -___ - -### stack - -• **stack**: *string[]* - -*Defined in [ethereum-types/src/index.ts:301](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L301)* - -___ - -### storage - -• **storage**: *object* - -*Defined in [ethereum-types/src/index.ts:302](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L302)* - -#### Type declaration: - -● \[▪ **location**: *string*\]: string - -
- -# Interface: TraceParams - - -## Properties - -### `Optional` disableMemory - -• **disableMemory**? : *undefined | false | true* - -*Defined in [ethereum-types/src/index.ts:519](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L519)* - -___ - -### `Optional` disableStack - -• **disableStack**? : *undefined | false | true* - -*Defined in [ethereum-types/src/index.ts:520](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L520)* - -___ - -### `Optional` disableStorage - -• **disableStorage**? : *undefined | false | true* - -*Defined in [ethereum-types/src/index.ts:521](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L521)* - -___ - -### `Optional` timeout - -• **timeout**? : *undefined | string* - -*Defined in [ethereum-types/src/index.ts:523](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L523)* - -___ - -### `Optional` tracer - -• **tracer**? : *undefined | string* - -*Defined in [ethereum-types/src/index.ts:522](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L522)* - -
- -# Interface: Transaction - - -## Properties - -### blockHash - -• **blockHash**: *string | null* - -*Defined in [ethereum-types/src/index.ts:378](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L378)* - -___ - -### blockNumber - -• **blockNumber**: *number | null* - -*Defined in [ethereum-types/src/index.ts:379](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L379)* - -___ - -### from - -• **from**: *string* - -*Defined in [ethereum-types/src/index.ts:381](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L381)* - -___ - -### gas - -• **gas**: *number* - -*Defined in [ethereum-types/src/index.ts:385](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L385)* - -___ - -### gasPrice - -• **gasPrice**: *`BigNumber`* - -*Defined in [ethereum-types/src/index.ts:384](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L384)* - -___ - -### hash - -• **hash**: *string* - -*Defined in [ethereum-types/src/index.ts:376](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L376)* - -___ - -### input - -• **input**: *string* - -*Defined in [ethereum-types/src/index.ts:386](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L386)* - -___ - -### nonce - -• **nonce**: *number* - -*Defined in [ethereum-types/src/index.ts:377](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L377)* - -___ - -### to - -• **to**: *string | null* - -*Defined in [ethereum-types/src/index.ts:382](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L382)* - -___ - -### transactionIndex - -• **transactionIndex**: *number | null* - -*Defined in [ethereum-types/src/index.ts:380](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L380)* - -___ - -### value - -• **value**: *`BigNumber`* - -*Defined in [ethereum-types/src/index.ts:383](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L383)* - -
- -# Interface: TransactionReceipt - - -## Properties - -### blockHash - -• **blockHash**: *string* - -*Defined in [ethereum-types/src/index.ts:449](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L449)* - -___ - -### blockNumber - -• **blockNumber**: *number* - -*Defined in [ethereum-types/src/index.ts:450](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L450)* - -___ - -### contractAddress - -• **contractAddress**: *string | null* - -*Defined in [ethereum-types/src/index.ts:458](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L458)* - -___ - -### cumulativeGasUsed - -• **cumulativeGasUsed**: *number* - -*Defined in [ethereum-types/src/index.ts:456](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L456)* - -___ - -### from - -• **from**: *string* - -*Defined in [ethereum-types/src/index.ts:453](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L453)* - -___ - -### gasUsed - -• **gasUsed**: *number* - -*Defined in [ethereum-types/src/index.ts:457](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L457)* - -___ - -### logs - -• **logs**: *[LogEntry](#class-logentry)[]* - -*Defined in [ethereum-types/src/index.ts:459](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L459)* - -___ - -### status - -• **status**: *[TransactionReceiptStatus](#transactionreceiptstatus)* - -*Defined in [ethereum-types/src/index.ts:455](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L455)* - -___ - -### to - -• **to**: *string* - -*Defined in [ethereum-types/src/index.ts:454](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L454)* - -___ - -### transactionHash - -• **transactionHash**: *string* - -*Defined in [ethereum-types/src/index.ts:451](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L451)* - -___ - -### transactionIndex - -• **transactionIndex**: *number* - -*Defined in [ethereum-types/src/index.ts:452](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L452)* - -
- -# Interface: TransactionReceiptWithDecodedLogs - -Contains the logs returned by a TransactionReceipt. We attempt to decode the -logs using AbiDecoder. If we have the logs corresponding ABI, we decode it, -otherwise we don't. - - -## Properties - -### blockHash - -• **blockHash**: *string* - -*Inherited from [TransactionReceipt](#interface-transactionreceipt).[blockHash](#blockhash)* - -*Defined in [ethereum-types/src/index.ts:449](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L449)* - -___ - -### blockNumber - -• **blockNumber**: *number* - -*Inherited from [TransactionReceipt](#interface-transactionreceipt).[blockNumber](#blocknumber)* - -*Defined in [ethereum-types/src/index.ts:450](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L450)* - -___ - -### contractAddress - -• **contractAddress**: *string | null* - -*Inherited from [TransactionReceipt](#interface-transactionreceipt).[contractAddress](#contractaddress)* - -*Defined in [ethereum-types/src/index.ts:458](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L458)* - -___ - -### cumulativeGasUsed - -• **cumulativeGasUsed**: *number* - -*Inherited from [TransactionReceipt](#interface-transactionreceipt).[cumulativeGasUsed](#cumulativegasused)* - -*Defined in [ethereum-types/src/index.ts:456](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L456)* - -___ - -### from - -• **from**: *string* - -*Inherited from [TransactionReceipt](#interface-transactionreceipt).[from](#from)* - -*Defined in [ethereum-types/src/index.ts:453](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L453)* - -___ - -### gasUsed - -• **gasUsed**: *number* - -*Inherited from [TransactionReceipt](#interface-transactionreceipt).[gasUsed](#gasused)* - -*Defined in [ethereum-types/src/index.ts:457](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L457)* - -___ - -### logs - -• **logs**: *`Array | LogEntry>`* - -*Overrides [TransactionReceipt](_ethereum_types_src_index_.transactionreceipt.md).[logs](#logs)* - -*Defined in [ethereum-types/src/index.ts:515](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L515)* - -___ - -### status - -• **status**: *[TransactionReceiptStatus](#transactionreceiptstatus)* - -*Inherited from [TransactionReceipt](#interface-transactionreceipt).[status](#status)* - -*Defined in [ethereum-types/src/index.ts:455](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L455)* - -___ - -### to - -• **to**: *string* - -*Inherited from [TransactionReceipt](#interface-transactionreceipt).[to](#to)* - -*Defined in [ethereum-types/src/index.ts:454](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L454)* - -___ - -### transactionHash - -• **transactionHash**: *string* - -*Inherited from [TransactionReceipt](#interface-transactionreceipt).[transactionHash](#transactionhash)* - -*Defined in [ethereum-types/src/index.ts:451](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L451)* - -___ - -### transactionIndex - -• **transactionIndex**: *number* - -*Inherited from [TransactionReceipt](#interface-transactionreceipt).[transactionIndex](#transactionindex)* - -*Defined in [ethereum-types/src/index.ts:452](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L452)* - -
- -# Interface: TransactionTrace - - -## Properties - -### gas - -• **gas**: *number* - -*Defined in [ethereum-types/src/index.ts:306](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L306)* - -___ - -### returnValue - -• **returnValue**: *any* - -*Defined in [ethereum-types/src/index.ts:307](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L307)* - -___ - -### structLogs - -• **structLogs**: *[StructLog](#class-structlog)[]* - -*Defined in [ethereum-types/src/index.ts:308](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L308)* - -
- -# Interface: TupleDataItem - - -## Properties - -### components - -• **components**: *[DataItem](#class-dataitem)[]* - -*Overrides [DataItem](_ethereum_types_src_index_.dataitem.md).[components](#optional-components)* - -*Defined in [ethereum-types/src/index.ts:142](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L142)* - -___ - -### `Optional` internalType - -• **internalType**? : *undefined | string* - -*Inherited from [DataItem](#interface-dataitem).[internalType](#optional-internaltype)* - -*Defined in [ethereum-types/src/index.ts:137](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L137)* - -___ - -### name - -• **name**: *string* - -*Inherited from [DataItem](#interface-dataitem).[name](#name)* - -*Defined in [ethereum-types/src/index.ts:135](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L135)* - -___ - -### type - -• **type**: *string* - -*Inherited from [DataItem](#interface-dataitem).[type](#type)* - -*Defined in [ethereum-types/src/index.ts:136](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L136)* - -
- -# Interface: TxData - - -## Properties - -### `Optional` data - -• **data**? : *undefined | string* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[data](#optional-data)* - -*Defined in [ethereum-types/src/index.ts:394](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L394)* - -___ - -### from - -• **from**: *string* - -*Defined in [ethereum-types/src/index.ts:399](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L399)* - -___ - -### `Optional` gas - -• **gas**? : *number | string | `BigNumber`* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[gas](#optional-gas)* - -*Defined in [ethereum-types/src/index.ts:392](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L392)* - -___ - -### `Optional` gasPrice - -• **gasPrice**? : *number | string | `BigNumber`* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[gasPrice](#optional-gasprice)* - -*Defined in [ethereum-types/src/index.ts:393](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L393)* - -___ - -### `Optional` nonce - -• **nonce**? : *undefined | number* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[nonce](#optional-nonce)* - -*Defined in [ethereum-types/src/index.ts:395](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L395)* - -___ - -### `Optional` to - -• **to**? : *undefined | string* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[to](#optional-to)* - -*Defined in [ethereum-types/src/index.ts:390](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L390)* - -___ - -### `Optional` value - -• **value**? : *number | string | `BigNumber`* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[value](#optional-value)* - -*Defined in [ethereum-types/src/index.ts:391](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L391)* - -
- -# Interface: TxDataPayable - - -## Properties - -### `Optional` data - -• **data**? : *undefined | string* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[data](#optional-data)* - -*Defined in [ethereum-types/src/index.ts:394](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L394)* - -___ - -### from - -• **from**: *string* - -*Inherited from [TxData](#interface-txdata).[from](#from)* - -*Defined in [ethereum-types/src/index.ts:399](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L399)* - -___ - -### `Optional` gas - -• **gas**? : *number | string | `BigNumber`* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[gas](#optional-gas)* - -*Defined in [ethereum-types/src/index.ts:392](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L392)* - -___ - -### `Optional` gasPrice - -• **gasPrice**? : *number | string | `BigNumber`* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[gasPrice](#optional-gasprice)* - -*Defined in [ethereum-types/src/index.ts:393](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L393)* - -___ - -### `Optional` nonce - -• **nonce**? : *undefined | number* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[nonce](#optional-nonce)* - -*Defined in [ethereum-types/src/index.ts:395](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L395)* - -___ - -### `Optional` to - -• **to**? : *undefined | string* - -*Inherited from [CallTxDataBase](#interface-calltxdatabase).[to](#optional-to)* - -*Defined in [ethereum-types/src/index.ts:390](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L390)* - -___ - -### `Optional` value - -• **value**? : *`BigNumber`* - -*Overrides [CallTxDataBase](_ethereum_types_src_index_.calltxdatabase.md).[value](#optional-value)* - -*Defined in [ethereum-types/src/index.ts:443](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L443)* - -
- -# Interface: Web3JsV1Provider - -Web3.js version 1 provider interface -This provider interface was implemented in the pre-1.0Beta releases for Web3.js. -This interface allowed sending synchonous requests, support for which was later dropped. - - -## Methods - -### send - -▸ **send**(`payload`: [JSONRPCRequestPayload](_ethereum_types_src_index_.jsonrpcrequestpayload.md)): *[JSONRPCResponsePayload](#class-jsonrpcresponsepayload)* - -*Defined in [ethereum-types/src/index.ts:45](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L45)* - -**Parameters:** - -Name | Type | ------- | ------ | -`payload` | [JSONRPCRequestPayload](#class-jsonrpcrequestpayload) | - -**Returns:** *[JSONRPCResponsePayload](#class-jsonrpcresponsepayload)* - -___ - -### sendAsync - -▸ **sendAsync**(`payload`: [JSONRPCRequestPayload](_ethereum_types_src_index_.jsonrpcrequestpayload.md), `callback`: [JSONRPCErrorCallback](#jsonrpcerrorcallback)): *void* - -*Defined in [ethereum-types/src/index.ts:44](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L44)* - -**Parameters:** - -Name | Type | ------- | ------ | -`payload` | [JSONRPCRequestPayload](#class-jsonrpcrequestpayload) | -`callback` | [JSONRPCErrorCallback](#jsonrpcerrorcallback) | - -**Returns:** *void* - -
- -# Interface: Web3JsV2Provider - -Web3.js version 2 provider interface -This provider interface was used in a couple of Web3.js 1.0 beta releases -before the first attempts to conform to EIP1193 - - -## Methods - -### send - -▸ **send**(`payload`: [JSONRPCRequestPayload](_ethereum_types_src_index_.jsonrpcrequestpayload.md), `callback`: [JSONRPCErrorCallback](#jsonrpcerrorcallback)): *void* - -*Defined in [ethereum-types/src/index.ts:54](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L54)* - -**Parameters:** - -Name | Type | ------- | ------ | -`payload` | [JSONRPCRequestPayload](#class-jsonrpcrequestpayload) | -`callback` | [JSONRPCErrorCallback](#jsonrpcerrorcallback) | - -**Returns:** *void* - -
- -# Interface: Web3JsV3Provider - -Web3.js version 3 provider interface -This provider interface was implemented with the hopes for conforming to the EIP1193 spec, -however it does not conform entirely. - - -## Methods - -### send - -▸ **send**(`method`: string, `params?`: any[]): *`Promise`* - -*Defined in [ethereum-types/src/index.ts:63](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L63)* - -**Parameters:** - -Name | Type | ------- | ------ | -`method` | string | -`params?` | any[] | - -**Returns:** *`Promise`* - -
- -# Interface: ZeroExProvider - -The interface for the provider used internally by 0x libraries -Any property we use from any SupportedProvider should we explicitly -add here - - -## Properties - -### `Optional` isMetaMask - -• **isMetaMask**? : *undefined | false | true* - -*Defined in [ethereum-types/src/index.ts:31](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L31)* - -___ - -### `Optional` isParity - -• **isParity**? : *undefined | false | true* - -*Defined in [ethereum-types/src/index.ts:32](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L32)* - -___ - -### `Optional` isZeroExProvider - -• **isZeroExProvider**? : *undefined | false | true* - -*Defined in [ethereum-types/src/index.ts:30](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L30)* - -## Methods - -### `Optional` enable - -▸ **enable**(): *`Promise`* - -*Defined in [ethereum-types/src/index.ts:34](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L34)* - -**Returns:** *`Promise`* - -___ - -### sendAsync - -▸ **sendAsync**(`payload`: [JSONRPCRequestPayload](_ethereum_types_src_index_.jsonrpcrequestpayload.md), `callback`: [JSONRPCErrorCallback](#jsonrpcerrorcallback)): *void* - -*Defined in [ethereum-types/src/index.ts:35](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L35)* - -**Parameters:** - -Name | Type | ------- | ------ | -`payload` | [JSONRPCRequestPayload](#class-jsonrpcrequestpayload) | -`callback` | [JSONRPCErrorCallback](#jsonrpcerrorcallback) | - -**Returns:** *void* - -___ - -### `Optional` stop - -▸ **stop**(): *void* - -*Defined in [ethereum-types/src/index.ts:33](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L33)* - -**Returns:** *void* - -
- - - -# Interface: BlockWithoutTransactionDataRPC - - -## Properties - -### difficulty - -• **difficulty**: *string* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[difficulty](#difficulty)* - -*Defined in [web3-wrapper/src/types.ts:15](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L15)* - -___ - -### extraData - -• **extraData**: *string* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[extraData](#extradata)* - -*Defined in [web3-wrapper/src/types.ts:17](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L17)* - -___ - -### gasLimit - -• **gasLimit**: *string* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[gasLimit](#gaslimit)* - -*Defined in [web3-wrapper/src/types.ts:19](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L19)* - -___ - -### gasUsed - -• **gasUsed**: *string* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[gasUsed](#gasused)* - -*Defined in [web3-wrapper/src/types.ts:20](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L20)* - -___ - -### hash - -• **hash**: *string | null* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[hash](#hash)* - -*Defined in [web3-wrapper/src/types.ts:7](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L7)* - -___ - -### logsBloom - -• **logsBloom**: *string | null* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[logsBloom](#logsbloom)* - -*Defined in [web3-wrapper/src/types.ts:11](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L11)* - -___ - -### miner - -• **miner**: *string* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[miner](#miner)* - -*Defined in [web3-wrapper/src/types.ts:14](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L14)* - -___ - -### nonce - -• **nonce**: *string | null* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[nonce](#nonce)* - -*Defined in [web3-wrapper/src/types.ts:9](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L9)* - -___ - -### number - -• **number**: *string | null* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[number](#number)* - -*Defined in [web3-wrapper/src/types.ts:6](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L6)* - -___ - -### parentHash - -• **parentHash**: *string* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[parentHash](#parenthash)* - -*Defined in [web3-wrapper/src/types.ts:8](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L8)* - -___ - -### sha3Uncles - -• **sha3Uncles**: *string* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[sha3Uncles](#sha3uncles)* - -*Defined in [web3-wrapper/src/types.ts:10](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L10)* - -___ - -### size - -• **size**: *string* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[size](#size)* - -*Defined in [web3-wrapper/src/types.ts:18](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L18)* - -___ - -### stateRoot - -• **stateRoot**: *string* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[stateRoot](#stateroot)* - -*Defined in [web3-wrapper/src/types.ts:13](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L13)* - -___ - -### timestamp - -• **timestamp**: *string* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[timestamp](#timestamp)* - -*Defined in [web3-wrapper/src/types.ts:21](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L21)* - -___ - -### totalDifficulty - -• **totalDifficulty**: *string* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[totalDifficulty](#totaldifficulty)* - -*Defined in [web3-wrapper/src/types.ts:16](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L16)* - -___ - -### transactions - -• **transactions**: *string[]* - -*Defined in [web3-wrapper/src/types.ts:25](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L25)* - -___ - -### transactionsRoot - -• **transactionsRoot**: *string* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[transactionsRoot](#transactionsroot)* - -*Defined in [web3-wrapper/src/types.ts:12](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L12)* - -___ - -### uncles - -• **uncles**: *string[]* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[uncles](#uncles)* - -*Defined in [web3-wrapper/src/types.ts:22](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L22)* - -
- -# Interface: BlockWithTransactionDataRPC - - -## Properties - -### difficulty - -• **difficulty**: *string* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[difficulty](#difficulty)* - -*Defined in [web3-wrapper/src/types.ts:15](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L15)* - -___ - -### extraData - -• **extraData**: *string* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[extraData](#extradata)* - -*Defined in [web3-wrapper/src/types.ts:17](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L17)* - -___ - -### gasLimit - -• **gasLimit**: *string* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[gasLimit](#gaslimit)* - -*Defined in [web3-wrapper/src/types.ts:19](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L19)* - -___ - -### gasUsed - -• **gasUsed**: *string* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[gasUsed](#gasused)* - -*Defined in [web3-wrapper/src/types.ts:20](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L20)* - -___ - -### hash - -• **hash**: *string | null* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[hash](#hash)* - -*Defined in [web3-wrapper/src/types.ts:7](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L7)* - -___ - -### logsBloom - -• **logsBloom**: *string | null* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[logsBloom](#logsbloom)* - -*Defined in [web3-wrapper/src/types.ts:11](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L11)* - -___ - -### miner - -• **miner**: *string* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[miner](#miner)* - -*Defined in [web3-wrapper/src/types.ts:14](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L14)* - -___ - -### nonce - -• **nonce**: *string | null* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[nonce](#nonce)* - -*Defined in [web3-wrapper/src/types.ts:9](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L9)* - -___ - -### number - -• **number**: *string | null* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[number](#number)* - -*Defined in [web3-wrapper/src/types.ts:6](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L6)* - -___ - -### parentHash - -• **parentHash**: *string* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[parentHash](#parenthash)* - -*Defined in [web3-wrapper/src/types.ts:8](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L8)* - -___ - -### sha3Uncles - -• **sha3Uncles**: *string* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[sha3Uncles](#sha3uncles)* - -*Defined in [web3-wrapper/src/types.ts:10](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L10)* - -___ - -### size - -• **size**: *string* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[size](#size)* - -*Defined in [web3-wrapper/src/types.ts:18](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L18)* - -___ - -### stateRoot - -• **stateRoot**: *string* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[stateRoot](#stateroot)* - -*Defined in [web3-wrapper/src/types.ts:13](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L13)* - -___ - -### timestamp - -• **timestamp**: *string* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[timestamp](#timestamp)* - -*Defined in [web3-wrapper/src/types.ts:21](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L21)* - -___ - -### totalDifficulty - -• **totalDifficulty**: *string* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[totalDifficulty](#totaldifficulty)* - -*Defined in [web3-wrapper/src/types.ts:16](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L16)* - -___ - -### transactions - -• **transactions**: *[TransactionRPC](#class-transactionrpc)[]* - -*Defined in [web3-wrapper/src/types.ts:28](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L28)* - -___ - -### transactionsRoot - -• **transactionsRoot**: *string* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[transactionsRoot](#transactionsroot)* - -*Defined in [web3-wrapper/src/types.ts:12](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L12)* - -___ - -### uncles - -• **uncles**: *string[]* - -*Inherited from [AbstractBlockRPC](#interface-abstractblockrpc).[uncles](#uncles)* - -*Defined in [web3-wrapper/src/types.ts:22](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L22)* - -
- -# Interface: CallDataRPC - - -## Properties - -### `Optional` data - -• **data**? : *undefined | string* - -*Inherited from [CallTxDataBaseRPC](#interface-calltxdatabaserpc).[data](#optional-data)* - -*Defined in [web3-wrapper/src/types.ts:76](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L76)* - -___ - -### `Optional` from - -• **from**? : *undefined | string* - -*Defined in [web3-wrapper/src/types.ts:85](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L85)* - -___ - -### `Optional` gas - -• **gas**? : *undefined | string* - -*Inherited from [CallTxDataBaseRPC](#interface-calltxdatabaserpc).[gas](#optional-gas)* - -*Defined in [web3-wrapper/src/types.ts:74](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L74)* - -___ - -### `Optional` gasPrice - -• **gasPrice**? : *undefined | string* - -*Inherited from [CallTxDataBaseRPC](#interface-calltxdatabaserpc).[gasPrice](#optional-gasprice)* - -*Defined in [web3-wrapper/src/types.ts:75](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L75)* - -___ - -### `Optional` nonce - -• **nonce**? : *undefined | string* - -*Inherited from [CallTxDataBaseRPC](#interface-calltxdatabaserpc).[nonce](#optional-nonce)* - -*Defined in [web3-wrapper/src/types.ts:77](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L77)* - -___ - -### `Optional` to - -• **to**? : *undefined | string* - -*Inherited from [CallTxDataBaseRPC](#interface-calltxdatabaserpc).[to](#optional-to)* - -*Defined in [web3-wrapper/src/types.ts:72](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L72)* - -___ - -### `Optional` value - -• **value**? : *undefined | string* - -*Inherited from [CallTxDataBaseRPC](#interface-calltxdatabaserpc).[value](#optional-value)* - -*Defined in [web3-wrapper/src/types.ts:73](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L73)* - -
- - - -# Interface: LogEntryRPC - - -## Properties - -### address - -• **address**: *string* - -*Defined in [web3-wrapper/src/types.ts:64](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L64)* - -___ - -### blockHash - -• **blockHash**: *string | null* - -*Defined in [web3-wrapper/src/types.ts:62](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L62)* - -___ - -### blockNumber - -• **blockNumber**: *string | null* - -*Defined in [web3-wrapper/src/types.ts:63](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L63)* - -___ - -### data - -• **data**: *string* - -*Defined in [web3-wrapper/src/types.ts:65](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L65)* - -___ - -### logIndex - -• **logIndex**: *string | null* - -*Defined in [web3-wrapper/src/types.ts:59](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L59)* - -___ - -### topics - -• **topics**: *string[]* - -*Defined in [web3-wrapper/src/types.ts:66](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L66)* - -___ - -### transactionHash - -• **transactionHash**: *string* - -*Defined in [web3-wrapper/src/types.ts:61](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L61)* - -___ - -### transactionIndex - -• **transactionIndex**: *string | null* - -*Defined in [web3-wrapper/src/types.ts:60](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L60)* - -
- -# Interface: TransactionReceiptRPC - - -## Properties - -### blockHash - -• **blockHash**: *string* - -*Defined in [web3-wrapper/src/types.ts:45](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L45)* - -___ - -### blockNumber - -• **blockNumber**: *string* - -*Defined in [web3-wrapper/src/types.ts:46](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L46)* - -___ - -### contractAddress - -• **contractAddress**: *string | null* - -*Defined in [web3-wrapper/src/types.ts:54](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L54)* - -___ - -### cumulativeGasUsed - -• **cumulativeGasUsed**: *string* - -*Defined in [web3-wrapper/src/types.ts:52](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L52)* - -___ - -### from - -• **from**: *string* - -*Defined in [web3-wrapper/src/types.ts:49](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L49)* - -___ - -### gasUsed - -• **gasUsed**: *string* - -*Defined in [web3-wrapper/src/types.ts:53](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L53)* - -___ - -### logs - -• **logs**: *[LogEntryRPC](#class-logentryrpc)[]* - -*Defined in [web3-wrapper/src/types.ts:55](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L55)* - -___ - -### status - -• **status**: *[TransactionReceiptStatusRPC](#transactionreceiptstatusrpc)* - -*Defined in [web3-wrapper/src/types.ts:51](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L51)* - -___ - -### to - -• **to**: *string* - -*Defined in [web3-wrapper/src/types.ts:50](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L50)* - -___ - -### transactionHash - -• **transactionHash**: *string* - -*Defined in [web3-wrapper/src/types.ts:47](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L47)* - -___ - -### transactionIndex - -• **transactionIndex**: *string* - -*Defined in [web3-wrapper/src/types.ts:48](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L48)* - -
- -# Interface: TransactionRPC - - -## Properties - -### blockHash - -• **blockHash**: *string | null* - -*Defined in [web3-wrapper/src/types.ts:33](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L33)* - -___ - -### blockNumber - -• **blockNumber**: *string | null* - -*Defined in [web3-wrapper/src/types.ts:34](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L34)* - -___ - -### from - -• **from**: *string* - -*Defined in [web3-wrapper/src/types.ts:36](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L36)* - -___ - -### gas - -• **gas**: *string* - -*Defined in [web3-wrapper/src/types.ts:40](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L40)* - -___ - -### gasPrice - -• **gasPrice**: *string* - -*Defined in [web3-wrapper/src/types.ts:39](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L39)* - -___ - -### hash - -• **hash**: *string* - -*Defined in [web3-wrapper/src/types.ts:31](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L31)* - -___ - -### input - -• **input**: *string* - -*Defined in [web3-wrapper/src/types.ts:41](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L41)* - -___ - -### nonce - -• **nonce**: *string* - -*Defined in [web3-wrapper/src/types.ts:32](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L32)* - -___ - -### to - -• **to**: *string | null* - -*Defined in [web3-wrapper/src/types.ts:37](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L37)* - -___ - -### transactionIndex - -• **transactionIndex**: *string | null* - -*Defined in [web3-wrapper/src/types.ts:35](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L35)* - -___ - -### value - -• **value**: *string* - -*Defined in [web3-wrapper/src/types.ts:38](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L38)* - -
- -# Interface: TxDataRPC - - -## Properties - -### `Optional` data - -• **data**? : *undefined | string* - -*Inherited from [CallTxDataBaseRPC](#interface-calltxdatabaserpc).[data](#optional-data)* - -*Defined in [web3-wrapper/src/types.ts:76](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L76)* - -___ - -### from - -• **from**: *string* - -*Defined in [web3-wrapper/src/types.ts:81](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L81)* - -___ - -### `Optional` gas - -• **gas**? : *undefined | string* - -*Inherited from [CallTxDataBaseRPC](#interface-calltxdatabaserpc).[gas](#optional-gas)* - -*Defined in [web3-wrapper/src/types.ts:74](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L74)* - -___ - -### `Optional` gasPrice - -• **gasPrice**? : *undefined | string* - -*Inherited from [CallTxDataBaseRPC](#interface-calltxdatabaserpc).[gasPrice](#optional-gasprice)* - -*Defined in [web3-wrapper/src/types.ts:75](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L75)* - -___ - -### `Optional` nonce - -• **nonce**? : *undefined | string* - -*Inherited from [CallTxDataBaseRPC](#interface-calltxdatabaserpc).[nonce](#optional-nonce)* - -*Defined in [web3-wrapper/src/types.ts:77](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L77)* - -___ - -### `Optional` to - -• **to**? : *undefined | string* - -*Inherited from [CallTxDataBaseRPC](#interface-calltxdatabaserpc).[to](#optional-to)* - -*Defined in [web3-wrapper/src/types.ts:72](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L72)* - -___ - -### `Optional` value - -• **value**? : *undefined | string* - -*Inherited from [CallTxDataBaseRPC](#interface-calltxdatabaserpc).[value](#optional-value)* - -*Defined in [web3-wrapper/src/types.ts:73](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L73)* - -
- - - - -## Type aliases - -### TransactionReceiptStatusRPC - -Ƭ **TransactionReceiptStatusRPC**: *null | string | `0` | `1`* - -*Defined in [web3-wrapper/src/types.ts:69](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/types.ts#L69)* - -
- - - - -## Type aliases - -### AbiDefinition - -Ƭ **AbiDefinition**: *[FunctionAbi](_ethereum_types_src_index_.md#functionabi) | [EventAbi](#interface-eventabi) | [RevertErrorAbi](#interface-reverterrorabi)* - -*Defined in [ethereum-types/src/index.ts:80](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L80)* - -___ - -### BlockParam - -Ƭ **BlockParam**: *[BlockParamLiteral](#enumeration-blockparamliteral) | number* - -*Defined in [ethereum-types/src/index.ts:484](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L484)* - -___ - -### ConstructorStateMutability - -Ƭ **ConstructorStateMutability**: *"nonpayable" | "payable"* - -*Defined in [ethereum-types/src/index.ts:84](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L84)* - -___ - - - -### ContractEventArg - -Ƭ **ContractEventArg**: *any* - -*Defined in [ethereum-types/src/index.ts:469](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L469)* - -___ - - - -### EIP1193Event - -Ƭ **EIP1193Event**: *"accountsChanged" | "networkChanged" | "close" | "connect" | "notification"* - -*Defined in [ethereum-types/src/index.ts:70](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L70)* - -Interface for providers that conform to EIP 1193 -Source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md - -___ - - - - - -### FunctionAbi - -Ƭ **FunctionAbi**: *[MethodAbi](#interface-methodabi) | [ConstructorAbi](#interface-constructorabi) | [FallbackAbi](#interface-fallbackabi)* - -*Defined in [ethereum-types/src/index.ts:82](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L82)* - -___ - -### JSONRPCErrorCallback - -Ƭ **JSONRPCErrorCallback**: *function* - -*Defined in [ethereum-types/src/index.ts:3](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L3)* - -#### Type declaration: - -▸ (`err`: `Error` | null, `result?`: [JSONRPCResponsePayload](#interface-jsonrpcresponsepayload)): *void* - -**Parameters:** - -Name | Type | ------- | ------ | -`err` | `Error` \| null | -`result?` | [JSONRPCResponsePayload](#interface-jsonrpcresponsepayload) | - -___ - -### LogTopic - -Ƭ **LogTopic**: *null | string | string[]* - -*Defined in [ethereum-types/src/index.ts:414](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L414)* - -___ - - - - - -### RawLog - -Ƭ **RawLog**: *[LogEntry](#interface-logentry)* - -*Defined in [ethereum-types/src/index.ts:476](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L476)* - -___ - -### StateMutability - -Ƭ **StateMutability**: *"pure" | "view" | [ConstructorStateMutability](#constructorstatemutability)* - -*Defined in [ethereum-types/src/index.ts:85](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L85)* - -___ - -### SupportedProvider - -Ƭ **SupportedProvider**: *[Web3JsProvider](_ethereum_types_src_index_.md#web3jsprovider) | [GanacheProvider](#interface-ganacheprovider) | [EIP1193Provider](#interface-eip1193provider) | [ZeroExProvider](#interface-zeroexprovider)* - -*Defined in [ethereum-types/src/index.ts:9](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L9)* - -Do not create your own provider. Use an existing provider from a Web3 or ProviderEngine library -Read more about Providers in the guides section of the 0x docs. - -___ - -### TransactionReceiptStatus - -Ƭ **TransactionReceiptStatus**: *null | string | `0` | `1`* - -*Defined in [ethereum-types/src/index.ts:446](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L446)* - -___ - - - -### Web3JsProvider - -Ƭ **Web3JsProvider**: *[Web3JsV1Provider](#interface-web3jsv1provider) | [Web3JsV2Provider](#interface-web3jsv2provider) | [Web3JsV3Provider](#interface-web3jsv3provider)* - -*Defined in [ethereum-types/src/index.ts:11](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L11)* - -
- - - -
- - - - -## Object literals - -### `Const` marshaller - -#### ▪ **marshaller**: *object* - -*Defined in [web3-wrapper/src/marshaller.ts:33](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/marshaller.ts#L33)* - -Utils to convert ethereum structures from user-space format to RPC format. (marshall/unmarshall) - -#### _marshalCallTxDataBase - -▸ **_marshalCallTxDataBase**(`callTxDataBase`: `Partial`): *`Partial`* - -*Defined in [web3-wrapper/src/marshaller.ts:208](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/marshaller.ts#L208)* - -**Parameters:** - -Name | Type | ------- | ------ | -`callTxDataBase` | `Partial` | - -**Returns:** *`Partial`* - -#### marshalAddress - -▸ **marshalAddress**(`address`: string): *string* - -*Defined in [web3-wrapper/src/marshaller.ts:176](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/marshaller.ts#L176)* - -Marshall address - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`address` | string | address to marshall | - -**Returns:** *string* - -marshalled address - -#### marshalBlockParam - -▸ **marshalBlockParam**(`blockParam`: [BlockParam](#blockparam) | string | number | undefined): *string | undefined* - -*Defined in [web3-wrapper/src/marshaller.ts:187](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/marshaller.ts#L187)* - -Marshall block param - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`blockParam` | [BlockParam](#blockparam) \| string \| number \| undefined | block param to marshall | - -**Returns:** *string | undefined* - -marshalled block param - -#### marshalCallData - -▸ **marshalCallData**(`callData`: `Partial`): *`Partial`* - -*Defined in [web3-wrapper/src/marshaller.ts:159](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/marshaller.ts#L159)* - -Marshall call data - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`callData` | `Partial` | call data to marshall | - -**Returns:** *`Partial`* - -marshalled call data - -#### marshalTxData - -▸ **marshalTxData**(`txData`: `Partial`): *`Partial`* - -*Defined in [web3-wrapper/src/marshaller.ts:133](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/marshaller.ts#L133)* - -Marshall transaction data - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`txData` | `Partial` | transaction data to marshall | - -**Returns:** *`Partial`* - -marshalled transaction data - -#### unmarshalIntoBlockWithTransactionData - -▸ **unmarshalIntoBlockWithTransactionData**(`blockWithHexValues`: [BlockWithTransactionDataRPC](#interface-blockwithtransactiondatarpc)): *`BlockWithTransactionData`* - -*Defined in [web3-wrapper/src/marshaller.ts:59](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/marshaller.ts#L59)* - -Unmarshall block with transaction data - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`blockWithHexValues` | [BlockWithTransactionDataRPC](#interface-blockwithtransactiondatarpc) | block to unmarshall | - -**Returns:** *`BlockWithTransactionData`* - -unmarshalled block with transaction data - -#### unmarshalIntoBlockWithoutTransactionData - -▸ **unmarshalIntoBlockWithoutTransactionData**(`blockWithHexValues`: [BlockWithoutTransactionDataRPC](#interface-blockwithouttransactiondatarpc)): *`BlockWithoutTransactionData`* - -*Defined in [web3-wrapper/src/marshaller.ts:39](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/marshaller.ts#L39)* - -Unmarshall block without transaction data - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`blockWithHexValues` | [BlockWithoutTransactionDataRPC](#interface-blockwithouttransactiondatarpc) | block to unmarshall | - -**Returns:** *`BlockWithoutTransactionData`* - -unmarshalled block without transaction data - -#### unmarshalLog - -▸ **unmarshalLog**(`rawLog`: `RawLogEntry`): *`LogEntry`* - -*Defined in [web3-wrapper/src/marshaller.ts:199](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/marshaller.ts#L199)* - -Unmarshall log - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`rawLog` | `RawLogEntry` | log to unmarshall | - -**Returns:** *`LogEntry`* - -unmarshalled log - -#### unmarshalTransaction - -▸ **unmarshalTransaction**(`txRpc`: [TransactionRPC](#interface-transactionrpc)): *`Transaction`* - -*Defined in [web3-wrapper/src/marshaller.ts:82](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/marshaller.ts#L82)* - -Unmarshall transaction - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`txRpc` | [TransactionRPC](#interface-transactionrpc) | transaction to unmarshall | - -**Returns:** *`Transaction`* - -unmarshalled transaction - -#### unmarshalTransactionReceipt - -▸ **unmarshalTransactionReceipt**(`txReceiptRpc`: [TransactionReceiptRPC](#interface-transactionreceiptrpc)): *`TransactionReceipt`* - -*Defined in [web3-wrapper/src/marshaller.ts:99](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/marshaller.ts#L99)* - -Unmarshall transaction receipt - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`txReceiptRpc` | [TransactionReceiptRPC](#interface-transactionreceiptrpc) | transaction receipt to unmarshall | - -**Returns:** *`TransactionReceipt`* - -unmarshalled transaction receipt - -#### unmarshalTxData - -▸ **unmarshalTxData**(`txDataRpc`: [TxDataRPC](#interface-txdatarpc)): *`TxData`* - -*Defined in [web3-wrapper/src/marshaller.ts:115](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/web3-wrapper/src/marshaller.ts#L115)* - -Unmarshall transaction data - -**Parameters:** - -Name | Type | Description | ------- | ------ | ------ | -`txDataRpc` | [TxDataRPC](#interface-txdatarpc) | transaction data to unmarshall | - -**Returns:** *`TxData`* - -unmarshalled transaction data - -
- diff --git a/packages/web3-wrapper/package.json b/packages/web3-wrapper/package.json deleted file mode 100644 index b8bec36914..0000000000 --- a/packages/web3-wrapper/package.json +++ /dev/null @@ -1,74 +0,0 @@ -{ - "name": "@0x/web3-wrapper", - "version": "7.2.0", - "engines": { - "node": ">=6.12" - }, - "description": "Wraps around web3 and gives a nicer interface", - "main": "lib/src/index.js", - "types": "lib/src/index.d.ts", - "scripts": { - "build": "tsc -b", - "build:ci": "yarn build", - "watch_without_deps": "tsc -w", - "clean": "shx rm -rf lib generated_docs", - "lint": "tslint --format stylish --project .", - "fix": "tslint --fix --format stylish --project .", - "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", - "diff_docs": "git diff --exit-code ./docs", - "docs:md": "ts-doc-gen --sourceDir='$PROJECT_FILES' --output=$MD_FILE_DIR --fileExtension=mdx --tsconfig=./typedoc-tsconfig.json", - "docs:json": "typedoc --excludePrivate --excludeExternals --excludeProtected --ignoreCompilerErrors --target ES5 --tsconfig typedoc-tsconfig.json --json $JSON_FILE_PATH $PROJECT_FILES" - }, - "config": { - "postpublish": { - "assets": [] - } - }, - "license": "Apache-2.0", - "repository": { - "type": "git", - "url": "https://github.com/0xProject/0x-monorepo.git" - }, - "bugs": { - "url": "https://github.com/0xProject/0x-monorepo/issues" - }, - "homepage": "https://github.com/0xProject/0x-monorepo/packages/web3-wrapper/README.md", - "devDependencies": { - "@0x/ts-doc-gen": "^0.0.22", - "@0x/tslint-config": "^4.1.0", - "@types/lodash": "4.14.104", - "@types/mocha": "^5.2.7", - "chai": "^4.0.1", - "chai-as-promised": "^7.1.0", - "chai-bignumber": "^3.0.0", - "dirty-chai": "^2.0.1", - "ganache-core": "^2.10.2", - "make-promises-safe": "^1.1.0", - "mocha": "^6.2.0", - "npm-run-all": "^4.1.2", - "nyc": "^11.0.1", - "shx": "^0.2.2", - "tslint": "5.11.0", - "typedoc": "^0.15.0", - "typescript": "3.0.1" - }, - "dependencies": { - "@0x/assert": "^3.0.9", - "@0x/json-schemas": "^5.1.0", - "@0x/typescript-typings": "^5.1.1", - "@0x/utils": "^5.5.1", - "ethereum-types": "^3.2.0", - "ethereumjs-util": "^5.1.1", - "ethers": "~4.0.4", - "lodash": "^4.17.11" - }, - "publishConfig": { - "access": "public" - }, - "gitHead": "4f91bfd907996b2f4dd383778b50c479c2602b56" -} diff --git a/packages/web3-wrapper/src/globals.d.ts b/packages/web3-wrapper/src/globals.d.ts deleted file mode 100644 index 94e63a32de..0000000000 --- a/packages/web3-wrapper/src/globals.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -declare module '*.json' { - const json: any; - /* tslint:disable */ - export default json; - /* tslint:enable */ -} diff --git a/packages/web3-wrapper/src/index.ts b/packages/web3-wrapper/src/index.ts deleted file mode 100644 index 44ee3daf55..0000000000 --- a/packages/web3-wrapper/src/index.ts +++ /dev/null @@ -1,72 +0,0 @@ -export { Web3Wrapper } from './web3_wrapper'; -export { marshaller } from './marshaller'; - -export { AbiDecoder, DecodedCalldata } from '@0x/utils'; - -export { - BlockParam, - TxData, - SupportedProvider, - TransactionReceipt, - Transaction, - TraceParams, - TransactionTrace, - BlockWithoutTransactionData, - LogEntry, - FilterObject, - CallData, - GethCallOverrides, - TransactionReceiptWithDecodedLogs, - BlockWithTransactionData, - LogTopic, - JSONRPCRequestPayload, - TransactionReceiptStatus, - DecodedLogArgs, - StructLog, - BlockParamLiteral, - ContractEventArg, - DecodedLogEntry, - LogEntryEvent, - OpCode, - TxDataPayable, - JSONRPCErrorCallback, - JSONRPCResponsePayload, - JSONRPCResponseError, - RawLogEntry, - DecodedLogEntryEvent, - LogWithDecodedArgs, - AbiDefinition, - RawLog, - FunctionAbi, - EventAbi, - EventParameter, - MethodAbi, - ConstructorAbi, - FallbackAbi, - DataItem, - TupleDataItem, - ConstructorStateMutability, - StateMutability, - Web3JsProvider, - GanacheProvider, - EIP1193Provider, - ZeroExProvider, - EIP1193Event, - Web3JsV1Provider, - Web3JsV2Provider, - Web3JsV3Provider, - RevertErrorAbi, -} from 'ethereum-types'; -export { - Web3WrapperErrors, - NodeType, - CallDataRPC, - GethCallOverridesRPC, - BlockWithoutTransactionDataRPC, - BlockWithTransactionDataRPC, - TransactionReceiptStatusRPC, - TransactionReceiptRPC, - LogEntryRPC, - TransactionRPC, - TxDataRPC, -} from './types'; diff --git a/packages/web3-wrapper/src/marshaller.ts b/packages/web3-wrapper/src/marshaller.ts deleted file mode 100644 index 8e6db237a6..0000000000 --- a/packages/web3-wrapper/src/marshaller.ts +++ /dev/null @@ -1,255 +0,0 @@ -import { addressUtils } from '@0x/utils'; -import { - BlockParam, - BlockParamLiteral, - BlockWithoutTransactionData, - BlockWithTransactionData, - CallData, - CallTxDataBase, - GethCallOverrides, - LogEntry, - RawLogEntry, - Transaction, - TransactionReceipt, - TxData, -} from 'ethereum-types'; -import ethUtil = require('ethereumjs-util'); -import * as _ from 'lodash'; - -import { - BlockWithoutTransactionDataRPC, - BlockWithTransactionDataRPC, - CallDataRPC, - CallTxDataBaseRPC, - GethCallOverridesRPC, - TransactionReceiptRPC, - TransactionRPC, - TxDataRPC, -} from './types'; -import { utils } from './utils'; - -/** - * Utils to convert ethereum structures from user-space format to RPC format. (marshall/unmarshall) - */ -export const marshaller = { - /** - * Unmarshall block without transaction data - * @param blockWithHexValues block to unmarshall - * @return unmarshalled block without transaction data - */ - unmarshalIntoBlockWithoutTransactionData( - blockWithHexValues: BlockWithoutTransactionDataRPC, - ): BlockWithoutTransactionData { - const block = { - ...blockWithHexValues, - gasLimit: utils.convertHexToNumber(blockWithHexValues.gasLimit), - gasUsed: utils.convertHexToNumber(blockWithHexValues.gasUsed), - size: utils.convertHexToNumber(blockWithHexValues.size), - timestamp: utils.convertHexToNumber(blockWithHexValues.timestamp), - number: blockWithHexValues.number === null ? null : utils.convertHexToNumber(blockWithHexValues.number), - difficulty: utils.convertAmountToBigNumber(blockWithHexValues.difficulty), - totalDifficulty: utils.convertAmountToBigNumber(blockWithHexValues.totalDifficulty), - }; - return block; - }, - /** - * Unmarshall block with transaction data - * @param blockWithHexValues block to unmarshall - * @return unmarshalled block with transaction data - */ - unmarshalIntoBlockWithTransactionData(blockWithHexValues: BlockWithTransactionDataRPC): BlockWithTransactionData { - const block = { - ...blockWithHexValues, - gasLimit: utils.convertHexToNumber(blockWithHexValues.gasLimit), - gasUsed: utils.convertHexToNumber(blockWithHexValues.gasUsed), - size: utils.convertHexToNumber(blockWithHexValues.size), - timestamp: utils.convertHexToNumber(blockWithHexValues.timestamp), - number: blockWithHexValues.number === null ? null : utils.convertHexToNumber(blockWithHexValues.number), - difficulty: utils.convertAmountToBigNumber(blockWithHexValues.difficulty), - totalDifficulty: utils.convertAmountToBigNumber(blockWithHexValues.totalDifficulty), - transactions: [] as Transaction[], - }; - block.transactions = _.map(blockWithHexValues.transactions, (tx: TransactionRPC) => { - const transaction = marshaller.unmarshalTransaction(tx); - return transaction; - }); - return block; - }, - /** - * Unmarshall transaction - * @param txRpc transaction to unmarshall - * @return unmarshalled transaction - */ - unmarshalTransaction(txRpc: TransactionRPC): Transaction { - const tx = { - ...txRpc, - blockNumber: txRpc.blockNumber !== null ? utils.convertHexToNumber(txRpc.blockNumber) : null, - transactionIndex: txRpc.transactionIndex !== null ? utils.convertHexToNumber(txRpc.transactionIndex) : null, - nonce: utils.convertHexToNumber(txRpc.nonce), - gas: utils.convertHexToNumber(txRpc.gas), - gasPrice: utils.convertAmountToBigNumber(txRpc.gasPrice), - value: utils.convertAmountToBigNumber(txRpc.value), - }; - return tx; - }, - /** - * Unmarshall transaction receipt - * @param txReceiptRpc transaction receipt to unmarshall - * @return unmarshalled transaction receipt - */ - unmarshalTransactionReceipt(txReceiptRpc: TransactionReceiptRPC): TransactionReceipt { - const txReceipt = { - ...txReceiptRpc, - blockNumber: utils.convertHexToNumber(txReceiptRpc.blockNumber), - transactionIndex: utils.convertHexToNumber(txReceiptRpc.transactionIndex), - cumulativeGasUsed: utils.convertHexToNumber(txReceiptRpc.cumulativeGasUsed), - gasUsed: utils.convertHexToNumber(txReceiptRpc.gasUsed), - logs: _.map(txReceiptRpc.logs, marshaller.unmarshalLog.bind(marshaller)), - }; - return txReceipt; - }, - /** - * Unmarshall transaction data - * @param txDataRpc transaction data to unmarshall - * @return unmarshalled transaction data - */ - unmarshalTxData(txDataRpc: TxDataRPC): TxData { - if (txDataRpc.from === undefined) { - throw new Error(`txData must include valid 'from' value.`); - } - const txData = { - ...txDataRpc, - value: txDataRpc.value !== undefined ? utils.convertAmountToBigNumber(txDataRpc.value) : undefined, - gas: txDataRpc.gas !== undefined ? utils.convertHexToNumber(txDataRpc.gas) : undefined, - gasPrice: txDataRpc.gasPrice !== undefined ? utils.convertAmountToBigNumber(txDataRpc.gasPrice) : undefined, - nonce: txDataRpc.nonce !== undefined ? utils.convertHexToNumber(txDataRpc.nonce) : undefined, - }; - return txData; - }, - /** - * Marshall transaction data - * @param txData transaction data to marshall - * @return marshalled transaction data - */ - marshalTxData(txData: Partial): Partial { - if (txData.from === undefined) { - throw new Error(`txData must include valid 'from' value.`); - } - const callTxDataBase = { - ...txData, - }; - delete callTxDataBase.from; - const callTxDataBaseRPC = marshaller._marshalCallTxDataBase(callTxDataBase); - const txDataRPC = { - ...callTxDataBaseRPC, - from: marshaller.marshalAddress(txData.from), - }; - const prunableIfUndefined = ['gasPrice', 'gas', 'value', 'nonce']; - _.each(txDataRPC, (value: any, key: string) => { - if (value === undefined && _.includes(prunableIfUndefined, key)) { - delete (txDataRPC as any)[key]; - } - }); - return txDataRPC; - }, - /** - * Marshall call data - * @param callData call data to marshall - * @return marshalled call data - */ - marshalCallData(callData: Partial): Partial { - const callTxDataBase = { - ...callData, - }; - delete callTxDataBase.from; - delete callTxDataBase.overrides; - const callTxDataBaseRPC = marshaller._marshalCallTxDataBase(callTxDataBase); - const callDataRPC = { - ...callTxDataBaseRPC, - from: callData.from === undefined ? undefined : marshaller.marshalAddress(callData.from), - }; - return callDataRPC; - }, - /** - * Marshall call overrides parameter for for a geth eth_call. - * @param overrides overrides to marshal - * @return marshalled overrides - */ - marshalCallOverrides(overrides: GethCallOverrides): GethCallOverridesRPC { - const marshalled: GethCallOverridesRPC = {}; - for (const address in overrides) { - if (address) { - const override = overrides[address]; - const marshalledAddress = marshaller.marshalAddress(address); - const marshalledOverride: GethCallOverridesRPC[keyof GethCallOverridesRPC] = (marshalled[ - marshalledAddress - ] = {}); - if (override.code !== undefined) { - marshalledOverride.code = override.code; - } - if (override.nonce !== undefined) { - marshalledOverride.nonce = utils.encodeAmountAsHexString(override.nonce); - } - if (override.balance !== undefined) { - marshalledOverride.balance = utils.encodeAmountAsHexString(override.balance); - } - if (Object.keys(marshalledOverride).length === 0) { - delete marshalled[marshalledAddress]; - } - } - } - return marshalled; - }, - /** - * Marshall address - * @param address address to marshall - * @return marshalled address - */ - marshalAddress(address: string): string { - if (addressUtils.isAddress(address)) { - return ethUtil.addHexPrefix(address); - } - throw new Error(`Invalid address encountered: ${address}`); - }, - /** - * Marshall block param - * @param blockParam block param to marshall - * @return marshalled block param - */ - marshalBlockParam(blockParam: BlockParam | string | number | undefined): string | undefined { - if (blockParam === undefined) { - return BlockParamLiteral.Latest; - } - const encodedBlockParam = _.isNumber(blockParam) ? utils.numberToHex(blockParam) : blockParam; - return encodedBlockParam; - }, - /** - * Unmarshall log - * @param rawLog log to unmarshall - * @return unmarshalled log - */ - unmarshalLog(rawLog: RawLogEntry): LogEntry { - const formattedLog = { - ...rawLog, - logIndex: utils.convertHexToNumberOrNull(rawLog.logIndex), - blockNumber: utils.convertHexToNumberOrNull(rawLog.blockNumber), - transactionIndex: utils.convertHexToNumberOrNull(rawLog.transactionIndex), - }; - return formattedLog; - }, - _marshalCallTxDataBase(callTxDataBase: Partial): Partial { - const callTxDataBaseRPC = { - ...callTxDataBase, - to: callTxDataBase.to === undefined ? undefined : marshaller.marshalAddress(callTxDataBase.to), - gasPrice: - callTxDataBase.gasPrice === undefined - ? undefined - : utils.encodeAmountAsHexString(callTxDataBase.gasPrice), - gas: callTxDataBase.gas === undefined ? undefined : utils.encodeAmountAsHexString(callTxDataBase.gas), - value: callTxDataBase.value === undefined ? undefined : utils.encodeAmountAsHexString(callTxDataBase.value), - nonce: callTxDataBase.nonce === undefined ? undefined : utils.encodeAmountAsHexString(callTxDataBase.nonce), - }; - - return callTxDataBaseRPC; - }, -}; diff --git a/packages/web3-wrapper/src/types.ts b/packages/web3-wrapper/src/types.ts deleted file mode 100644 index 5c90bc17f3..0000000000 --- a/packages/web3-wrapper/src/types.ts +++ /dev/null @@ -1,100 +0,0 @@ -export enum Web3WrapperErrors { - TransactionMiningTimeout = 'TRANSACTION_MINING_TIMEOUT', -} - -export interface AbstractBlockRPC { - number: string | null; - hash: string | null; - parentHash: string; - nonce: string | null; - sha3Uncles: string; - logsBloom: string | null; - transactionsRoot: string; - stateRoot: string; - miner: string; - difficulty: string; - totalDifficulty: string; - extraData: string; - size: string; - gasLimit: string; - gasUsed: string; - timestamp: string; - uncles: string[]; -} -export interface BlockWithoutTransactionDataRPC extends AbstractBlockRPC { - transactions: string[]; -} -export interface BlockWithTransactionDataRPC extends AbstractBlockRPC { - transactions: TransactionRPC[]; -} -export interface TransactionRPC { - hash: string; - nonce: string; - blockHash: string | null; - blockNumber: string | null; - transactionIndex: string | null; - from: string; - to: string | null; - value: string; - gasPrice: string; - gas: string; - input: string; -} - -export interface TransactionReceiptRPC { - blockHash: string; - blockNumber: string; - transactionHash: string; - transactionIndex: string; - from: string; - to: string; - status: TransactionReceiptStatusRPC; - cumulativeGasUsed: string; - gasUsed: string; - contractAddress: string | null; - logs: LogEntryRPC[]; -} - -export interface LogEntryRPC { - logIndex: string | null; - transactionIndex: string | null; - transactionHash: string; - blockHash: string | null; - blockNumber: string | null; - address: string; - data: string; - topics: string[]; -} - -export type TransactionReceiptStatusRPC = null | string | 0 | 1; - -export interface CallTxDataBaseRPC { - to?: string; - value?: string; - gas?: string; - gasPrice?: string; - data?: string; - nonce?: string; -} - -export interface TxDataRPC extends CallTxDataBaseRPC { - from: string; -} - -export interface CallDataRPC extends CallTxDataBaseRPC { - from?: string; -} - -export interface GethCallOverridesRPC { - [address: string]: { - code?: string; - nonce?: string; - balance?: string; - }; -} - -// NodeType represents the type of the backing Ethereum node. -export enum NodeType { - Geth = 'GETH', - Ganache = 'GANACHE', -} diff --git a/packages/web3-wrapper/src/utils.ts b/packages/web3-wrapper/src/utils.ts deleted file mode 100644 index d0962ceab7..0000000000 --- a/packages/web3-wrapper/src/utils.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { BigNumber } from '@0x/utils'; -import * as _ from 'lodash'; - -export const utils = { - convertHexToNumber(value: string): number { - const valueBigNumber = new BigNumber(value); - const valueNumber = valueBigNumber.toNumber(); - return valueNumber; - }, - convertHexToNumberOrNull(hex: string | null): number | null { - if (hex === null) { - return null; - } - const decimal = utils.convertHexToNumber(hex); - return decimal; - }, - convertAmountToBigNumber(value: string | number | BigNumber): BigNumber { - const num = value || 0; - const isBigNumber = BigNumber.isBigNumber(num); - if (isBigNumber) { - return num as BigNumber; - } - - if (_.isString(num) && (num.indexOf('0x') === 0 || num.indexOf('-0x') === 0)) { - return new BigNumber(num.replace('0x', ''), 16); - } - - const baseTen = 10; - return new BigNumber((num as number).toString(baseTen), baseTen); - }, - encodeAmountAsHexString(value: string | number | BigNumber): string { - const valueBigNumber = utils.convertAmountToBigNumber(value); - const hexBase = 16; - const valueHex = valueBigNumber.toString(hexBase); - - return valueBigNumber.isLessThan(0) ? `-0x${valueHex.substr(1)}` : `0x${valueHex}`; - }, - numberToHex(value: number): string { - if (!isFinite(value) && !utils.isHexStrict(value)) { - throw new Error(`Given input ${value} is not a number.`); - } - - const valueBigNumber = new BigNumber(value); - const hexBase = 16; - const result = valueBigNumber.toString(hexBase); - - return valueBigNumber.lt(0) ? `-0x${result.substr(1)}` : `0x${result}`; - }, - isHexStrict(hex: string | number): boolean { - return ( - (_.isString(hex) || _.isNumber(hex)) && /^(-)?0x[0-9a-f]*$/i.test(_.isNumber(hex) ? hex.toString() : hex) - ); - }, -}; diff --git a/packages/web3-wrapper/src/web3_wrapper.ts b/packages/web3-wrapper/src/web3_wrapper.ts deleted file mode 100644 index 8761c24c12..0000000000 --- a/packages/web3-wrapper/src/web3_wrapper.ts +++ /dev/null @@ -1,730 +0,0 @@ -import { assert } from '@0x/assert'; -import { schemas } from '@0x/json-schemas'; -import { AbiDecoder, addressUtils, BigNumber, intervalUtils, promisify, providerUtils } from '@0x/utils'; -import { - BlockParam, - BlockParamLiteral, - BlockWithoutTransactionData, - BlockWithTransactionData, - CallData, - FilterObject, - JSONRPCRequestPayload, - JSONRPCResponsePayload, - LogEntry, - RawLogEntry, - SupportedProvider, - TraceParams, - Transaction, - TransactionReceipt, - TransactionReceiptWithDecodedLogs, - TransactionTrace, - TxData, - ZeroExProvider, -} from 'ethereum-types'; -import * as _ from 'lodash'; - -import { marshaller } from './marshaller'; -import { - BlockWithoutTransactionDataRPC, - BlockWithTransactionDataRPC, - NodeType, - TransactionReceiptRPC, - TransactionRPC, - Web3WrapperErrors, -} from './types'; -import { utils } from './utils'; - -const BASE_TEN = 10; - -// These are unique identifiers contained in the response of the -// web3_clientVersion call. -const uniqueVersionIds = { - geth: 'Geth', - ganache: 'EthereumJS TestRPC', -}; - -/** - * An alternative to the Web3.js library that provides a consistent, clean, promise-based interface. - */ -export class Web3Wrapper { - /** - * Flag to check if this instance is of type Web3Wrapper - */ - public isZeroExWeb3Wrapper = true; - public abiDecoder: AbiDecoder; - private _provider: ZeroExProvider; - // Raw provider passed in. Do not use. Only here to return the unmodified provider passed in via `getProvider()` - private readonly _supportedProvider: SupportedProvider; - private readonly _callAndTxnDefaults: Partial | undefined; - private _jsonRpcRequestId: number; - /** - * Check if an address is a valid Ethereum address - * @param address Address to check - * @returns Whether the address is a valid Ethereum address - */ - public static isAddress(address: string): boolean { - return addressUtils.isAddress(address); - } - /** - * 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 aUnit = new BigNumber(BASE_TEN).pow(decimals); - const unit = amount.div(aUnit); - return unit; - } - /** - * 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 | number, decimals: number): BigNumber { - assert.isNumber('decimals', decimals); - const unit = new BigNumber(BASE_TEN).pow(decimals); - const baseUnitAmount = unit.times(amount); - const hasDecimals = baseUnitAmount.decimalPlaces() !== 0; - if (hasDecimals) { - throw new Error(`Invalid unit amount: ${amount.toString(BASE_TEN)} - Too many decimal places`); - } - return baseUnitAmount; - } - /** - * Convert an Ether amount from ETH to Wei - * @param ethAmount Amount of Ether to convert to wei - * @returns Amount in wei - */ - public static toWei(ethAmount: BigNumber): BigNumber { - assert.isBigNumber('ethAmount', ethAmount); - const ETH_DECIMALS = 18; - const balanceWei = Web3Wrapper.toBaseUnitAmount(ethAmount, ETH_DECIMALS); - return balanceWei; - } - private static _assertBlockParam(blockParam: string | BlockParam): void { - if (_.isNumber(blockParam)) { - return; - } else if (_.isString(blockParam)) { - assert.doesBelongToStringEnum('blockParam', blockParam, BlockParamLiteral); - } - } - private static _assertBlockParamOrString(blockParam: string | BlockParam): void { - try { - Web3Wrapper._assertBlockParam(blockParam); - } catch (err) { - try { - assert.isHexString('blockParam', blockParam as string); - return; - } catch (err) { - throw new Error(`Expected blockParam to be of type "string | BlockParam", encountered ${blockParam}`); - } - } - } - private static _normalizeTxReceiptStatus(status: undefined | null | string | 0 | 1): null | 0 | 1 { - // Transaction status might have four values - // undefined - Testrpc and other old clients - // null - New clients on old transactions - // number - Parity - // hex - Geth - if (_.isString(status)) { - return utils.convertHexToNumber(status) as 0 | 1; - } else if (status === undefined) { - return null; - } else { - return status; - } - } - /** - * Instantiates a new Web3Wrapper. - * @param provider The Web3 provider instance you would like the Web3Wrapper to use for interacting with - * the backing Ethereum node. - * @param callAndTxnDefaults Override Call and Txn Data defaults sent with RPC requests to the backing Ethereum node. - * @return An instance of the Web3Wrapper class. - */ - constructor(supportedProvider: SupportedProvider, callAndTxnDefaults: Partial = {}) { - this.abiDecoder = new AbiDecoder([]); - this._supportedProvider = supportedProvider; - this._provider = providerUtils.standardizeOrThrow(supportedProvider); - this._callAndTxnDefaults = callAndTxnDefaults; - this._jsonRpcRequestId = 1; - } - /** - * Get the contract defaults set to the Web3Wrapper instance - * @return CallAndTxnData defaults (e.g gas, gasPrice, nonce, etc...) - */ - public getContractDefaults(): Partial | undefined { - return this._callAndTxnDefaults; - } - /** - * Retrieve the Web3 provider - * @return Web3 provider instance - */ - public getProvider(): SupportedProvider { - return this._supportedProvider; - } - /** - * Update the used Web3 provider - * @param provider The new Web3 provider to be set - */ - public setProvider(supportedProvider: SupportedProvider): void { - const provider = providerUtils.standardizeOrThrow(supportedProvider); - this._provider = provider; - } - /** - * Check whether an address is available through the backing provider. This can be - * useful if you want to know whether a user can sign messages or transactions from - * a given Ethereum address. - * @param senderAddress Address to check availability for - * @returns Whether the address is available through the provider. - */ - public async isSenderAddressAvailableAsync(senderAddress: string): Promise { - assert.isETHAddressHex('senderAddress', senderAddress); - const addresses = await this.getAvailableAddressesAsync(); - const normalizedAddress = senderAddress.toLowerCase(); - return _.includes(addresses, normalizedAddress); - } - /** - * Fetch the backing Ethereum node's version string (e.g `MetaMask/v4.2.0`) - * @returns Ethereum node's version string - */ - public async getNodeVersionAsync(): Promise { - const nodeVersion = await this.sendRawPayloadAsync({ method: 'web3_clientVersion' }); - return nodeVersion; - } - /** - * Fetches the networkId of the backing Ethereum node - * @returns The network id - */ - public async getNetworkIdAsync(): Promise { - const networkIdStr = await this.sendRawPayloadAsync({ method: 'net_version' }); - const networkId = _.parseInt(networkIdStr); - return networkId; - } - /** - * Fetches the chainId of the backing Ethereum node - * @returns The chain id - */ - public async getChainIdAsync(): Promise { - const chainIdStr = await this.sendRawPayloadAsync({ method: 'eth_chainId' }); - const chainId = _.parseInt(chainIdStr); - return chainId; - } - /** - * Retrieves the transaction receipt for a given transaction hash if found - * @param txHash Transaction hash - * @returns The transaction receipt, including it's status (0: failed, 1: succeeded). Returns undefined if transaction not found. - */ - public async getTransactionReceiptIfExistsAsync(txHash: string): Promise { - assert.isHexString('txHash', txHash); - const transactionReceiptRpc = await this.sendRawPayloadAsync({ - method: 'eth_getTransactionReceipt', - params: [txHash], - }); - // HACK Parity can return a pending transaction receipt. We check for a non null - // block number before continuing with returning a fully realised receipt. - // ref: https://github.com/paritytech/parity-ethereum/issues/1180 - if (transactionReceiptRpc !== null && transactionReceiptRpc.blockNumber !== null) { - transactionReceiptRpc.status = Web3Wrapper._normalizeTxReceiptStatus(transactionReceiptRpc.status); - const transactionReceipt = marshaller.unmarshalTransactionReceipt(transactionReceiptRpc); - return transactionReceipt; - } else { - return undefined; - } - } - /** - * Retrieves the transaction data for a given transaction - * @param txHash Transaction hash - * @returns The raw transaction data - */ - public async getTransactionByHashAsync(txHash: string): Promise { - assert.isHexString('txHash', txHash); - const transactionRpc = await this.sendRawPayloadAsync({ - method: 'eth_getTransactionByHash', - params: [txHash], - }); - const transaction = marshaller.unmarshalTransaction(transactionRpc); - return transaction; - } - /** - * Retrieves an accounts Ether balance in wei - * @param owner Account whose balance you wish to check - * @param defaultBlock The block depth at which to fetch the balance (default=latest) - * @returns Balance in wei - */ - public async getBalanceInWeiAsync(owner: string, defaultBlock?: BlockParam): Promise { - assert.isETHAddressHex('owner', owner); - if (defaultBlock !== undefined) { - Web3Wrapper._assertBlockParam(defaultBlock); - } - const marshalledDefaultBlock = marshaller.marshalBlockParam(defaultBlock); - const encodedOwner = marshaller.marshalAddress(owner); - const balanceInWei = await this.sendRawPayloadAsync({ - method: 'eth_getBalance', - params: [encodedOwner, marshalledDefaultBlock], - }); - // Rewrap in a new BigNumber - return new BigNumber(balanceInWei); - } - /** - * Check if a contract exists at a given address - * @param address Address to which to check - * @returns Whether or not contract code was found at the supplied address - */ - public async doesContractExistAtAddressAsync(address: string): Promise { - assert.isETHAddressHex('address', address); - const code = await this.getContractCodeAsync(address); - // Regex matches 0x0, 0x00, 0x in order to accommodate poorly implemented clients - const isCodeEmpty = /^0x0{0,40}$/i.test(code); - return !isCodeEmpty; - } - /** - * Gets the contract code by address - * @param address Address of the contract - * @param defaultBlock Block height at which to make the call. Defaults to `latest` - * @return Code of the contract - */ - public async getContractCodeAsync(address: string, defaultBlock?: BlockParam): Promise { - assert.isETHAddressHex('address', address); - if (defaultBlock !== undefined) { - Web3Wrapper._assertBlockParam(defaultBlock); - } - const marshalledDefaultBlock = marshaller.marshalBlockParam(defaultBlock); - const encodedAddress = marshaller.marshalAddress(address); - const code = await this.sendRawPayloadAsync({ - method: 'eth_getCode', - params: [encodedAddress, marshalledDefaultBlock], - }); - return code; - } - /** - * Gets the debug trace of a transaction - * @param txHash Hash of the transactuon to get a trace for - * @param traceParams Config object allowing you to specify if you need memory/storage/stack traces. - * @return Transaction trace - */ - public async getTransactionTraceAsync(txHash: string, traceParams: TraceParams): Promise { - assert.isHexString('txHash', txHash); - const trace = await this.sendRawPayloadAsync({ - method: 'debug_traceTransaction', - params: [txHash, traceParams], - }); - return trace; - } - /** - * Sign a message with a specific address's private key (`eth_sign`) - * @param address Address of signer - * @param message Message to sign - * @returns Signature string (might be VRS or RSV depending on the Signer) - */ - public async signMessageAsync(address: string, message: string): Promise { - assert.isETHAddressHex('address', address); - assert.isString('message', message); // TODO: Should this be stricter? Hex string? - const signData = await this.sendRawPayloadAsync({ - method: 'eth_sign', - params: [address, message], - }); - return signData; - } - /** - * Sign an EIP712 typed data message with a specific address's private key (`eth_signTypedData`) - * @param address Address of signer - * @param typedData Typed data message to sign - * @returns Signature string (as RSV) - */ - public async signTypedDataAsync(address: string, typedData: any): Promise { - assert.isETHAddressHex('address', address); - assert.doesConformToSchema('typedData', typedData, schemas.eip712TypedDataSchema); - const signData = await this.sendRawPayloadAsync({ - method: 'eth_signTypedData', - params: [address, typedData], - }); - return signData; - } - /** - * Fetches the latest block number - * @returns Block number - */ - public async getBlockNumberAsync(): Promise { - const blockNumberHex = await this.sendRawPayloadAsync({ - method: 'eth_blockNumber', - params: [], - }); - const blockNumber = utils.convertHexToNumberOrNull(blockNumberHex); - return blockNumber as number; - } - /** - * Fetches the nonce for an account (transaction count for EOAs). - * @param address Address of account. - * @param defaultBlock Block height at which to make the call. Defaults to `latest` - * @returns Account nonce. - */ - public async getAccountNonceAsync(address: string, defaultBlock?: BlockParam): Promise { - assert.isETHAddressHex('address', address); - if (defaultBlock !== undefined) { - Web3Wrapper._assertBlockParam(defaultBlock); - } - const marshalledDefaultBlock = marshaller.marshalBlockParam(defaultBlock); - const encodedAddress = marshaller.marshalAddress(address); - const nonceHex = await this.sendRawPayloadAsync({ - method: 'eth_getTransactionCount', - params: [encodedAddress, marshalledDefaultBlock], - }); - assert.isHexString('nonce', nonceHex); - // tslint:disable-next-line:custom-no-magic-numbers - return parseInt(nonceHex.substr(2), 16); - } - /** - * Fetch a specific Ethereum block without transaction data - * @param blockParam The block you wish to fetch (blockHash, blockNumber or blockLiteral) - * @returns The requested block without transaction data, or undefined if block was not found - * (e.g the node isn't fully synced, there was a block re-org and the requested block was uncles, etc...) - */ - public async getBlockIfExistsAsync( - blockParam: string | BlockParam, - ): Promise { - Web3Wrapper._assertBlockParamOrString(blockParam); - const encodedBlockParam = marshaller.marshalBlockParam(blockParam); - const method = utils.isHexStrict(blockParam) ? 'eth_getBlockByHash' : 'eth_getBlockByNumber'; - const shouldIncludeTransactionData = false; - const blockWithoutTransactionDataWithHexValuesOrNull = await this.sendRawPayloadAsync< - BlockWithoutTransactionDataRPC - >({ - method, - params: [encodedBlockParam, shouldIncludeTransactionData], - }); - let blockWithoutTransactionDataIfExists; - if (blockWithoutTransactionDataWithHexValuesOrNull !== null) { - blockWithoutTransactionDataIfExists = marshaller.unmarshalIntoBlockWithoutTransactionData( - blockWithoutTransactionDataWithHexValuesOrNull, - ); - } - return blockWithoutTransactionDataIfExists; - } - /** - * Fetch a specific Ethereum block with transaction data - * @param blockParam The block you wish to fetch (blockHash, blockNumber or blockLiteral) - * @returns The requested block with transaction data - */ - public async getBlockWithTransactionDataAsync(blockParam: string | BlockParam): Promise { - Web3Wrapper._assertBlockParamOrString(blockParam); - let encodedBlockParam = blockParam; - if (_.isNumber(blockParam)) { - encodedBlockParam = utils.numberToHex(blockParam); - } - const method = utils.isHexStrict(blockParam) ? 'eth_getBlockByHash' : 'eth_getBlockByNumber'; - const shouldIncludeTransactionData = true; - const blockWithTransactionDataWithHexValues = await this.sendRawPayloadAsync({ - method, - params: [encodedBlockParam, shouldIncludeTransactionData], - }); - const blockWithoutTransactionData = marshaller.unmarshalIntoBlockWithTransactionData( - blockWithTransactionDataWithHexValues, - ); - return blockWithoutTransactionData; - } - /** - * Fetch a block's timestamp - * @param blockParam The block you wish to fetch (blockHash, blockNumber or blockLiteral) - * @returns The block's timestamp - */ - public async getBlockTimestampAsync(blockParam: string | BlockParam): Promise { - Web3Wrapper._assertBlockParamOrString(blockParam); - const blockIfExists = await this.getBlockIfExistsAsync(blockParam); - if (blockIfExists === undefined) { - throw new Error(`Failed to fetch block with blockParam: ${JSON.stringify(blockParam)}`); - } - return blockIfExists.timestamp; - } - /** - * Retrieve the user addresses available through the backing provider - * @returns Available user addresses - */ - public async getAvailableAddressesAsync(): Promise { - const addresses = await this.sendRawPayloadAsync({ - method: 'eth_accounts', - params: [], - }); - const normalizedAddresses = _.map(addresses, address => address.toLowerCase()); - return normalizedAddresses; - } - /** - * Take a snapshot of the blockchain state on a TestRPC/Ganache local node - * @returns The snapshot id. This can be used to revert to this snapshot - */ - public async takeSnapshotAsync(): Promise { - const snapshotId = Number(await this.sendRawPayloadAsync({ method: 'evm_snapshot', params: [] })); - return snapshotId; - } - /** - * Revert the blockchain state to a previous snapshot state on TestRPC/Ganache local node - * @param snapshotId snapshot id to revert to - * @returns Whether the revert was successful - */ - public async revertSnapshotAsync(snapshotId: number): Promise { - assert.isNumber('snapshotId', snapshotId); - const didRevert = await this.sendRawPayloadAsync({ method: 'evm_revert', params: [snapshotId] }); - return didRevert; - } - /** - * Mine a block on a TestRPC/Ganache local node - */ - public async mineBlockAsync(): Promise { - await this.sendRawPayloadAsync({ method: 'evm_mine', params: [] }); - } - /** - * Increase the next blocks timestamp on TestRPC/Ganache or Geth local node. - * Will throw if provider is neither TestRPC/Ganache or Geth. - * @param timeDelta Amount of time to add in seconds - */ - public async increaseTimeAsync(timeDelta: number): Promise { - assert.isNumber('timeDelta', timeDelta); - // Detect Geth vs. Ganache and use appropriate endpoint. - const version = await this.getNodeVersionAsync(); - if (_.includes(version, uniqueVersionIds.geth)) { - return this.sendRawPayloadAsync({ method: 'debug_increaseTime', params: [timeDelta] }); - } else if (_.includes(version, uniqueVersionIds.ganache)) { - return this.sendRawPayloadAsync({ method: 'evm_increaseTime', params: [timeDelta] }); - } else { - throw new Error(`Unknown client version: ${version}`); - } - } - /** - * Retrieve smart contract logs for a given filter - * @param filter Parameters by which to filter which logs to retrieve - * @returns The corresponding log entries - */ - public async getLogsAsync(filter: FilterObject): Promise { - if (filter.blockHash !== undefined && (filter.fromBlock !== undefined || filter.toBlock !== undefined)) { - throw new Error( - `Cannot specify 'blockHash' as well as 'fromBlock'/'toBlock' in the filter supplied to 'getLogsAsync'`, - ); - } - - let fromBlock = filter.fromBlock; - if (_.isNumber(fromBlock)) { - fromBlock = utils.numberToHex(fromBlock); - } - let toBlock = filter.toBlock; - if (_.isNumber(toBlock)) { - toBlock = utils.numberToHex(toBlock); - } - const serializedFilter = { - ...filter, - fromBlock, - toBlock, - }; - const payload = { - method: 'eth_getLogs', - params: [serializedFilter], - }; - const rawLogs = await this.sendRawPayloadAsync(payload); - const formattedLogs = _.map(rawLogs, marshaller.unmarshalLog.bind(marshaller)); - return formattedLogs; - } - /** - * Calculate the estimated gas cost for a given transaction - * @param txData Transaction data - * @returns Estimated gas cost - */ - public async estimateGasAsync(txData: Partial): Promise { - assert.doesConformToSchema('txData', txData, schemas.txDataSchema, [ - schemas.addressSchema, - schemas.numberSchema, - schemas.jsNumber, - ]); - const txDataHex = marshaller.marshalTxData(txData); - const gasHex = await this.sendRawPayloadAsync({ method: 'eth_estimateGas', params: [txDataHex] }); - const gas = utils.convertHexToNumber(gasHex); - return gas; - } - /** - * Call a smart contract method at a given block height - * @param callData Call data - * @param defaultBlock Block height at which to make the call. Defaults to `latest` - * @returns The raw call result - */ - public async callAsync(callData: CallData, defaultBlock?: BlockParam): Promise { - assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ - schemas.addressSchema, - schemas.numberSchema, - schemas.jsNumber, - ]); - if (defaultBlock !== undefined) { - Web3Wrapper._assertBlockParam(defaultBlock); - } - const marshalledDefaultBlock = marshaller.marshalBlockParam(defaultBlock); - const callDataHex = marshaller.marshalCallData(callData); - const overrides = marshaller.marshalCallOverrides(callData.overrides || {}); - const rawCallResult = await this.sendRawPayloadAsync({ - method: 'eth_call', - params: [callDataHex, marshalledDefaultBlock, ...(Object.keys(overrides).length === 0 ? [] : [overrides])], - }); - return rawCallResult; - } - /** - * Send a transaction - * @param txData Transaction data - * @returns Transaction hash - */ - public async sendTransactionAsync(txData: TxData): Promise { - assert.doesConformToSchema('txData', txData, schemas.txDataSchema, [ - schemas.addressSchema, - schemas.numberSchema, - schemas.jsNumber, - ]); - const txDataHex = marshaller.marshalTxData(txData); - const txHash = await this.sendRawPayloadAsync({ method: 'eth_sendTransaction', params: [txDataHex] }); - return txHash; - } - /** - * Waits for a transaction to be mined and returns the transaction receipt. - * Note that just because a transaction was mined does not mean it was - * successful. You need to check the status code of the transaction receipt - * to find out if it was successful, or use the helper method - * awaitTransactionSuccessAsync. - * @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 { - assert.isHexString('txHash', txHash); - assert.isNumber('pollingIntervalMs', pollingIntervalMs); - if (timeoutMs !== undefined) { - assert.isNumber('timeoutMs', timeoutMs); - } - // Immediately check if the transaction has already been mined. - let transactionReceipt = await this.getTransactionReceiptIfExistsAsync(txHash); - if (transactionReceipt !== undefined) { - const logsWithDecodedArgs = _.map( - transactionReceipt.logs, - this.abiDecoder.tryToDecodeLogOrNoop.bind(this.abiDecoder), - ); - const transactionReceiptWithDecodedLogArgs: TransactionReceiptWithDecodedLogs = { - ...transactionReceipt, - logs: logsWithDecodedArgs, - }; - return transactionReceiptWithDecodedLogArgs; - } - - // Otherwise, check again every pollingIntervalMs. - let wasTimeoutExceeded = false; - if (timeoutMs) { - setTimeout(() => (wasTimeoutExceeded = true), timeoutMs); - } - - const txReceiptPromise = new Promise( - (resolve: (receipt: TransactionReceiptWithDecodedLogs) => void, reject) => { - const intervalId = intervalUtils.setAsyncExcludingInterval( - async () => { - if (wasTimeoutExceeded) { - intervalUtils.clearAsyncExcludingInterval(intervalId); - return reject(Web3WrapperErrors.TransactionMiningTimeout); - } - - transactionReceipt = await this.getTransactionReceiptIfExistsAsync(txHash); - if (transactionReceipt !== undefined) { - intervalUtils.clearAsyncExcludingInterval(intervalId); - const logsWithDecodedArgs = _.map( - transactionReceipt.logs, - this.abiDecoder.tryToDecodeLogOrNoop.bind(this.abiDecoder), - ); - const transactionReceiptWithDecodedLogArgs: TransactionReceiptWithDecodedLogs = { - ...transactionReceipt, - logs: logsWithDecodedArgs, - }; - resolve(transactionReceiptWithDecodedLogArgs); - } - }, - pollingIntervalMs, - (err: Error) => { - intervalUtils.clearAsyncExcludingInterval(intervalId); - reject(err); - }, - ); - }, - ); - const txReceipt = await txReceiptPromise; - return txReceipt; - } - /** - * Waits for a transaction to be mined and returns the transaction receipt. - * Unlike awaitTransactionMinedAsync, it will throw if the receipt has a - * status that is not equal to 1. A status of 0 or null indicates that the - * transaction was mined, but failed. See: - * https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethgettransactionreceipt - * @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 awaitTransactionSuccessAsync( - txHash: string, - pollingIntervalMs: number = 1000, - timeoutMs?: number, - ): Promise { - const receipt = await this.awaitTransactionMinedAsync(txHash, pollingIntervalMs, timeoutMs); - if (receipt.status !== 1) { - throw new Error(`Transaction failed: ${txHash}`); - } - return receipt; - } - /** - * Calls the 'debug_setHead' JSON RPC method, which sets the current head of - * the local chain by block number. Note, this is a destructive action and - * may severely damage your chain. Use with extreme caution. As of now, this - * is only supported by Geth. It sill throw if the 'debug_setHead' method is - * not supported. - * @param blockNumber The block number to reset to. - */ - public async setHeadAsync(blockNumber: number): Promise { - assert.isNumber('blockNumber', blockNumber); - await this.sendRawPayloadAsync({ method: 'debug_setHead', params: [utils.numberToHex(blockNumber)] }); - } - /** - * Sends a raw Ethereum JSON RPC payload and returns the response's `result` key - * @param payload A partial JSON RPC payload. No need to include version, id, params (if none needed) - * @return The contents nested under the result key of the response body - */ - public async sendRawPayloadAsync
(payload: Partial): Promise { - const sendAsync = this._provider.sendAsync.bind(this._provider); - const payloadWithDefaults = { - id: this._jsonRpcRequestId++, - params: [], - jsonrpc: '2.0', - ...payload, - }; - const response = await promisify(sendAsync)(payloadWithDefaults); - if (response.error) { - throw new Error(response.error.message); - } - const result = response.result; - return result; - } - /** - * Returns either NodeType.Geth or NodeType.Ganache depending on the type of - * the backing Ethereum node. Throws for any other type of node. - */ - public async getNodeTypeAsync(): Promise { - const version = await this.getNodeVersionAsync(); - if (_.includes(version, uniqueVersionIds.geth)) { - return NodeType.Geth; - } else if (_.includes(version, uniqueVersionIds.ganache)) { - return NodeType.Ganache; - } else { - throw new Error(`Unknown client version: ${version}`); - } - } -} // tslint:disable-line:max-file-line-count diff --git a/packages/web3-wrapper/test/utils/chai_setup.ts b/packages/web3-wrapper/test/utils/chai_setup.ts deleted file mode 100644 index 1a87330932..0000000000 --- a/packages/web3-wrapper/test/utils/chai_setup.ts +++ /dev/null @@ -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); - }, -}; diff --git a/packages/web3-wrapper/test/web3_wrapper_test.ts b/packages/web3-wrapper/test/web3_wrapper_test.ts deleted file mode 100644 index dfb05211a0..0000000000 --- a/packages/web3-wrapper/test/web3_wrapper_test.ts +++ /dev/null @@ -1,168 +0,0 @@ -import { BigNumber } from '@0x/utils'; -import * as chai from 'chai'; -import { BlockParamLiteral, JSONRPCErrorCallback, JSONRPCRequestPayload, TransactionReceipt } from 'ethereum-types'; -import * as Ganache from 'ganache-core'; -import * as _ from 'lodash'; -import 'mocha'; - -import { Web3Wrapper } from '../src/web3_wrapper'; - -import { chaiSetup } from './utils/chai_setup'; -chaiSetup.configure(); - -const { expect } = chai; - -const NUM_GANACHE_ADDRESSES = 10; - -describe('Web3Wrapper tests', () => { - const NETWORK_ID = 50; - const provider = Ganache.provider({ network_id: NETWORK_ID }); - const web3Wrapper = new Web3Wrapper(provider); - let addresses: string[]; - before(async () => { - addresses = await web3Wrapper.getAvailableAddressesAsync(); - }); - describe('#isAddress', () => { - it('correctly checks if a string is a valid ethereum address', () => { - expect(Web3Wrapper.isAddress('0x0')).to.be.false(); - expect(Web3Wrapper.isAddress('0xdeadbeef')).to.be.false(); - expect(Web3Wrapper.isAddress('42')).to.be.false(); - expect(Web3Wrapper.isAddress('weth.thetoken.eth')).to.be.false(); - expect(Web3Wrapper.isAddress('0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2')).to.be.true(); - expect(Web3Wrapper.isAddress('0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2')).to.be.true(); - }); - }); - describe('#getNodeVersionAsync', () => { - it('gets the node version', async () => { - const nodeVersion = await web3Wrapper.getNodeVersionAsync(); - expect(nodeVersion).to.be.match(/EthereumJS TestRPC\/.+\/ethereum-js$/); - }); - }); - describe('#getNetworkIdAsync', () => { - it('gets the network id', async () => { - const networkId = await web3Wrapper.getNetworkIdAsync(); - expect(networkId).to.be.equal(NETWORK_ID); - }); - }); - describe('#getNetworkIdAsync', () => { - it('gets the network id', async () => { - const networkId = await web3Wrapper.getNetworkIdAsync(); - expect(networkId).to.be.equal(NETWORK_ID); - }); - }); - describe('#getAvailableAddressesAsync', () => { - it('gets the available addresses', async () => { - const availableAddresses = await web3Wrapper.getAvailableAddressesAsync(); - expect(availableAddresses.length).to.be.equal(NUM_GANACHE_ADDRESSES); - expect(Web3Wrapper.isAddress(availableAddresses[0])).to.equal(true); - }); - }); - describe('#getBalanceInWeiAsync', () => { - it('gets the users balance in wei', async () => { - const secondAccount = addresses[1]; - const balanceInWei = await web3Wrapper.getBalanceInWeiAsync(secondAccount); - const tenEthInWei = 100000000000000000000; - expect(balanceInWei).to.be.bignumber.equal(tenEthInWei); - }); - it('should throw if supplied owner not an Ethereum address hex string', async () => { - const invalidEthAddress = 'deadbeef'; - expect(web3Wrapper.getBalanceInWeiAsync(invalidEthAddress)).to.eventually.to.be.rejected(); - }); - }); - describe('#signMessageAsync', () => { - it('should sign message', async () => { - const message = '0xdeadbeef'; - const signer = addresses[1]; - const signature = await web3Wrapper.signMessageAsync(signer, message); - const signatureLength = 132; - expect(signature.length).to.be.equal(signatureLength); - }); - it('should throw if the provider returns an error', async () => { - const message = '0xdeadbeef'; - const signer = addresses[1]; - const fakeProvider = { - async sendAsync(payload: JSONRPCRequestPayload, callback: JSONRPCErrorCallback): Promise { - callback(new Error('User denied message signature')); - }, - }; - const errorWeb3Wrapper = new Web3Wrapper(fakeProvider); - expect(errorWeb3Wrapper.signMessageAsync(signer, message)).to.be.rejectedWith( - 'User denied message signature', - ); - }); - }); - describe('#getBlockNumberAsync', () => { - it('get block number', async () => { - const blockNumber = await web3Wrapper.getBlockNumberAsync(); - expect(typeof blockNumber).to.be.equal('number'); - }); - }); - describe('#getTransactionReceiptAsync/awaitTransactionSuccessAsync', () => { - it('get block number', async () => { - const payload = { from: addresses[0], to: addresses[1], value: 1 }; - const txHash = await web3Wrapper.sendTransactionAsync(payload); - await web3Wrapper.awaitTransactionSuccessAsync(txHash); - const receiptIfExists = await web3Wrapper.getTransactionReceiptIfExistsAsync(txHash); - expect(receiptIfExists).to.not.be.undefined(); - const receipt = receiptIfExists as TransactionReceipt; - expect(receipt.transactionIndex).to.be.a('number'); - expect(receipt.transactionHash).to.be.equal(txHash); - }); - }); - describe('#getBlockIfExistsAsync', () => { - it('gets block when supplied a valid BlockParamLiteral value', async () => { - const blockParamLiteral = BlockParamLiteral.Earliest; - const blockIfExists = await web3Wrapper.getBlockIfExistsAsync(blockParamLiteral); - if (blockIfExists === undefined) { - throw new Error('Expected block to exist'); - } - expect(blockIfExists.number).to.be.equal(0); - expect(BigNumber.isBigNumber(blockIfExists.difficulty)).to.equal(true); - expect(_.isNumber(blockIfExists.gasLimit)).to.equal(true); - }); - it('gets block when supplied a block number', async () => { - const blockParamLiteral = 0; - const blockIfExists = await web3Wrapper.getBlockIfExistsAsync(blockParamLiteral); - if (blockIfExists === undefined) { - throw new Error('Expected block to exist'); - } - expect(blockIfExists.number).to.be.equal(0); - }); - it('gets block when supplied a block hash', async () => { - const blockParamLiteral = 0; - const blockIfExists = await web3Wrapper.getBlockIfExistsAsync(blockParamLiteral); - if (blockIfExists === undefined) { - throw new Error('Expected block to exist'); - } - const sameBlockIfExists = await web3Wrapper.getBlockIfExistsAsync(blockIfExists.hash as string); - if (sameBlockIfExists === undefined) { - throw new Error('Expected block to exist'); - } - expect(sameBlockIfExists.number).to.be.equal(0); - }); - it('should throw if supplied invalid blockParam value', async () => { - const invalidBlockParam = 'deadbeef'; - expect(web3Wrapper.getBlockIfExistsAsync(invalidBlockParam)).to.eventually.to.be.rejected(); - }); - }); - describe('#getBlockWithTransactionDataAsync', () => { - it('gets block when supplied a valid BlockParamLiteral value', async () => { - const blockParamLiteral = BlockParamLiteral.Earliest; - const block = await web3Wrapper.getBlockWithTransactionDataAsync(blockParamLiteral); - expect(block.number).to.be.equal(0); - expect(BigNumber.isBigNumber(block.difficulty)).to.equal(true); - expect(_.isNumber(block.gasLimit)).to.equal(true); - }); - it('should throw if supplied invalid blockParam value', async () => { - const invalidBlockParam = 'deadbeef'; - expect(web3Wrapper.getBlockWithTransactionDataAsync(invalidBlockParam)).to.eventually.to.be.rejected(); - }); - }); - describe('#getBlockTimestampAsync', () => { - it('gets block timestamp', async () => { - const blockParamLiteral = BlockParamLiteral.Earliest; - const timestamp = await web3Wrapper.getBlockTimestampAsync(blockParamLiteral); - expect(_.isNumber(timestamp)).to.be.equal(true); - }); - }); -}); diff --git a/packages/web3-wrapper/tsconfig.json b/packages/web3-wrapper/tsconfig.json deleted file mode 100644 index 718e623c74..0000000000 --- a/packages/web3-wrapper/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../tsconfig", - "compilerOptions": { - "outDir": "lib", - "rootDir": "." - }, - "include": ["src/**/*", "test/**/*"] -} diff --git a/packages/web3-wrapper/tslint.json b/packages/web3-wrapper/tslint.json deleted file mode 100644 index dd9053357e..0000000000 --- a/packages/web3-wrapper/tslint.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": ["@0x/tslint-config"] -} diff --git a/packages/web3-wrapper/typedoc-tsconfig.json b/packages/web3-wrapper/typedoc-tsconfig.json deleted file mode 100644 index b9c6b36f30..0000000000 --- a/packages/web3-wrapper/typedoc-tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "../../typedoc-tsconfig", - "compilerOptions": { - "outDir": "lib" - }, - "include": ["src/**/*", "test/**/*"] -} diff --git a/python-packages/build_docs b/python-packages/build_docs deleted file mode 100755 index 18271a5270..0000000000 --- a/python-packages/build_docs +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env bash - -./parallel ./setup.py build_sphinx diff --git a/python-packages/cmd_pkgs_in_dep_order.py b/python-packages/cmd_pkgs_in_dep_order.py deleted file mode 100755 index 9a0f3af2a6..0000000000 --- a/python-packages/cmd_pkgs_in_dep_order.py +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env python - -"""Run a command in every package, in order of increasing dependency.""" - -import os -import subprocess -import sys - - -PACKAGE_DEPENDENCY_LIST = [ - # Order matters! Packages must be handled in dependency order (most - # independent first) in order for them to resolve properly. - "contract_addresses", - "contract_artifacts", - "json_schemas", - "order_utils", - "sra_client", - "middlewares", - "contract_wrappers", -] - -for package in PACKAGE_DEPENDENCY_LIST: - print(f"Running command `{sys.argv[1:]}` in package {package}") - os.chdir(package) - subprocess.check_call(sys.argv[1:]) - os.chdir("..") diff --git a/python-packages/contract_addresses/.discharge.json b/python-packages/contract_addresses/.discharge.json deleted file mode 100644 index d6c90a20f0..0000000000 --- a/python-packages/contract_addresses/.discharge.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "domain": "0x-contract-addresses-py", - "build_command": "python setup.py build_sphinx", - "upload_directory": "build/docs/html", - "index_key": "index.html", - "error_key": "index.html", - "trailing_slashes": true, - "cache": 3600, - "aws_profile": "default", - "aws_region": "us-east-1", - "cdn": false, - "dns_configured": true -} diff --git a/python-packages/contract_addresses/CHANGELOG.md b/python-packages/contract_addresses/CHANGELOG.md deleted file mode 100644 index ca25a4c81b..0000000000 --- a/python-packages/contract_addresses/CHANGELOG.md +++ /dev/null @@ -1,20 +0,0 @@ -# Changelog - -## 3.0.0 - 2019-12-03 - -- Addresses are now indexed by chain ID rather than by network ID. - -## 2.2.0 - 2019-08-08 - -- Added ERC1155Proxy address -- Updated addresses for AssetProxyOwner, Coordinator, CoordinatorRegistry, Forwarder, and OrderValidator. - -## 2.1.0 - 2019-07-15 - -- Added Coordinator and CoordinatorRegistry addresses. -- Expanded documentation. -- Redeployed Mainnet V2.1 Exchange et al - -## 2.0.1 - 2019-02-25 - -- Updated addresses of OrderValidator and Forwarder contracts. diff --git a/python-packages/contract_addresses/README.md b/python-packages/contract_addresses/README.md deleted file mode 100644 index d5e098deba..0000000000 --- a/python-packages/contract_addresses/README.md +++ /dev/null @@ -1,39 +0,0 @@ -## 0x-contract-addresses - -Addresses at which the 0x smart contracts have been deployed. - -Read the [documentation](http://0x-contract-addresses-py.s3-website-us-east-1.amazonaws.com/) - -## Installing - -```bash -pip install 0x-contract-addresses -``` - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install Code and Dependencies - -```bash -pip install -e .[dev] -``` - -### Clean - -`./setup.py clean --all` - -### Lint - -`./setup.py lint` - -### Build Documentation - -`./setup.py build_sphinx` - -### More - -See `./setup.py --help-commands` for more info. diff --git a/python-packages/contract_addresses/setup.py b/python-packages/contract_addresses/setup.py deleted file mode 100755 index f5686de89b..0000000000 --- a/python-packages/contract_addresses/setup.py +++ /dev/null @@ -1,229 +0,0 @@ -#!/usr/bin/env python - -"""setuptools module for contract_addresses package.""" - -# pylint: disable=import-outside-toplevel -# we import things outside of top-level because 3rd party libs may not yet be -# installed when you invoke this script - -import subprocess # nosec -from shutil import copyfile, rmtree -from os import environ, path -from sys import argv, exit # pylint: disable=redefined-builtin - -from distutils.command.clean import clean -import distutils.command.build_py -from setuptools import find_packages, setup -from setuptools.command.test import test as TestCommand - - -class PreInstallCommand(distutils.command.build_py.build_py): - """Custom setuptools command class for pulling in addresses.json.""" - - description = ( - "Pull in addresses.json from ../../packages/contract-addresses" - ) - - def run(self): - """Copy over addresses.json.""" - pkgdir = path.dirname(path.realpath(argv[0])) - - destination_path = path.join( - pkgdir, "src", "zero_ex", "contract_addresses" - ) - - copyfile( - path.join( - pkgdir, - "..", - "..", - "packages", - "contract-addresses", - "addresses.json", - ), - path.join(destination_path, "addresses.json"), - ) - - -class LintCommand(distutils.command.build_py.build_py): - """Custom setuptools command class for running linters.""" - - description = "Run linters" - - def run(self): - """Run linter shell commands.""" - lint_commands = [ - # formatter: - "black --line-length 79 --check --diff src setup.py".split(), - # style guide checker (formerly pep8): - "pycodestyle --show-source --show-pep8 src setup.py".split(), - # docstring style checker: - "pydocstyle src setup.py".split(), - # static type checker: - "mypy src setup.py".split(), - # security issue checker: - "bandit -r src ./setup.py".split(), - # general linter: - "pylint src setup.py".split(), - # pylint takes relatively long to run, so it runs last, to enable - # fast failures. - ] - - # tell mypy where to find interface stubs for 3rd party libs - environ["MYPYPATH"] = path.join( - path.dirname(path.realpath(argv[0])), "stubs" - ) - - for lint_command in lint_commands: - print( - "Running lint command `", " ".join(lint_command).strip(), "`" - ) - subprocess.check_call(lint_command) # nosec - - -class CleanCommandExtension(clean): - """Custom command to do custom cleanup.""" - - def run(self): - """Run the regular clean, followed by our custom commands.""" - super().run() - rmtree("build", ignore_errors=True) - rmtree("dist", ignore_errors=True) - rmtree(".mypy_cache", ignore_errors=True) - rmtree(".tox", ignore_errors=True) - rmtree(".pytest_cache", ignore_errors=True) - rmtree("src/0x_contract_addresses.egg-info", ignore_errors=True) - - -class TestPublishCommand(distutils.command.build_py.build_py): - """Custom command to publish to test.pypi.org.""" - - description = ( - "Publish dist/* to test.pypi.org. Run sdist & bdist_wheel first." - ) - - def run(self): - """Run twine to upload to test.pypi.org.""" - subprocess.check_call( # nosec - ( - "twine upload --repository-url https://test.pypi.org/legacy/" - + " --verbose dist/*" - ).split() - ) - - -class PublishCommand(distutils.command.build_py.build_py): - """Custom command to publish to pypi.org.""" - - description = "Publish dist/* to pypi.org. Run sdist & bdist_wheel first." - - def run(self): - """Run twine to upload to pypi.org.""" - subprocess.check_call("twine upload dist/*".split()) # nosec - - -class PublishDocsCommand(distutils.command.build_py.build_py): - """Custom command to publish docs to S3.""" - - description = ( - "Publish docs to " - + "http://0x-contract-addresses-py.s3-website-us-east-1.amazonaws.com/" - ) - - def run(self): - """Run npm package `discharge` to build & upload docs.""" - subprocess.check_call("discharge deploy".split()) # nosec - - -class TestCommandExtension(TestCommand): - """Run pytest tests.""" - - def run_tests(self): - """Invoke pytest.""" - import pytest - - exit(pytest.main(["--doctest-modules", "-rapP"])) - # show short test summary at end ^ - - -with open("README.md", "r") as file_handle: - README_MD = file_handle.read() - - -setup( - name="0x-contract-addresses", - version="3.0.0", - description="Addresses at which the 0x smart contracts have been deployed", - long_description=README_MD, - long_description_content_type="text/markdown", - url=( - "https://github.com/0xproject/0x-monorepo/tree/development" - + "/python-packages/contract_addresses" - ), - author="F. Eugene Aumson", - author_email="feuGeneA@users.noreply.github.com", - cmdclass={ - "clean": CleanCommandExtension, - "pre_install": PreInstallCommand, - "lint": LintCommand, - "test": TestCommandExtension, - "test_publish": TestPublishCommand, - "publish": PublishCommand, - "publish_docs": PublishDocsCommand, - }, - install_requires=["mypy_extensions"], - extras_require={ - "dev": [ - "bandit", - "black", - "coverage", - "coveralls", - "mypy<=0.770", # see https://github.com/python/mypy/issues/8953 - "mypy_extensions", - "pycodestyle", - "pydocstyle", - "pylint", - "pytest", - "sphinx", - "tox", - "twine", - ] - }, - python_requires=">=3.6, <4", - package_data={ - "zero_ex.contract_addresses": ["py.typed", "addresses.json"] - }, - package_dir={"": "src"}, - license="Apache 2.0", - keywords=( - "ethereum cryptocurrency 0x decentralized blockchain dex exchange" - ), - namespace_packages=["zero_ex"], - packages=find_packages("src"), - classifiers=[ - "Development Status :: 5 - Production/Stable", - "Intended Audience :: Developers", - "Intended Audience :: Financial and Insurance Industry", - "License :: OSI Approved :: Apache Software License", - "Natural Language :: English", - "Operating System :: OS Independent", - "Programming Language :: Python", - "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3.6", - "Programming Language :: Python :: 3.7", - "Topic :: Internet :: WWW/HTTP", - "Topic :: Office/Business :: Financial", - "Topic :: Other/Nonlisted Topic", - "Topic :: Security :: Cryptography", - "Topic :: Software Development :: Libraries", - "Topic :: Utilities", - ], - zip_safe=False, # required per mypy - command_options={ - "build_sphinx": { - "source_dir": ("setup.py", "src"), - "build_dir": ("setup.py", "build/docs"), - "warning_is_error": ("setup.py", "true"), - } - }, -) diff --git a/python-packages/contract_addresses/src/conf.py b/python-packages/contract_addresses/src/conf.py deleted file mode 100644 index a0f372bc5f..0000000000 --- a/python-packages/contract_addresses/src/conf.py +++ /dev/null @@ -1,54 +0,0 @@ -"""Configuration file for the Sphinx documentation builder.""" - -# Reference: http://www.sphinx-doc.org/en/master/config - -from typing import List -import pkg_resources - - -# pylint: disable=invalid-name -# because these variables are not named in upper case, as globals should be. - -project = "0x-contract-addresses" -# pylint: disable=redefined-builtin -copyright = "2018, ZeroEx, Intl." -author = "F. Eugene Aumson" -version = pkg_resources.get_distribution("0x-contract-addresses").version -release = "" # The full version, including alpha/beta/rc tags - -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.doctest", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.viewcode", -] - -templates_path = ["doc_templates"] - -source_suffix = ".rst" -# eg: source_suffix = [".rst", ".md"] - -master_doc = "index" # The master toctree document. - -language = None - -exclude_patterns: List[str] = [] - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = None - -html_theme = "alabaster" - -html_static_path = ["doc_static"] -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". - -# Output file base name for HTML help builder. -htmlhelp_basename = "contract_addressespydoc" - -# -- Extension configuration: - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = {"https://docs.python.org/": None} diff --git a/python-packages/contract_addresses/src/doc_static/.gitkeep b/python-packages/contract_addresses/src/doc_static/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_addresses/src/index.rst b/python-packages/contract_addresses/src/index.rst deleted file mode 100644 index 7b9ea29f02..0000000000 --- a/python-packages/contract_addresses/src/index.rst +++ /dev/null @@ -1,30 +0,0 @@ -.. source for the sphinx-generated build/docs/web/index.html - -Python zero_ex.contract_addresses -================================= - -.. toctree:: - :maxdepth: 2 - :caption: Contents: - -.. automodule:: zero_ex.contract_addresses - :no-members: - -.. autoclass:: zero_ex.contract_addresses.ChainId - :members: - :undoc-members: - :show-inheritance: - -.. autoclass:: zero_ex.contract_addresses.ContractAddresses - :members: - :show-inheritance: - -.. autodata:: zero_ex.contract_addresses.chain_to_addresses - :annotation: : Dict[ChainId, ContractAddresses] - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` diff --git a/python-packages/contract_addresses/src/zero_ex/__init__.py b/python-packages/contract_addresses/src/zero_ex/__init__.py deleted file mode 100644 index 3fe1300cfb..0000000000 --- a/python-packages/contract_addresses/src/zero_ex/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -"""0x Python API.""" -__import__("pkg_resources").declare_namespace(__name__) # type: ignore diff --git a/python-packages/contract_addresses/src/zero_ex/contract_addresses/__init__.py b/python-packages/contract_addresses/src/zero_ex/contract_addresses/__init__.py deleted file mode 100644 index f99153ea93..0000000000 --- a/python-packages/contract_addresses/src/zero_ex/contract_addresses/__init__.py +++ /dev/null @@ -1,153 +0,0 @@ -"""Addresses at which the 0x smart contracts have been deployed. - -Setup ------ - -Install the package with pip:: - - pip install 0x-contract-addresses - -""" - -from enum import Enum -import json -from typing import Dict, NamedTuple - -from pkg_resources import resource_string - - -class ContractAddresses(NamedTuple): - """An abstract record listing all the contracts that have addresses.""" - - erc20_proxy: str - """Address of the ERC20Proxy contract.""" - - erc721_proxy: str - """Address of the ERC721Proxy contract.""" - - zrx_token: str - """Address of the ZRX token contract.""" - - ether_token: str - """Address of the WETH token contract.""" - - exchange_v2: str - """Address of the v2 Exchange contract.""" - - exchange: str - """Address of the v3 Exchange contract.""" - - asset_proxy_owner: str - """Address of the AssetProxyOwner contract.""" - - zero_ex_governor: str - """Address of the ZeroExGovernor contract.""" - - forwarder: str - """Address of the Forwarder contract.""" - - coordinator_registry: str - """Address of the CoordinatorRegistry contract.""" - - coordinator: str - """Address of the Coordinator contract.""" - - multi_asset_proxy: str - """Address of the MultiAssetProxy contract.""" - - static_call_proxy: str - """Address of the StaticCallProxy contract.""" - - erc1155_proxy: str - """Address of the ERC1155Proxy contract.""" - - dev_utils: str - """Address of the DevUtils contract.""" - - zrx_vault: str - """Address of the ZRXVault contract.""" - - staking: str - """Address of the Staking contract.""" - - staking_proxy: str - """Address of the StakingProxy contract.""" - - erc20_bridge_proxy: str - """Address of the ERC20BridgeProxy contract.""" - - -class ChainId(Enum): - """Chain names correlated to their chain identification numbers. - - >>> ChainId.MAINNET - - - >>> ChainId.MAINNET.value - 1 - """ - - MAINNET = 1 - ROPSTEN = 3 - RINKEBY = 4 - KOVAN = 42 - GANACHE = 1337 - - -class _AddressCache: - """A cache to facilitate lazy & singular loading of contract addresses.""" - - # pylint: disable=too-few-public-methods - - # class data, not instance: - _chain_to_addresses: Dict[str, ContractAddresses] = {} - - @classmethod - def chain_to_addresses(cls, chain_id: ChainId): - """Return the addresses for the given chain ID. - - First tries to get data from the class level storage - `_chain_to_addresses`. If it's not there, loads it from disk, stores - it in the class data (for the next caller), and then returns it. - """ - try: - return cls._chain_to_addresses[str(chain_id.value)] - except KeyError: - cls._chain_to_addresses = json.loads( - resource_string("zero_ex.contract_addresses", "addresses.json") - ) - return cls._chain_to_addresses[str(chain_id.value)] - - -def chain_to_addresses(chain_id: ChainId) -> ContractAddresses: - """Map a ChainId to an instance of ContractAddresses. - - Addresses under ChainId.Ganache are from our Ganache snapshot generated - from npm package @0x/migrations. - - >>> chain_to_addresses(ChainId.MAINNET).exchange - '0x...' - """ - addresses = _AddressCache.chain_to_addresses(chain_id) - - return ContractAddresses( - erc20_proxy=addresses["erc20Proxy"], - erc721_proxy=addresses["erc721Proxy"], - zrx_token=addresses["zrxToken"], - ether_token=addresses["etherToken"], - exchange_v2=addresses["exchangeV2"], - exchange=addresses["exchange"], - asset_proxy_owner=addresses["assetProxyOwner"], - zero_ex_governor=addresses["zeroExGovernor"], - forwarder=addresses["forwarder"], - coordinator_registry=addresses["coordinatorRegistry"], - coordinator=addresses["coordinator"], - multi_asset_proxy=addresses["multiAssetProxy"], - static_call_proxy=addresses["staticCallProxy"], - erc1155_proxy=addresses["erc1155Proxy"], - dev_utils=addresses["devUtils"], - zrx_vault=addresses["zrxVault"], - staking=addresses["staking"], - staking_proxy=addresses["stakingProxy"], - erc20_bridge_proxy=addresses["erc20BridgeProxy"], - ) diff --git a/python-packages/contract_addresses/src/zero_ex/contract_addresses/py.typed b/python-packages/contract_addresses/src/zero_ex/contract_addresses/py.typed deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_addresses/stubs/distutils/__init__.pyi b/python-packages/contract_addresses/stubs/distutils/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_addresses/stubs/distutils/command/__init__.pyi b/python-packages/contract_addresses/stubs/distutils/command/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_addresses/stubs/distutils/command/clean.pyi b/python-packages/contract_addresses/stubs/distutils/command/clean.pyi deleted file mode 100644 index 46a42ddb13..0000000000 --- a/python-packages/contract_addresses/stubs/distutils/command/clean.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from distutils.core import Command - -class clean(Command): - def initialize_options(self: clean) -> None: ... - def finalize_options(self: clean) -> None: ... - def run(self: clean) -> None: ... - ... diff --git a/python-packages/contract_addresses/stubs/pytest/__init__.pyi b/python-packages/contract_addresses/stubs/pytest/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_addresses/stubs/setuptools/__init__.pyi b/python-packages/contract_addresses/stubs/setuptools/__init__.pyi deleted file mode 100644 index 8ea8d32b7e..0000000000 --- a/python-packages/contract_addresses/stubs/setuptools/__init__.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from distutils.dist import Distribution -from typing import Any, List - -def setup(**attrs: Any) -> Distribution: ... - -class Command: ... - -def find_packages(where: str) -> List[str]: ... diff --git a/python-packages/contract_addresses/stubs/setuptools/command/__init__.pyi b/python-packages/contract_addresses/stubs/setuptools/command/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_addresses/stubs/setuptools/command/test.pyi b/python-packages/contract_addresses/stubs/setuptools/command/test.pyi deleted file mode 100644 index c5ec770ad3..0000000000 --- a/python-packages/contract_addresses/stubs/setuptools/command/test.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from setuptools import Command - -class test(Command): ... diff --git a/python-packages/contract_addresses/tox.ini b/python-packages/contract_addresses/tox.ini deleted file mode 100644 index 944049af60..0000000000 --- a/python-packages/contract_addresses/tox.ini +++ /dev/null @@ -1,18 +0,0 @@ -# tox (https://tox.readthedocs.io/) is a tool for running tests -# in multiple virtualenvs. This configuration file will run the -# test suite on all supported python versions. To use it, "pip install tox" -# and then run "tox" from this directory. - -[tox] -envlist = py37 - -[testenv] -commands = - pip install -e .[dev] - python setup.py test - -[testenv:run_tests_against_deployment] -setenv = PY_IGNORE_IMPORTMISMATCH = 1 -commands= - pip install 0x-contract-addresses[dev] - pytest --doctest-modules src diff --git a/python-packages/contract_artifacts/.discharge.json b/python-packages/contract_artifacts/.discharge.json deleted file mode 100644 index d9cb2a37b2..0000000000 --- a/python-packages/contract_artifacts/.discharge.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "domain": "0x-contract-artifacts-py", - "build_command": "python setup.py build_sphinx", - "upload_directory": "build/docs/html", - "index_key": "index.html", - "error_key": "index.html", - "trailing_slashes": true, - "cache": 3600, - "aws_profile": "default", - "aws_region": "us-east-1", - "cdn": false, - "dns_configured": true -} diff --git a/python-packages/contract_artifacts/.pylintrc b/python-packages/contract_artifacts/.pylintrc deleted file mode 100644 index 937bc6313b..0000000000 --- a/python-packages/contract_artifacts/.pylintrc +++ /dev/null @@ -1,3 +0,0 @@ -[MESSAGES CONTROL] -disable=C0330,line-too-long,fixme,too-few-public-methods,too-many-ancestors -# C0330 is "bad hanging indent". we use indents per `black`. diff --git a/python-packages/contract_artifacts/CHANGELOG.md b/python-packages/contract_artifacts/CHANGELOG.md deleted file mode 100644 index cd0ec7a9d4..0000000000 --- a/python-packages/contract_artifacts/CHANGELOG.md +++ /dev/null @@ -1,13 +0,0 @@ -# Changelog - -## 3.0.0 - 2019-12-03 - -- Updated with artifacts for version 3 of the protocol. - -## 2.0.1 - 2019-04-30 - -- Expanded documentation. - -## 2.0.0 - 2019-01-09 - -- Initial release. diff --git a/python-packages/contract_artifacts/README.md b/python-packages/contract_artifacts/README.md deleted file mode 100644 index e29af2ba35..0000000000 --- a/python-packages/contract_artifacts/README.md +++ /dev/null @@ -1,45 +0,0 @@ -## 0x-contract-artifacts - -0x smart contract compilation artifacts - -Read the [documentation](http://0x-contract-artifacts-py.s3-website-us-east-1.amazonaws.com/) - -## Installing - -```bash -pip install 0x-contract-artifacts -``` - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Pull in artifacts from TypeScript build environment - -```bash -./setup.py pre_install -``` - -### Install Code and Dependencies - -```bash -pip install -e .[dev] -``` - -### Clean - -`./setup.py clean --all` - -### Lint - -`./setup.py lint` - -### Build Documentation - -`./setup.py build_sphinx` - -### More - -See `./setup.py --help-commands` for more info. diff --git a/python-packages/contract_artifacts/setup.py b/python-packages/contract_artifacts/setup.py deleted file mode 100755 index 1d9e71b87d..0000000000 --- a/python-packages/contract_artifacts/setup.py +++ /dev/null @@ -1,228 +0,0 @@ -#!/usr/bin/env python - -"""setuptools module for contract_artifacts package.""" - -# pylint: disable=import-outside-toplevel -# we import things outside of top-level because 3rd party libs may not yet be -# installed when you invoke this script - -import subprocess # nosec -from shutil import copytree, rmtree -from os import environ, path -from sys import argv, exit # pylint: disable=redefined-builtin - -from distutils.command.clean import clean -import distutils.command.build_py -from setuptools import find_packages, setup -from setuptools.command.test import test as TestCommand - - -class PreInstallCommand(distutils.command.build_py.build_py): - """Custom setuptools command class for pulling in artifacts.""" - - description = "Pull in the artifacts that live in the TypeScript package." - - def run(self): - """Copy files from TS build area to local src, & `black` them.""" - pkgdir = path.dirname(path.realpath(argv[0])) - rmtree( - path.join( - pkgdir, "src", "zero_ex", "contract_artifacts", "artifacts" - ), - ignore_errors=True, - ) - copytree( - path.join( - pkgdir, - "..", - "..", - "packages", - "contract-artifacts", - "artifacts", - ), - path.join( - pkgdir, "src", "zero_ex", "contract_artifacts", "artifacts" - ), - ) - - -class LintCommand(distutils.command.build_py.build_py): - """Custom setuptools command class for running linters.""" - - description = "Run linters" - - def run(self): - """Run linter shell commands.""" - lint_commands = [ - # formatter: - "black --line-length 79 --check --diff src setup.py".split(), - # style guide checker (formerly pep8): - "pycodestyle --show-source --show-pep8 src setup.py".split(), - # docstring style checker: - "pydocstyle src setup.py".split(), - # static type checker: - "mypy src setup.py".split(), - # security issue checker: - "bandit -r src ./setup.py".split(), - # general linter: - "pylint src setup.py".split(), - # pylint takes relatively long to run, so it runs last, to enable - # fast failures. - ] - - # tell mypy where to find interface stubs for 3rd party libs - environ["MYPYPATH"] = path.join( - path.dirname(path.realpath(argv[0])), "stubs" - ) - - for lint_command in lint_commands: - print( - "Running lint command `", " ".join(lint_command).strip(), "`" - ) - subprocess.check_call(lint_command) # nosec - - -class CleanCommandExtension(clean): - """Custom command to do custom cleanup.""" - - def run(self): - """Run the regular clean, followed by our custom commands.""" - super().run() - rmtree("build", ignore_errors=True) - rmtree("dist", ignore_errors=True) - rmtree(".mypy_cache", ignore_errors=True) - rmtree(".tox", ignore_errors=True) - rmtree(".pytest_cache", ignore_errors=True) - rmtree("src/0x_contract_artifacts.egg-info", ignore_errors=True) - - -class TestPublishCommand(distutils.command.build_py.build_py): - """Custom command to publish to test.pypi.org.""" - - description = ( - "Publish dist/* to test.pypi.org. Run sdist & bdist_wheel first." - ) - - def run(self): - """Run twine to upload to test.pypi.org.""" - subprocess.check_call( # nosec - ( - "twine upload --repository-url https://test.pypi.org/legacy/" - + " --verbose dist/*" - ).split() - ) - - -class PublishCommand(distutils.command.build_py.build_py): - """Custom command to publish to pypi.org.""" - - description = "Publish dist/* to pypi.org. Run sdist & bdist_wheel first." - - def run(self): - """Run twine to upload to pypi.org.""" - subprocess.check_call("twine upload dist/*".split()) # nosec - - -class PublishDocsCommand(distutils.command.build_py.build_py): - """Custom command to publish docs to S3.""" - - description = ( - "Publish docs to " - + "http://0x-contract-artifacts-py.s3-website-us-east-1.amazonaws.com/" - ) - - def run(self): - """Run npm package `discharge` to build & upload docs.""" - subprocess.check_call("discharge deploy".split()) # nosec - - -class TestCommandExtension(TestCommand): - """Run pytest tests.""" - - def run_tests(self): - """Invoke pytest.""" - import pytest - - exit(pytest.main(["--doctest-modules", "-rapP"])) - # show short test summary at end ^ - - -with open("README.md", "r") as file_handle: - README_MD = file_handle.read() - - -setup( - name="0x-contract-artifacts", - version="3.0.0", - description="0x smart contract compilation artifacts", - long_description=README_MD, - long_description_content_type="text/markdown", - url=( - "https://github.com/0xproject/0x-monorepo/tree/development" - + "/python-packages/contract_artifacts" - ), - author="F. Eugene Aumson", - author_email="feuGeneA@users.noreply.github.com", - cmdclass={ - "pre_install": PreInstallCommand, - "clean": CleanCommandExtension, - "lint": LintCommand, - "test": TestCommandExtension, - "test_publish": TestPublishCommand, - "publish": PublishCommand, - "publish_docs": PublishDocsCommand, - }, - install_requires=["mypy_extensions"], - extras_require={ - "dev": [ - "bandit", - "black", - "coverage", - "coveralls", - "mypy<=0.770", # https://github.com/python/mypy/issues/8953 - "mypy_extensions", - "pycodestyle", - "pydocstyle", - "pylint", - "pytest", - "sphinx", - "tox", - "twine", - ] - }, - python_requires=">=3.6, <4", - package_data={"zero_ex.contract_artifacts": ["py.typed", "artifacts/*"]}, - package_dir={"": "src"}, - license="Apache 2.0", - keywords=( - "ethereum cryptocurrency 0x decentralized blockchain dex exchange" - ), - namespace_packages=["zero_ex"], - packages=find_packages("src"), - classifiers=[ - "Development Status :: 5 - Production/Stable", - "Intended Audience :: Developers", - "Intended Audience :: Financial and Insurance Industry", - "License :: OSI Approved :: Apache Software License", - "Natural Language :: English", - "Operating System :: OS Independent", - "Programming Language :: Python", - "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3.6", - "Programming Language :: Python :: 3.7", - "Topic :: Internet :: WWW/HTTP", - "Topic :: Office/Business :: Financial", - "Topic :: Other/Nonlisted Topic", - "Topic :: Security :: Cryptography", - "Topic :: Software Development :: Libraries", - "Topic :: Utilities", - ], - zip_safe=False, # required per mypy - command_options={ - "build_sphinx": { - "source_dir": ("setup.py", "src"), - "build_dir": ("setup.py", "build/docs"), - "warning_is_error": ("setup.py", "true"), - } - }, -) diff --git a/python-packages/contract_artifacts/src/conf.py b/python-packages/contract_artifacts/src/conf.py deleted file mode 100644 index 2b0a971168..0000000000 --- a/python-packages/contract_artifacts/src/conf.py +++ /dev/null @@ -1,54 +0,0 @@ -"""Configuration file for the Sphinx documentation builder.""" - -# Reference: http://www.sphinx-doc.org/en/master/config - -from typing import List -import pkg_resources - - -# pylint: disable=invalid-name -# because these variables are not named in upper case, as globals should be. - -project = "0x-contract-artifacts" -# pylint: disable=redefined-builtin -copyright = "2018, ZeroEx, Intl." -author = "F. Eugene Aumson" -version = pkg_resources.get_distribution("0x-contract-artifacts").version -release = "" # The full version, including alpha/beta/rc tags - -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.doctest", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.viewcode", -] - -templates_path = ["doc_templates"] - -source_suffix = ".rst" -# eg: source_suffix = [".rst", ".md"] - -master_doc = "index" # The master toctree document. - -language = None - -exclude_patterns: List[str] = [] - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = None - -html_theme = "alabaster" - -html_static_path = ["doc_static"] -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". - -# Output file base name for HTML help builder. -htmlhelp_basename = "contract_artifactspydoc" - -# -- Extension configuration: - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = {"https://docs.python.org/": None} diff --git a/python-packages/contract_artifacts/src/doc_static/.gitkeep b/python-packages/contract_artifacts/src/doc_static/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_artifacts/src/index.rst b/python-packages/contract_artifacts/src/index.rst deleted file mode 100644 index d086ad2880..0000000000 --- a/python-packages/contract_artifacts/src/index.rst +++ /dev/null @@ -1,18 +0,0 @@ -.. source for the sphinx-generated build/docs/web/index.html - -Python zero_ex.contract_artifacts -================================= - -.. toctree:: - :maxdepth: 2 - :caption: Contents: - -.. automodule:: zero_ex.contract_artifacts - :members: - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` diff --git a/python-packages/contract_artifacts/src/zero_ex/__init__.py b/python-packages/contract_artifacts/src/zero_ex/__init__.py deleted file mode 100644 index 3fe1300cfb..0000000000 --- a/python-packages/contract_artifacts/src/zero_ex/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -"""0x Python API.""" -__import__("pkg_resources").declare_namespace(__name__) # type: ignore diff --git a/python-packages/contract_artifacts/src/zero_ex/contract_artifacts/__init__.py b/python-packages/contract_artifacts/src/zero_ex/contract_artifacts/__init__.py deleted file mode 100644 index f1946a8ea0..0000000000 --- a/python-packages/contract_artifacts/src/zero_ex/contract_artifacts/__init__.py +++ /dev/null @@ -1,61 +0,0 @@ -"""0x smart contract compilation artifacts. - -Setup ------ - -Install the package with pip:: - - pip install 0x-contract-artifacts -""" - -import json -from typing import Dict -from pkg_resources import resource_string - - -class _ArtifactCache: - """A cache to facilitate lazy & singular loading of contract artifacts.""" - - _contract_name_to_abi: Dict[str, Dict] = {} # class data, not instance - - @classmethod - def contract_name_to_abi(cls, contract_name: str) -> Dict: - """Return the ABI for the given contract name. - - First tries to get data from the class level storage - `_contract_name_to_abi`. If it's not there, loads it from disk, stores - it in the class data (for the next caller), and then returns it. - """ - try: - return cls._contract_name_to_abi[contract_name] - except KeyError: - cls._contract_name_to_abi[contract_name] = json.loads( - resource_string( - "zero_ex.contract_artifacts", - f"artifacts/{contract_name}.json", - ) - )["compilerOutput"]["abi"] - return cls._contract_name_to_abi[contract_name] - - -def abi_by_name(contract_name: str) -> Dict: - """Return the ABI for the named contract. - - Contract names must correspond to files in the package's `artifacts`:code: - directory, without the `.json`:code: suffix. - - >>> from pprint import pprint - >>> pprint(abi_by_name("IValidator")) - [{'constant': True, - 'inputs': [{'internalType': 'bytes32', 'name': 'hash', 'type': 'bytes32'}, - {'internalType': 'address', - 'name': 'signerAddress', - 'type': 'address'}, - {'internalType': 'bytes', 'name': 'signature', 'type': 'bytes'}], - 'name': 'isValidSignature', - 'outputs': [{'internalType': 'bytes4', 'name': '', 'type': 'bytes4'}], - 'payable': False, - 'stateMutability': 'view', - 'type': 'function'}] - """ # noqa: E501 (line too long) - return _ArtifactCache.contract_name_to_abi(contract_name) diff --git a/python-packages/contract_artifacts/src/zero_ex/contract_artifacts/py.typed b/python-packages/contract_artifacts/src/zero_ex/contract_artifacts/py.typed deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_artifacts/stubs/distutils/__init__.pyi b/python-packages/contract_artifacts/stubs/distutils/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_artifacts/stubs/distutils/command/__init__.pyi b/python-packages/contract_artifacts/stubs/distutils/command/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_artifacts/stubs/distutils/command/clean.pyi b/python-packages/contract_artifacts/stubs/distutils/command/clean.pyi deleted file mode 100644 index 46a42ddb13..0000000000 --- a/python-packages/contract_artifacts/stubs/distutils/command/clean.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from distutils.core import Command - -class clean(Command): - def initialize_options(self: clean) -> None: ... - def finalize_options(self: clean) -> None: ... - def run(self: clean) -> None: ... - ... diff --git a/python-packages/contract_artifacts/stubs/pytest/__init__.pyi b/python-packages/contract_artifacts/stubs/pytest/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_artifacts/stubs/setuptools/__init__.pyi b/python-packages/contract_artifacts/stubs/setuptools/__init__.pyi deleted file mode 100644 index 8ea8d32b7e..0000000000 --- a/python-packages/contract_artifacts/stubs/setuptools/__init__.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from distutils.dist import Distribution -from typing import Any, List - -def setup(**attrs: Any) -> Distribution: ... - -class Command: ... - -def find_packages(where: str) -> List[str]: ... diff --git a/python-packages/contract_artifacts/stubs/setuptools/command/__init__.pyi b/python-packages/contract_artifacts/stubs/setuptools/command/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_artifacts/stubs/setuptools/command/test.pyi b/python-packages/contract_artifacts/stubs/setuptools/command/test.pyi deleted file mode 100644 index c5ec770ad3..0000000000 --- a/python-packages/contract_artifacts/stubs/setuptools/command/test.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from setuptools import Command - -class test(Command): ... diff --git a/python-packages/contract_artifacts/tox.ini b/python-packages/contract_artifacts/tox.ini deleted file mode 100644 index 4fd5f65639..0000000000 --- a/python-packages/contract_artifacts/tox.ini +++ /dev/null @@ -1,18 +0,0 @@ -# tox (https://tox.readthedocs.io/) is a tool for running tests -# in multiple virtualenvs. This configuration file will run the -# test suite on all supported python versions. To use it, "pip install tox" -# and then run "tox" from this directory. - -[tox] -envlist = py37 - -[testenv] -commands = - pip install -e .[dev] - python setup.py test - -[testenv:run_tests_against_deployment] -setenv = PY_IGNORE_IMPORTMISMATCH = 1 -commands= - pip install 0x-contract-artifacts[dev] - pytest --doctest-modules src diff --git a/python-packages/contract_wrappers/.discharge.json b/python-packages/contract_wrappers/.discharge.json deleted file mode 100644 index 62c1e576ae..0000000000 --- a/python-packages/contract_wrappers/.discharge.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "domain": "0x-contract-wrappers-py", - "build_command": "python setup.py build_sphinx", - "upload_directory": "build/docs/html", - "index_key": "index.html", - "error_key": "index.html", - "trailing_slashes": true, - "cache": 3600, - "aws_profile": "default", - "aws_region": "us-east-1", - "cdn": false, - "dns_configured": true -} diff --git a/python-packages/contract_wrappers/.pylintrc b/python-packages/contract_wrappers/.pylintrc deleted file mode 100644 index 74fb21334a..0000000000 --- a/python-packages/contract_wrappers/.pylintrc +++ /dev/null @@ -1,7 +0,0 @@ -[MESSAGES CONTROL] -disable=C0330,line-too-long,fixme,too-few-public-methods,too-many-ancestors,duplicate-code -# C0330 is "bad hanging indent". we use indents per `black`. - -[BASIC] -argument-rgx=[a-z_][a-z0-9_]{1,31}$ -# above differs from the default only in that it allows 2-character names diff --git a/python-packages/contract_wrappers/CHANGELOG.md b/python-packages/contract_wrappers/CHANGELOG.md deleted file mode 100644 index a206f81aaf..0000000000 --- a/python-packages/contract_wrappers/CHANGELOG.md +++ /dev/null @@ -1,36 +0,0 @@ -# Changelog - -## 2.0.0 - 2019-12-03 - -- Updated for version 3 of the protocol. -- Allow wrappers to be instantiated with EITHER a Web3.py `BaseProvider` OR an already-instantiated `Web3` client object. -- Accept `str`ing arguments to `bytes` contract method parameters. -- Expanded documentation examples. -- Moved methods `jsdict_to_order()` and `order_to_jsdict()` from `zero_ex.contract_wrappers.exchange.types` to `zero_ex.contract_wrappers.order_conversions`. -- Changed field name `zero_ex.contract_wrappers.tx_params.TxParams.gasPrice` to `.gas_price`. -- Migrated to new version of 0x-contract-addresses. -- Made the `underlying_method` field on ContractMethod private by prefixing its name with an underscore. -- Corrected return types and values for call() interface to generated method wrappers. (Fixes #2298.) -- Removed `send_transaction()` method from ContractMethod instances for underlying Solidity methods that are const (view/pure). -- Added a `build_transaction()` method to instances of ContractMethod for non-const Solidity methods. -- Removed `validator` argument from ContractMethod instances for underlying Solidity methods that lack inputs. - -## 1.1.0 - 2019-08-14 - -- Added wrapper for DevUtils contract. - -## 1.0.3 - 2019-08-10 - -- Added erroneously missing source files. - -## 1.0.2 - 2019-08-10 - -- Added erroneously missing source files. - -## 1.0.1 - 2019-08-10 - -- Botched upload to PyPI. - -## 1.0.0 - 2019-08-08 - -- Initial release diff --git a/python-packages/contract_wrappers/README.md b/python-packages/contract_wrappers/README.md deleted file mode 100644 index 8598d02dd0..0000000000 --- a/python-packages/contract_wrappers/README.md +++ /dev/null @@ -1,47 +0,0 @@ -## 0x-contract-wrappers - -0x contract wrappers for those developing on top of 0x protocol. - -Read the [documentation](http://0x-contract-wrappers-py.s3-website-us-east-1.amazonaws.com/) - -## Installing - -```bash -pip install 0x-contract-wrappers -``` - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install Code and Dependencies - -This package contains code generated via npm package @0x/abi-gen. Preparing this package for development or installation requires running `./setup.py pre_install`, which will invoke abi-gen to write the files to the src hierarchy. It expects to find abi-gen and the contract artifacts at the relative directory locations in the monorepo. - -After code generation, ensure that you have installed Python >=3.6 and Docker, and then: - -```bash -pip install -e .[dev] -``` - -### Test - -Tests depend on a running ganache instance and with the 0x contracts deployed in it. For convenience, a docker container is provided that has ganache-cli and a snapshot containing the necessary contracts. A shortcut is provided to run that docker container: `./setup.py ganache`. With that running, the tests can be run with `./setup.py test`. - -### Clean - -`./setup.py clean --all` - -### Lint - -`./setup.py lint` - -### Build Documentation - -`./setup.py build_sphinx` - -### More - -See `./setup.py --help-commands` for more info. diff --git a/python-packages/contract_wrappers/setup.cfg b/python-packages/contract_wrappers/setup.cfg deleted file mode 100644 index e37dc107e7..0000000000 --- a/python-packages/contract_wrappers/setup.cfg +++ /dev/null @@ -1,5 +0,0 @@ -[pycodestyle] -ignore = E501, W503 -# E501 = line too long -# W503 = line break occurred before a binary operator -# we let black handle these things diff --git a/python-packages/contract_wrappers/setup.py b/python-packages/contract_wrappers/setup.py deleted file mode 100755 index 5eb83240a5..0000000000 --- a/python-packages/contract_wrappers/setup.py +++ /dev/null @@ -1,268 +0,0 @@ -#!/usr/bin/env python - -"""setuptools module for contract_wrappers package.""" - -# pylint: disable=import-outside-toplevel -# we import things outside of top-level because 3rd party libs may not yet be -# installed when you invoke this script - -from glob import glob -import subprocess # nosec -from shutil import rmtree -from os import environ, path, remove -from pathlib import Path -from sys import argv, exit # pylint: disable=redefined-builtin - -from distutils.command.clean import clean -import distutils.command.build_py -from setuptools import find_packages, setup -from setuptools.command.test import test as TestCommand - - -class PreInstallCommand(distutils.command.build_py.build_py): - """Custom setuptools command class for pulling in generated code.""" - - description = "Pull in code generated by TypeScript" - - def run(self): - """Use abi-gen to generate contract wrappers.""" - subprocess.check_call("pip install black".split()) # nosec - subprocess.check_call( # nosec - ( - "../../node_modules/.bin/abi-gen" - " --language Python" - " --abis ../../packages/contract-artifacts/artifacts/*" - " --output src/zero_ex/contract_wrappers" - ).split() - ) - - -class TestCommandExtension(TestCommand): - """Run pytest tests.""" - - def run_tests(self): - """Invoke pytest.""" - import pytest - - exit(pytest.main(["--doctest-modules", "-rapP"])) - # show short test summary at end ^ - - -class LintCommand(distutils.command.build_py.build_py): - """Custom setuptools command class for running linters.""" - - description = "Run linters" - - def run(self): - """Run linter shell commands.""" - lint_commands = [ - # formatter: - ( - "black --line-length 79 --check --diff src test setup.py" - ).split(), - # style guide checker (formerly pep8): - "pycodestyle src test setup.py".split(), - # docstring style checker: - "pydocstyle src test setup.py".split(), - # static type checker: - "mypy src test setup.py".split(), - # security issue checker: - "bandit -r src ./setup.py".split(), - # general linter: - "pylint src test setup.py".split(), - # pylint takes relatively long to run, so it runs last, to enable - # fast failures. - ] - - # tell mypy where to find interface stubs for 3rd party libs - environ["MYPYPATH"] = path.join( - path.dirname(path.realpath(argv[0])), "stubs" - ) - - # HACK(gene): until eth_utils fixes - # https://github.com/ethereum/eth-utils/issues/140 , we need to simply - # create an empty file `py.typed` in the eth_abi package directory. - import eth_utils - - eth_utils_dir = path.dirname(path.realpath(eth_utils.__file__)) - Path(path.join(eth_utils_dir, "py.typed")).touch() - - for lint_command in lint_commands: - print( - "Running lint command `", " ".join(lint_command).strip(), "`" - ) - subprocess.check_call(lint_command) # nosec - - -class CleanCommandExtension(clean): - """Custom command to do custom cleanup.""" - - def run(self): - """Run the regular clean, followed by our custom commands.""" - super().run() - rmtree("build", ignore_errors=True) - rmtree("dist", ignore_errors=True) - rmtree(".mypy_cache", ignore_errors=True) - rmtree(".tox", ignore_errors=True) - rmtree(".pytest_cache", ignore_errors=True) - rmtree( - path.join("src", "0x_contract_wrappers.egg-info"), - ignore_errors=True, - ) - # generated files: - print("Removing src/zero_ex/contract_wrappers/*/__init__.py...") - for contract in glob( - path.join( - ".", "src", "zero_ex", "contract_wrappers", "*", "__init__.py" - ) - ): - try: - print(f"Removing {contract}...", end="") - remove(contract) - print("done") - except FileNotFoundError: - print("file not found") - - -class TestPublishCommand(distutils.command.build_py.build_py): - """Custom command to publish to test.pypi.org.""" - - description = ( - "Publish dist/* to test.pypi.org. Run sdist & bdist_wheel first." - ) - - def run(self): - """Run twine to upload to test.pypi.org.""" - subprocess.check_call( # nosec - ( - "twine upload --repository-url https://test.pypi.org/legacy/" - + " --verbose dist/*" - ).split() - ) - - -class PublishCommand(distutils.command.build_py.build_py): - """Custom command to publish to pypi.org.""" - - description = "Publish dist/* to pypi.org. Run sdist & bdist_wheel first." - - def run(self): - """Run twine to upload to pypi.org.""" - subprocess.check_call("twine upload dist/*".split()) # nosec - - -class PublishDocsCommand(distutils.command.build_py.build_py): - """Custom command to publish docs to S3.""" - - description = ( - "Publish docs to " - + "http://0x-contract-wrappers-py.s3-website-us-east-1.amazonaws.com/" - ) - - def run(self): - """Run npm package `discharge` to build & upload docs.""" - subprocess.check_call("discharge deploy".split()) # nosec - - -class GanacheCommand(distutils.command.build_py.build_py): - """Custom command to publish to pypi.org.""" - - description = "Run ganache daemon to support tests." - - def run(self): - """Run ganache.""" - subprocess.call(("docker pull 0xorg/ganache-cli").split()) # nosec - subprocess.call( # nosec - ("docker run -d -p 8545:8545 0xorg/ganache-cli").split() - ) - - -with open("README.md", "r") as file_handle: - README_MD = file_handle.read() - - -setup( - name="0x-contract-wrappers", - version="2.0.0", - description="Python wrappers for 0x smart contracts", - long_description=README_MD, - long_description_content_type="text/markdown", - url=( - "https://github.com/0xproject/0x-monorepo/tree/development" - + "/python-packages/contract_wrappers" - ), - author="F. Eugene Aumson", - author_email="feuGeneA@users.noreply.github.com", - cmdclass={ - "clean": CleanCommandExtension, - "pre_install": PreInstallCommand, - "lint": LintCommand, - "test": TestCommandExtension, - "test_publish": TestPublishCommand, - "publish": PublishCommand, - "publish_docs": PublishDocsCommand, - "ganache": GanacheCommand, - }, - install_requires=[ - "0x-contract-addresses", - "0x-contract-artifacts", - "0x-json-schemas", - "0x-order-utils", - "web3", - "attrs", - "eth_utils", - "mypy_extensions", - ], - extras_require={ - "dev": [ - "bandit", - "black", - "coverage", - "coveralls", - "mypy<=0.770", # see https://github.com/python/mypy/issues/8953 - "mypy_extensions", - "pycodestyle", - "pydocstyle", - "pylint", - "pytest", - "sphinx", - "tox", - "twine", - ] - }, - python_requires=">=3.6, <4", - package_data={"zero_ex.contract_wrappers": ["py.typed"]}, - package_dir={"": "src"}, - license="Apache 2.0", - keywords=( - "ethereum cryptocurrency 0x decentralized blockchain dex exchange" - ), - namespace_packages=["zero_ex"], - packages=find_packages("src"), - classifiers=[ - "Development Status :: 2 - Pre-Alpha", - "Intended Audience :: Developers", - "Intended Audience :: Financial and Insurance Industry", - "License :: OSI Approved :: Apache Software License", - "Natural Language :: English", - "Operating System :: OS Independent", - "Programming Language :: Python", - "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3.6", - "Programming Language :: Python :: 3.7", - "Topic :: Internet :: WWW/HTTP", - "Topic :: Office/Business :: Financial", - "Topic :: Other/Nonlisted Topic", - "Topic :: Security :: Cryptography", - "Topic :: Software Development :: Libraries", - "Topic :: Utilities", - ], - zip_safe=False, # required per mypy - command_options={ - "build_sphinx": { - "source_dir": ("setup.py", "src"), - "build_dir": ("setup.py", "build/docs"), - "warning_is_error": ("setup.py", "true"), - } - }, -) diff --git a/python-packages/contract_wrappers/src/conf.py b/python-packages/contract_wrappers/src/conf.py deleted file mode 100644 index f353138f52..0000000000 --- a/python-packages/contract_wrappers/src/conf.py +++ /dev/null @@ -1,91 +0,0 @@ -"""Configuration file for the Sphinx documentation builder.""" - -# Reference: http://www.sphinx-doc.org/en/master/config - -from typing import List - -import pkg_resources - - -# pylint: disable=invalid-name -# because these variables are not named in upper case, as globals should be. - -project = "0x-contract-wrappers" -# pylint: disable=redefined-builtin -copyright = "2019, ZeroEx, Intl." -author = "Michael Huang" -version = pkg_resources.get_distribution("0x-contract-wrappers").version -release = "" # The full version, including alpha/beta/rc tags - -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.doctest", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.viewcode", -] - -templates_path = ["doc_templates"] - -source_suffix = ".rst" -# eg: source_suffix = [".rst", ".md"] - -master_doc = "index" # The master toctree document. - -language = None - -exclude_patterns: List[str] = [] - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = None - -html_theme = "alabaster" - -html_static_path = ["doc_static"] -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". - -# Output file base name for HTML help builder. -htmlhelp_basename = "contract_wrapperspydoc" - -# -- Extension configuration: - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = {"https://docs.python.org/": None} - - -def annotate_gend_tuple_docstring( # pylint: disable=too-many-arguments - app, # pylint: disable=unused-argument - what, # pylint: disable=unused-argument - name, # pylint: disable=unused-argument - obj, # pylint: disable=unused-argument - options, # pylint: disable=unused-argument - lines, -): - """Annotate docstrings of generated tuples.""" - docstring_extensions = { - "LibOrderOrder": [ - "This is the generated class representing `the Order struct `_." - ], - "LibFillResultsFillResults": [ - "This is the generated class representing `the FillResults struct `_." - ], - "LibFillResultsMatchedFillResults": [ - "This is the generated class representing `the MatchedFillResults struct `_." - ], - "LibOrderOrderInfo": [ - "This is the generated class representing `the OrderInfo struct `_." - ], - "LibZeroExTransactionZeroExTransaction": [ - "This is the generated class representing `the ZeroExTransaction struct `_." - ], - } - unqualified_name = name.split(".")[-1] - if unqualified_name in docstring_extensions: - lines.extend(docstring_extensions[unqualified_name]) - - -def setup(app): - """Install callbacks.""" - app.connect("autodoc-process-docstring", annotate_gend_tuple_docstring) diff --git a/python-packages/contract_wrappers/src/doc_static/.gitkeep b/python-packages/contract_wrappers/src/doc_static/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_wrappers/src/doc_templates/.gitkeep b/python-packages/contract_wrappers/src/doc_templates/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_wrappers/src/index.rst b/python-packages/contract_wrappers/src/index.rst deleted file mode 100644 index ef482bccd4..0000000000 --- a/python-packages/contract_wrappers/src/index.rst +++ /dev/null @@ -1,206 +0,0 @@ -Python zero_ex.contract_wrappers -================================ - -.. toctree:: - :maxdepth: 2 - :caption: Contents: - -.. automodule:: zero_ex.contract_wrappers - :members: - - -zero_ex.contract_wrappers.asset_proxy_owner -=========================================== - -.. automodule:: zero_ex.contract_wrappers.asset_proxy_owner - :members: - :special-members: - - -zero_ex.contract_wrappers.coordinator -===================================== - -.. automodule:: zero_ex.contract_wrappers.coordinator - :members: - :special-members: - - -zero_ex.contract_wrappers.coordinator_registry -============================================== - -.. automodule:: zero_ex.contract_wrappers.coordinator_registry - :members: - :special-members: - - -zero_ex.contract_wrappers.dev_utils -=================================== - -.. automodule:: zero_ex.contract_wrappers.dev_utils - :members: - :special-members: - - -zero_ex.contract_wrappers.dutch_auction -======================================= - -.. automodule:: zero_ex.contract_wrappers.dutch_auction - :members: - :special-members: - - -zero_ex.contract_wrappers.erc1155_mintable -========================================== - -.. automodule:: zero_ex.contract_wrappers.erc1155_mintable - :members: - :special-members: - - -zero_ex.contract_wrappers.erc1155_proxy -======================================= - -.. automodule:: zero_ex.contract_wrappers.erc1155_proxy - :members: - :special-members: - - -zero_ex.contract_wrappers.erc20_proxy -===================================== - -.. automodule:: zero_ex.contract_wrappers.erc20_proxy - :members: - :special-members: - - -zero_ex.contract_wrappers.erc20_token -===================================== - -.. automodule:: zero_ex.contract_wrappers.erc20_token - :members: - :special-members: - - -zero_ex.contract_wrappers.erc721_proxy -====================================== - -.. automodule:: zero_ex.contract_wrappers.erc721_proxy - :members: - :special-members: - - -zero_ex.contract_wrappers.erc721_token -====================================== - -.. automodule:: zero_ex.contract_wrappers.erc721_token - :members: - :special-members: - - -zero_ex.contract_wrappers.exchange -================================== - -.. automodule:: zero_ex.contract_wrappers.exchange - :members: - :special-members: - - -zero_ex.contract_wrappers.forwarder -=================================== - -.. automodule:: zero_ex.contract_wrappers.forwarder - :members: - :special-members: - - -zero_ex.contract_wrappers.i_asset_proxy -======================================= - -.. automodule:: zero_ex.contract_wrappers.i_asset_proxy - :members: - :special-members: - - -zero_ex.contract_wrappers.i_validator -===================================== - -.. automodule:: zero_ex.contract_wrappers.i_validator - :members: - :special-members: - - -zero_ex.contract_wrappers.i_wallet -================================== - -.. automodule:: zero_ex.contract_wrappers.i_wallet - :members: - :special-members: - - -zero_ex.contract_wrappers.multi_asset_proxy -=========================================== - -.. automodule:: zero_ex.contract_wrappers.multi_asset_proxy - :members: - :special-members: - - -zero_ex.contract_wrappers.order_validator -========================================= - -.. automodule:: zero_ex.contract_wrappers.order_validator - :members: - :special-members: - - -zero_ex.contract_wrappers.static_call_proxy -=========================================== - -.. automodule:: zero_ex.contract_wrappers.static_call_proxy - :members: - :special-members: - - -zero_ex.contract_wrappers.weth9 -=============================== - -.. automodule:: zero_ex.contract_wrappers.weth9 - :members: - :special-members: - - -zero_ex.contract_wrappers.zrx_token -=================================== - -.. automodule:: zero_ex.contract_wrappers.zrx_token - :members: - :special-members: - - -zero_ex.contract_wrappers.TxParams -================================== - -.. autoclass:: zero_ex.contract_wrappers.TxParams - :members: - -zero_ex.contract_wrappers.exchange.types -======================================== - -.. automodule:: zero_ex.contract_wrappers.exchange.types - -.. autoclass:: zero_ex.contract_wrappers.exchange.types.Order - -.. autoclass:: zero_ex.contract_wrappers.exchange.types.OrderInfo - -.. autoclass:: zero_ex.contract_wrappers.exchange.types.FillResults - -.. autoclass:: zero_ex.contract_wrappers.exchange.types.MatchedFillResults - -.. autoclass:: zero_ex.contract_wrappers.exchange.types.ZeroExTransaction - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` diff --git a/python-packages/contract_wrappers/src/zero_ex/__init__.py b/python-packages/contract_wrappers/src/zero_ex/__init__.py deleted file mode 100644 index 3fe1300cfb..0000000000 --- a/python-packages/contract_wrappers/src/zero_ex/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -"""0x Python API.""" -__import__("pkg_resources").declare_namespace(__name__) # type: ignore diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/__init__.py b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/__init__.py deleted file mode 100644 index e9c4a5aab4..0000000000 --- a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/__init__.py +++ /dev/null @@ -1,386 +0,0 @@ -"""Python wrappers for interacting with 0x smart contracts. - -The smart contract wrappers have simplified interfaces, performing client-side -validation on transactions, and throwing helpful error messages. - -Setup ------ - -Install the 0x-contract-wrappers with pip:: - - pip install 0x-contract-wrappers - -We need a Web3 provider to allow us to talk to the blockchain. You can -read `more about providers in the Web3.py documentation -`_. The examples below assume -there's a local instance of Ganache listening on port 8545: - ->>> from web3 import HTTPProvider ->>> ganache = HTTPProvider("http://localhost:8545") - -To replicate these examples, one can use the `0xorg/ganache-cli`:code: docker -image, which comes with the 0x contracts pre-deployed. To start it:: - - docker run -d -p 8545:8545 0xorg/ganache-cli - -Accounts --------- - -In the examples below, we will use the accounts provided by Ganache, which are -accessible through the Web3 instance. The first account will be the maker, and -the second account will be the taker. - ->>> from web3 import Web3 ->>> accounts = Web3(ganache).eth.accounts ->>> maker_address = accounts[0] ->>> taker_address = accounts[1] - -In the examples below, we'll use the optional `tx_params`:code: parameter to -the contract calls, in order to specify which account each transaction is to -originate from. Under normal circumstances, your provider will have a default -account which will be used if you decline to specify an originating address. -For convenience, a `TxParams`:code: class is provided: - ->>> from zero_ex.contract_wrappers import TxParams - -Contract Addresses ------------------- - -The `0x-contract-addresses`:code: package (which is used by -`0x-contract-wrappers`:code: and thus gets installed along with it) provides -the addresses of the 0x contracts on each chain, including those that come -pre-deployed deployed in the `0xorg/ganache-cli`:code: docker image. Let's -capture the addresses we'll use throughout the examples below: - ->>> from zero_ex.contract_addresses import chain_to_addresses, ChainId ->>> weth_address = chain_to_addresses(ChainId.GANACHE).ether_token ->>> zrx_address = chain_to_addresses(ChainId.GANACHE).zrx_token ->>> exchange_address = chain_to_addresses(ChainId.GANACHE).exchange - -Wrapping ETH ------------- - -The examples below demonstrate constructing an order with the maker providing -ZRX in exchange for the taker providing some WETH. For the order to be valid, -our Taker first needs to wrap some ether as WETH. - -First get an instance of the WETH contract on the network: - ->>> from zero_ex.contract_artifacts import abi_by_name ->>> weth_instance = Web3(ganache).eth.contract( -... address=Web3.toChecksumAddress(weth_address), -... abi=abi_by_name("WETH9") -... ) - -Then have the Taker deposit some ETH into that contract, which will result in -it receiving WETH: - ->>> from eth_utils import to_wei ->>> weth_instance.functions.deposit().transact( -... {"from": Web3.toChecksumAddress(taker_address), -... "value": to_wei(1, 'ether')} -... ) -HexBytes('0x...') - -Approvals ---------- - -In order to trade on 0x, one must approve the 0x smart contracts to transfer -their tokens. Because the order constructed below has the maker giving WETH, -we need to tell the WETH token contract to let the 0x contracts transfer our -balance: - ->>> from zero_ex.contract_wrappers.erc20_token import ERC20Token ->>> zrx_token = ERC20Token( -... web3_or_provider=ganache, -... contract_address=chain_to_addresses(ChainId.GANACHE).zrx_token, -... ) ->>> weth_token = ERC20Token( -... web3_or_provider=ganache, -... contract_address=chain_to_addresses(ChainId.GANACHE).ether_token, -... ) - ->>> erc20_proxy_addr = chain_to_addresses(ChainId.GANACHE).erc20_proxy - ->>> tx = zrx_token.approve.send_transaction( -... erc20_proxy_addr, -... to_wei(100, 'ether'), -... tx_params=TxParams(from_=maker_address), -... ) - ->>> tx = weth_token.approve.send_transaction( -... erc20_proxy_addr, -... to_wei(100, 'ether'), -... tx_params=TxParams(from_=taker_address), -... ) - -Constructing an order ---------------------- - ->>> from zero_ex.contract_wrappers.exchange.types import Order ->>> from zero_ex.order_utils import asset_data_utils ->>> from datetime import datetime, timedelta ->>> import random ->>> order = Order( -... makerAddress=maker_address, -... takerAddress='0x0000000000000000000000000000000000000000', -... senderAddress='0x0000000000000000000000000000000000000000', -... feeRecipientAddress='0x0000000000000000000000000000000000000000', -... makerAssetData=asset_data_utils.encode_erc20(zrx_address), -... takerAssetData=asset_data_utils.encode_erc20(weth_address), -... salt=random.randint(1, 100000000000000000), -... makerFee=0, -... takerFee=0, -... makerAssetAmount=to_wei(0.1, 'ether'), -... takerAssetAmount=to_wei(0.1, 'ether'), -... expirationTimeSeconds=round( -... (datetime.utcnow() + timedelta(days=1)).timestamp() -... ), -... makerFeeAssetData='0x', -... takerFeeAssetData='0x', -... ) - -For this order to be valid, our Maker must sign a hash of it: - ->>> from zero_ex.order_utils import generate_order_hash_hex ->>> order_hash_hex = generate_order_hash_hex( -... order, exchange_address, Web3(ganache).eth.chainId -... ) - ->>> from zero_ex.order_utils import sign_hash ->>> maker_signature = sign_hash( -... ganache, Web3.toChecksumAddress(maker_address), order_hash_hex -... ) - -Now our Maker can either deliver this order, along with his signature, directly -to the taker, or he can choose to broadcast the order to a 0x Relayer. For -more information on working with Relayers, see `the documentation for -0x-sra-client `_. - -Filling an order ----------------- - -Now we'll have our Taker fill the order. - ->>> from zero_ex.contract_wrappers.exchange import Exchange ->>> exchange = Exchange( -... web3_or_provider=ganache, -... contract_address=chain_to_addresses(ChainId.GANACHE).exchange, -... ) - -But before filling an order, one may wish to check that it's actually fillable: - ->>> from zero_ex.contract_wrappers.exchange.types import OrderStatus ->>> OrderStatus(exchange.get_order_info.call(order)["orderStatus"]) - - -The `takerAssetAmount`:code: parameter specifies the amount of tokens (in this -case WETH) that the taker wants to fill. This example fills the order -completely, but partial fills are possible too. - -Note that sending value in the fill transaction is a way to pay the protocol -fee. The value to send is a function of the gas price, so we'll need some help -in that determination: - ->>> from web3.gas_strategies.rpc import rpc_gas_price_strategy ->>> web3 = Web3(ganache) ->>> web3.eth.setGasPriceStrategy(rpc_gas_price_strategy) - -One may wish to first call the method in a read-only way, to ensure that it -will not revert, and to validate that the return data is as expected: - ->>> from pprint import pprint ->>> pprint(exchange.fill_order.call( -... order=order, -... taker_asset_fill_amount=order["takerAssetAmount"], -... signature=maker_signature, -... tx_params=TxParams( -... from_=taker_address, value=web3.eth.generateGasPrice() * 150000 -... ), -... )) -{'makerAssetFilledAmount': 100000000000000000, - 'makerFeePaid': 0, - 'protocolFeePaid': ..., - 'takerAssetFilledAmount': 100000000000000000, - 'takerFeePaid': 0} - -Finally, submit the transaction: - ->>> tx_hash = exchange.fill_order.send_transaction( -... order=order, -... taker_asset_fill_amount=order["takerAssetAmount"], -... signature=maker_signature, -... tx_params=TxParams( -... from_=taker_address, value=web3.eth.generateGasPrice() * 150000 -... ) -... ) - -Once the transaction is mined, we can get the details of our exchange through -the exchange wrapper: - ->>> exchange.get_fill_event(tx_hash) -(AttributeDict({'args': ...({'makerAddress': ...}), 'event': 'Fill', ...}),) ->>> pprint(exchange.get_fill_event(tx_hash)[0].args.__dict__) -{'feeRecipientAddress': '0x0000000000000000000000000000000000000000', - 'makerAddress': '0x...', - 'makerAssetData': b..., - 'makerAssetFilledAmount': 100000000000000000, - 'makerFeeAssetData': b..., - 'makerFeePaid': 0, - 'orderHash': b..., - 'protocolFeePaid': ..., - 'senderAddress': '0x...', - 'takerAddress': '0x...', - 'takerAssetData': b..., - 'takerAssetFilledAmount': 100000000000000000, - 'takerFeeAssetData': b..., - 'takerFeePaid': 0} ->>> exchange.get_fill_event(tx_hash)[0].args.takerAssetFilledAmount -100000000000000000 - -Cancelling an order --------------------- - -A Maker can cancel an order that has yet to be filled. - ->>> order = Order( -... makerAddress=maker_address, -... takerAddress='0x0000000000000000000000000000000000000000', -... exchangeAddress=exchange_address, -... senderAddress='0x0000000000000000000000000000000000000000', -... feeRecipientAddress='0x0000000000000000000000000000000000000000', -... makerAssetData=asset_data_utils.encode_erc20(weth_address), -... makerFeeAssetData=asset_data_utils.encode_erc20('0x' + '00'*20), -... takerAssetData=asset_data_utils.encode_erc20(weth_address), -... takerFeeAssetData=asset_data_utils.encode_erc20('0x' + '00'*20), -... salt=random.randint(1, 100000000000000000), -... makerFee=0, -... takerFee=0, -... makerAssetAmount=1000000000000000000, -... takerAssetAmount=500000000000000000000, -... expirationTimeSeconds=round( -... (datetime.utcnow() + timedelta(days=1)).timestamp() -... ) -... ) - ->>> tx_hash = exchange.cancel_order.send_transaction( -... order=order, tx_params=TxParams(from_=maker_address) -... ) - -Once the transaction is mined, we can get the details of the cancellation -through the Exchange wrapper: - ->>> exchange.get_cancel_event(tx_hash) -(AttributeDict({'args': ...({'makerAddress': ...}), 'event': 'Cancel', ...}),) ->>> pprint(exchange.get_cancel_event(tx_hash)[0].args.__dict__) -{'feeRecipientAddress': '0x0000000000000000000000000000000000000000', - 'makerAddress': '0x...', - 'makerAssetData': b..., - 'orderHash': b..., - 'senderAddress': '0x...', - 'takerAssetData': b...} ->>> exchange.get_cancel_event(tx_hash)[0].args.feeRecipientAddress -'0x0000000000000000000000000000000000000000' - -Batching orders ----------------- - -The Exchange contract can also process multiple orders at the same time. Here -is an example where the taker fills two orders in one transaction: - ->>> order_1 = Order( -... makerAddress=maker_address, -... takerAddress='0x0000000000000000000000000000000000000000', -... senderAddress='0x0000000000000000000000000000000000000000', -... feeRecipientAddress='0x0000000000000000000000000000000000000000', -... makerAssetData=asset_data_utils.encode_erc20(zrx_address), -... makerFeeAssetData=asset_data_utils.encode_erc20('0x' + '00'*20), -... takerAssetData=asset_data_utils.encode_erc20(weth_address), -... takerFeeAssetData=asset_data_utils.encode_erc20('0x' + '00'*20), -... salt=random.randint(1, 100000000000000000), -... makerFee=0, -... takerFee=0, -... makerAssetAmount=100, -... takerAssetAmount=100, -... expirationTimeSeconds=round( -... (datetime.utcnow() + timedelta(days=1)).timestamp() -... ) -... ) ->>> signature_1 = sign_hash( -... ganache, -... Web3.toChecksumAddress(maker_address), -... generate_order_hash_hex( -... order_1, exchange.contract_address, Web3(ganache).eth.chainId -... ), -... ) ->>> order_2 = Order( -... makerAddress=maker_address, -... takerAddress='0x0000000000000000000000000000000000000000', -... senderAddress='0x0000000000000000000000000000000000000000', -... feeRecipientAddress='0x0000000000000000000000000000000000000000', -... makerAssetData=asset_data_utils.encode_erc20(zrx_address), -... makerFeeAssetData=asset_data_utils.encode_erc20('0x' + '00'*20), -... takerAssetData=asset_data_utils.encode_erc20(weth_address), -... takerFeeAssetData=asset_data_utils.encode_erc20('0x' + '00'*20), -... salt=random.randint(1, 100000000000000000), -... makerFee=0, -... takerFee=0, -... makerAssetAmount=200, -... takerAssetAmount=200, -... expirationTimeSeconds=round( -... (datetime.utcnow() + timedelta(days=1)).timestamp() -... ) -... ) ->>> signature_2 = sign_hash( -... ganache, -... Web3.toChecksumAddress(maker_address), -... generate_order_hash_hex( -... order_2, exchange.contract_address, Web3(ganache).eth.chainId -... ), -... ) - -Fill order_1 and order_2 together: - ->>> exchange.batch_fill_orders.send_transaction( -... orders=[order_1, order_2], -... taker_asset_fill_amounts=[1, 2], -... signatures=[signature_1, signature_2], -... tx_params=TxParams( -... from_=taker_address, -... value=2*web3.eth.generateGasPrice()*150000 -... ) -... ) -HexBytes('0x...') - -Estimating gas consumption --------------------------- - -Before executing a transaction, you may want to get an estimate of how much gas -will be consumed. - ->>> exchange.cancel_order.estimate_gas( -... order=Order( -... makerAddress=maker_address, -... takerAddress='0x0000000000000000000000000000000000000000', -... exchangeAddress=exchange_address, -... senderAddress='0x0000000000000000000000000000000000000000', -... feeRecipientAddress='0x0000000000000000000000000000000000000000', -... makerAssetData=asset_data_utils.encode_erc20(weth_address), -... makerFeeAssetData=asset_data_utils.encode_erc20('0x' + '00'*20), -... takerAssetData=asset_data_utils.encode_erc20(weth_address), -... takerFeeAssetData=asset_data_utils.encode_erc20('0x' + '00'*20), -... salt=random.randint(1, 100000000000000000), -... makerFee=0, -... takerFee=0, -... makerAssetAmount=1000000000000000000, -... takerAssetAmount=500000000000000000000, -... expirationTimeSeconds=round( -... (datetime.utcnow() + timedelta(days=1)).timestamp() -... ) -... ), -... tx_params=TxParams(from_=maker_address), -... ) -71... -""" - -from .tx_params import TxParams diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/asset_proxy_owner/.gitkeep b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/asset_proxy_owner/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/bases.py b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/bases.py deleted file mode 100644 index 75878c77e0..0000000000 --- a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/bases.py +++ /dev/null @@ -1,86 +0,0 @@ -"""Base wrapper class for accessing ethereum smart contracts.""" - -from typing import Any, Union - -from eth_utils import is_address, to_checksum_address -from web3 import Web3 -from web3.providers.base import BaseProvider - -from .tx_params import TxParams - - -class Validator: - """Base class for validating inputs to methods.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - ): - """Initialize the instance.""" - - def assert_valid( - self, method_name: str, parameter_name: str, argument_value: Any - ): - """Raise an exception if method input is not valid. - - :param method_name: Name of the method whose input is to be validated. - :param parameter_name: Name of the parameter whose input is to be - validated. - :param argument_value: Value of argument to parameter to be validated. - """ - - -class ContractMethod: - """Base class for wrapping an Ethereum smart contract method.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - validator: Validator = None, - ): - """Instantiate the object. - - :param provider: Instance of :class:`web3.providers.base.BaseProvider` - :param contract_address: Where the contract has been deployed to. - :param validator: Used to validate method inputs. - """ - web3 = None - if isinstance(web3_or_provider, BaseProvider): - web3 = Web3(web3_or_provider) - elif isinstance(web3_or_provider, Web3): - web3 = web3_or_provider - if web3 is None: - raise TypeError( - "Expected parameter 'web3_or_provider' to be an instance of either" - + " Web3 or BaseProvider" - ) - - self._web3_eth = web3.eth # pylint: disable=no-member - if validator is None: - validator = Validator(web3_or_provider, contract_address) - self.validator = validator - - @staticmethod - def validate_and_checksum_address(address: str): - """Validate the given address, and return it's checksum address.""" - if not is_address(address): - raise TypeError("Invalid address provided: {}".format(address)) - return to_checksum_address(address) - - def normalize_tx_params(self, tx_params) -> TxParams: - """Normalize and return the given transaction parameters.""" - if not tx_params: - tx_params = TxParams() - if not tx_params.from_: - tx_params.from_ = self._web3_eth.defaultAccount or ( - self._web3_eth.accounts[0] - if len(self._web3_eth.accounts) > 0 - else None - ) - if tx_params.from_: - tx_params.from_ = self.validate_and_checksum_address( - tx_params.from_ - ) - return tx_params diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/coordinator/.gitkeep b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/coordinator/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/coordinator_registry/.gitkeep b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/coordinator_registry/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/dev_utils/.gitkeep b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/dev_utils/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/dummy_erc20_token/.gitkeep b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/dummy_erc20_token/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/dummy_erc721_token/.gitkeep b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/dummy_erc721_token/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/dutch_auction/.gitkeep b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/dutch_auction/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/erc20_proxy/.gitkeep b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/erc20_proxy/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/erc20_token/.gitkeep b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/erc20_token/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/erc721_proxy/.gitkeep b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/erc721_proxy/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/erc721_token/.gitkeep b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/erc721_token/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/exceptions.py b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/exceptions.py deleted file mode 100644 index 32cf19f25c..0000000000 --- a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/exceptions.py +++ /dev/null @@ -1,80 +0,0 @@ -"""Exception classes common to all wrappers.""" - -from inspect import isclass -from typing import List - -from eth_abi import decode_abi - - -class RichRevert(Exception): - """Raised when a contract method returns a rich revert error.""" - - def __init__( - self, abi_signature: str, param_names: List[str], return_data: str - ): - """Populate instance variables with decoded return data values.""" - arg_start_index = abi_signature.index("(") + 1 - arg_end_index = abi_signature.index(")") - arguments = decode_abi( - abi_signature[arg_start_index:arg_end_index].split(","), - bytes.fromhex(return_data[10:]), - ) - for (param_name, argument) in zip(param_names, arguments): - setattr(self, param_name, argument) - super().__init__(vars(self)) - - -class NoExceptionForSelector(Exception): - """Indicates that no exception could be found for the given selector.""" - - -def exception_class_from_rich_revert_selector( - selector: str, exceptions_module -) -> RichRevert: - """Return the appropriate exception class. - - :param selector: A string of the format '0xffffffff' which indicates the - 4-byte ABI function selector of a rich revert error type, which is - expected to be found as a class attribute on some class in - `exceptions_module`:code:. - :param exceptions_module: The Python module in which to look for a class - with a `selector`:code: attribute matching the value of the - `selector`:code: argument. - """ - # noqa: D202 (No blank lines allowed after function docstring - def _get_rich_revert_exception_classes(): - def _exception_name_is_class_with_selector(name: str): - if not isclass(getattr(exceptions_module, name)): - return False - - try: - getattr(exceptions_module, name).selector - except AttributeError: - return False - - return True - - def _convert_class_name_to_class(name: str): - return getattr(exceptions_module, name) - - return list( - map( - _convert_class_name_to_class, - filter( - _exception_name_is_class_with_selector, - dir(exceptions_module), - ), - ) - ) - - rich_reverts = _get_rich_revert_exception_classes() - - try: - return next( - filter( - lambda rich_revert: rich_revert.selector == selector, - rich_reverts, - ) - ) - except StopIteration: - raise NoExceptionForSelector(selector) diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/exchange/exceptions.py b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/exchange/exceptions.py deleted file mode 100644 index ab60b845ac..0000000000 --- a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/exchange/exceptions.py +++ /dev/null @@ -1,341 +0,0 @@ -"""Exchange-specific exception classes.""" - -from enum import auto, Enum - -from zero_ex.contract_wrappers.exceptions import RichRevert - -# pylint: disable=missing-docstring - - -class AssetProxyDispatchErrorCodes(Enum): # noqa: D101 (missing docstring) - INVALID_ASSET_DATA_LENGTH = 0 - UNKNOWN_ASSET_PROXY = auto() - - -class BatchMatchOrdersErrorCodes(Enum): # noqa: D101 (missing docstring) - ZERO_LEFT_ORDERS = 0 - ZERO_RIGHT_ORDERS = auto() - INVALID_LENGTH_LEFT_SIGNATURES = auto() - INVALID_LENGTH_RIGHT_SIGNATURES = auto() - - -class ExchangeContextErrorCodes(Enum): # noqa: D101 (missing docstring) - INVALID_MAKER = 0 - INVALID_TAKER = auto() - INVALID_SENDER = auto() - - -class FillErrorCodes(Enum): # noqa: D101 (missing docstring) - INVALID_TAKER_AMOUNT = 0 - TAKER_OVERPAY = auto() - OVERFILL = auto() - INVALID_FILL_PRICE = auto() - - -class SignatureErrorCodes(Enum): # noqa: D101 (missing docstring) - BAD_ORDER_SIGNATURE = 0 - BAD_TRANSACTION_SIGNATURE = auto() - INVALID_LENGTH = auto() - UNSUPPORTED = auto() - ILLEGAL = auto() - INAPPROPRIATE_SIGNATURE_TYPE = auto() - INVALID_SIGNER = auto() - - -class TransactionErrorCodes(Enum): # noqa: D101 (missing docstring) - ALREADY_EXECUTED = 0 - EXPIRED = auto() - - -class IncompleteFillErrorCode(Enum): # noqa: D101 (missing docstring) - INCOMPLETE_MARKET_BUY_ORDERS = 0 - INCOMPLETE_MARKET_SELL_ORDERS = auto() - INCOMPLETE_FILL_ORDER = auto() - - -class SignatureError(RichRevert): # noqa: D101 (missing docstring) - def __init__(self, return_data): # noqa: D107 (missing docstring) - super().__init__( - "SignatureError(uint8,bytes32,address,bytes)", - ["errorCode", "hash", "signerAddress", "signature"], - return_data, - ) - - errorCode: SignatureErrorCodes - hash: bytes - signerAddress: str - signature: bytes - - selector = "0x7e5a2318" - - -class SignatureValidatorNotApprovedError( - RichRevert -): # noqa: D101 (missing docstring) - def __init__(self, return_data): # noqa: D107 (missing docstring) - super().__init__( - "SignatureValidatorNotApprovedError(address,address)", - ["signerAddress", "validatorAddress"], - return_data, - ) - - signerAddress: str - validatorAddress: str - - selector = "0xa15c0d06" - - -class EIP1271SignatureError(RichRevert): # noqa: D101 (missing docstring) - def __init__(self, return_data): # noqa: D107 (missing docstring) - super().__init__( - "EIP1271SignatureError(address,bytes,bytes,bytes)", - ["verifyingContractAddress", "data", "signature", "errorData"], - return_data, - ) - - verifyingContractAddress: str - data: bytes - signature: bytes - errorData: bytes - - selector = "0x5bd0428d" - - -class SignatureWalletError(RichRevert): # noqa: D101 (missing docstring) - def __init__(self, return_data): # noqa: D107 (missing docstring) - super().__init__( - "SignatureWalletError(bytes32,address,bytes,bytes)", - ["hash", "walletAddress", "signature", "errorData"], - return_data, - ) - - hash: bytes - walletAddress: str - signature: bytes - errorData: bytes - - selector = "0x1b8388f7" - - -class OrderStatusError(RichRevert): # noqa: D101 (missing docstring) - def __init__(self, return_data): # noqa: D107 (missing docstring) - super().__init__( - "OrderStatusError(bytes32,uint8)", - ["orderHash", "orderStatus"], - return_data, - ) - - orderHash: bytes - orderStatus: int - - selector = "0xfdb6ca8d" - - -class ExchangeInvalidContextError( - RichRevert -): # noqa: D101 (missing docstring) - def __init__(self, return_data): # noqa: D107 (missing docstring) - super().__init__( - "ExchangeInvalidContextError(uint8,bytes32,address)", - ["errorCode", "orderHash", "contextAddress"], - return_data, - ) - - errorCode: ExchangeContextErrorCodes - orderHash: bytes - contextAddress: str - - selector = "0xe53c76c8" - - -class FillError(RichRevert): # noqa: D101 (missing docstring) - def __init__(self, return_data): # noqa: D107 (missing docstring) - super().__init__( - "FillError(uint8,bytes32)", ["errorCode", "orderHash"], return_data - ) - - errorCode: FillErrorCodes - orderHash: bytes - - selector = "0xe94a7ed0" - - -class OrderEpochError(RichRevert): # noqa: D101 (missing docstring) - def __init__(self, return_data): # noqa: D107 (missing docstring) - super().__init__( - "OrderEpochError(address,address,uint256)", - ["makerAddress", "orderSenderAddress", "currentEpoch"], - return_data, - ) - - makerAddress: str - orderSenderAddress: str - currentEpoch: int - - selector = "0x4ad31275" - - -class AssetProxyExistsError(RichRevert): # noqa: D101 (missing docstring) - def __init__(self, return_data): # noqa: D107 (missing docstring) - super().__init__( - "AssetProxyExistsError(bytes4,address)", - ["assetProxyId", "assetProxyAddress"], - return_data, - ) - - assetProxyId: bytes - assetProxyAddress: str - - selector = "0x11c7b720" - - -class AssetProxyDispatchError(RichRevert): # noqa: D101 (missing docstring) - def __init__(self, return_data): # noqa: D107 (missing docstring) - super().__init__( - "AssetProxyDispatchError(uint8,bytes32,bytes)", - ["errorCode", "orderHash", "assetData"], - return_data, - ) - - errorCode: AssetProxyDispatchErrorCodes - orderHash: bytes - assetData: bytes - - selector = "0x488219a6" - - -class AssetProxyTransferError(RichRevert): # noqa: D101 (missing docstring) - def __init__(self, return_data): # noqa: D107 (missing docstring) - super().__init__( - "AssetProxyTransferError(bytes32,bytes,bytes)", - ["orderHash", "assetData", "errorData"], - return_data, - ) - - orderHash: bytes - assetData: bytes - errorData: bytes - - selector = "0x4678472b" - - -class NegativeSpreadError(RichRevert): # noqa: D101 (missing docstring) - def __init__(self, return_data): # noqa: D107 (missing docstring) - super().__init__( - "NegativeSpreadError(bytes32,bytes32)", - ["leftOrderHash", "rightOrderHash"], - return_data, - ) - - leftOrderHash: bytes - rightOrderHash: bytes - - selector = "0xb6555d6f" - - -class TransactionError(RichRevert): # noqa: D101 (missing docstring) - def __init__(self, return_data): # noqa: D107 (missing docstring) - super().__init__( - "TransactionError(uint8,bytes32)", - ["errorCode", "transactionHash"], - return_data, - ) - - errorCode: TransactionErrorCodes - transactionHash: bytes - - selector = "0xf5985184" - - -class TransactionExecutionError(RichRevert): # noqa: D101 (missing docstring) - def __init__(self, return_data): # noqa: D107 (missing docstring) - super().__init__( - "TransactionExecutionError(bytes32,bytes)", - ["transactionHash", "errorData"], - return_data, - ) - - transactionHash: bytes - errorData: bytes - - selector = "0x20d11f61" - - -class TransactionGasPriceError(RichRevert): # noqa: D101 (missing docstring) - def __init__(self, return_data): # noqa: D107 (missing docstring) - super().__init__( - "TransactionGasPriceError(bytes32,uint256,uint256)", - ["transactionHash", "actualGasPrice", "requiredGasPrice"], - return_data, - ) - - transactionHash: bytes - actualGasPrice: int - requiredGasPrice: int - - selector = "0xa26dac09" - - -class TransactionInvalidContextError( - RichRevert -): # noqa: D101 (missing docstring) - def __init__(self, return_data): # noqa: D107 (missing docstring) - super().__init__( - "TransactionInvalidContextError(bytes32,address)", - ["transactionHash", "currentContextAddress"], - return_data, - ) - - transactionHash: bytes - currentContextAddress: str - - selector = "0xdec4aedf" - - -class IncompleteFillError(RichRevert): # noqa: D101 (missing docstring) - def __init__(self, return_data): # noqa: D107 (missing docstring) - super().__init__( - "IncompleteFillError(uint8,uint256,uint256)", - ["errorCode", "expectedAssetAmount", "actualAssetAmount"], - return_data, - ) - - errorCode: IncompleteFillErrorCode - expectedAssetAmount: int - actualAssetAmount: int - - selector = "0x18e4b141" - - -class BatchMatchOrdersError(RichRevert): # noqa: D101 (missing docstring) - def __init__(self, return_data): # noqa: D107 (missing docstring) - super().__init__( - "BatchMatchOrdersError(uint8)", ["errorCode"], return_data - ) - - errorCode: BatchMatchOrdersErrorCodes - - selector = "0xd4092f4f" - - -class PayProtocolFeeError(RichRevert): # noqa: D101 (missing docstring) - def __init__(self, return_data): # noqa: D107 (missing docstring) - super().__init__( - "PayProtocolFeeError(bytes32,uint256,address,address,bytes)", - [ - "orderHash", - "protocolFee", - "makerAddress", - "takerAddress", - "errorData", - ], - return_data, - ) - - orderHash: bytes - protocolFee: int - makerAddress: str - takerAddress: str - errorData: bytes - - selector = "0x87cb1e75" diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/exchange/middleware.py b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/exchange/middleware.py deleted file mode 100644 index 4b509fdd8c..0000000000 --- a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/exchange/middleware.py +++ /dev/null @@ -1,36 +0,0 @@ -"""Web3.py-compatible middleware to be injected upon contract instantiation.""" - -from zero_ex.contract_wrappers.exceptions import ( - exception_class_from_rich_revert_selector, - NoExceptionForSelector, -) - -from . import exceptions - - -def rich_revert_handler(make_request, _): - """Return a middlware to raise exceptions for rich revert return data.""" - # noqa: D202 (No blank lines allowed after function docstring - def middleware(method, params): - response = make_request(method, params) - try: - raise exception_class_from_rich_revert_selector( - response["result"][0:10], exceptions - )(response["result"]) - except NoExceptionForSelector: - # response prefix didn't indicate a known error - pass - except TypeError: - # eg "unhashable type: 'slice'". if response["result"] isn't - # sliceable (eg if it's a dict), then it definitely isn't a rich - # revert. - pass - except KeyError: - # response doesn't have a "result" key - pass - return response - - return middleware - - -MIDDLEWARE = [{"layer": 0, "function": rich_revert_handler}] diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/exchange/types.py b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/exchange/types.py deleted file mode 100644 index d324655f72..0000000000 --- a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/exchange/types.py +++ /dev/null @@ -1,75 +0,0 @@ -"""Conveniences for handling types representing Exchange Solidity structs. - -The `TypedDict`:code: classes in the .exchange module represent tuples -encountered in the Exchange contract's ABI. However, they have weird names, -containing hashes of the tuple's field names, because the name of a Solidity -`struct`:code: isn't conveyed through the ABI. This module provides type -aliases with human-friendly names. -""" - -from enum import auto, Enum - -from . import ( - LibFillResultsFillResults, - LibOrderOrder, - LibFillResultsMatchedFillResults, - LibZeroExTransactionZeroExTransaction, - LibOrderOrderInfo, -) - - -# Would rather not repeat ourselves below, but base classes are mentioned in -# the class docstrings because of a bug in sphinx rendering. Using the `.. -# autoclass` directive, with the `:show-inheritance:` role, results in docs -# being rendered with just "Bases: dict", and no mention of the direct ancestor -# of each of these classes. - - -class FillResults(LibFillResultsFillResults): - """The `FillResults`:code: Solidity struct. - - Also known as - `zero_ex.contract_wrappers.exchange.LibFillResultsFillResults`:py:class:. - """ - - -class Order(LibOrderOrder): - """The `Order`:code: Solidity struct. - - Also known as - `zero_ex.contract_wrappers.exchange.LibOrderOrder`:py:class:. - """ - - -class MatchedFillResults(LibFillResultsMatchedFillResults): - """The `MatchedFillResults`:code: Solidity struct. - - Also known as - `zero_ex.contract_wrappers.exchange.LibFillResultsMatchedFillResults`:py:class:. - """ - - -class ZeroExTransaction(LibZeroExTransactionZeroExTransaction): - """The `ZeroExTransaction`:code: Solidity struct. - - Also known as - `zero_ex.contract_wrappers.exchange.LibZeroExTransactionZeroExTransaction`:py:class:. - """ - - -class OrderInfo(LibOrderOrderInfo): - """The `OrderInfo`:code: Solidity struct. - - Also known as - `zero_ex.contract_wrappers.exchange.LibOrderOrderInfo`:py:class:. - """ - - -class OrderStatus(Enum): # noqa: D101 # pylint: disable=missing-docstring - INVALID = 0 - INVALID_MAKER_ASSET_AMOUNT = auto() - INVALID_TAKER_ASSET_AMOUNT = auto() - FILLABLE = auto() - EXPIRED = auto() - FULLY_FILLED = auto() - CANCELLED = auto() diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/exchange/validator.py b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/exchange/validator.py deleted file mode 100644 index bf9ec40a3b..0000000000 --- a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/exchange/validator.py +++ /dev/null @@ -1,64 +0,0 @@ -"""Validate inputs to the Exchange contract.""" - -from typing import Any, Union - -from web3 import Web3 -from web3.providers.base import BaseProvider - -from zero_ex import json_schemas -from zero_ex.contract_wrappers.order_conversions import order_to_jsdict - -from ..bases import Validator - - -class ExchangeValidator(Validator): - """Validate inputs to Exchange methods.""" - - def __init__( - self, - web3_or_provider: Union[Web3, BaseProvider], - contract_address: str, - ): - """Initialize the class.""" - super().__init__(web3_or_provider, contract_address) - - web3 = None - if isinstance(web3_or_provider, BaseProvider): - web3 = Web3(web3_or_provider) - elif isinstance(web3_or_provider, Web3): - web3 = web3_or_provider - if web3 is None: - raise TypeError( - "Expected parameter 'web3_or_provider' to be an instance of either" - + " Web3 or BaseProvider" - ) - - self.contract_address = contract_address - self.chain_id = web3.eth.chainId - - def assert_valid( - self, method_name: str, parameter_name: str, argument_value: Any - ) -> None: - """Raise an exception if method input is not valid. - - :param method_name: Name of the method whose input is to be validated. - :param parameter_name: Name of the parameter whose input is to be - validated. - :param argument_value: Value of argument to parameter to be validated. - """ - if parameter_name == "order": - json_schemas.assert_valid( - order_to_jsdict( - argument_value, self.chain_id, self.contract_address - ), - "/orderSchema", - ) - - if parameter_name == "orders": - for order in argument_value: - json_schemas.assert_valid( - order_to_jsdict( - order, self.chain_id, self.contract_address - ), - "/orderSchema", - ) diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/forwarder/.gitkeep b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/forwarder/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/i_asset_proxy/.gitkeep b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/i_asset_proxy/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/i_validator/.gitkeep b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/i_validator/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/i_wallet/.gitkeep b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/i_wallet/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/multi_asset_proxy/.gitkeep b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/multi_asset_proxy/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/order_conversions.py b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/order_conversions.py deleted file mode 100644 index a639ffe1c5..0000000000 --- a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/order_conversions.py +++ /dev/null @@ -1,185 +0,0 @@ -"""Utilities to convert between JSON and Python-native objects. - -Converting between the JSON wire format and the types accepted by Web3.py (eg -`bytes` vs `str`) can be onerous. This module provides conveniences for -converting Exchange structs between JSON and Python objects. -""" - -from copy import copy -from typing import cast, Dict, Union - -from eth_utils import remove_0x_prefix - -from zero_ex.json_schemas import assert_valid -from zero_ex.contract_wrappers.exchange.types import Order - - -def order_to_jsdict( - order: Order, - chain_id: int, - exchange_address="0x0000000000000000000000000000000000000000", - signature: str = None, -) -> dict: - """Convert a Web3-compatible order struct to a JSON-schema-compatible dict. - - More specifically, do explicit decoding for the `bytes`:code: fields, and - convert numerics to strings. - - >>> import pprint - >>> pprint.pprint(order_to_jsdict( - ... { - ... 'makerAddress': "0x0000000000000000000000000000000000000000", - ... 'takerAddress': "0x0000000000000000000000000000000000000000", - ... 'feeRecipientAddress': - ... "0x0000000000000000000000000000000000000000", - ... 'senderAddress': "0x0000000000000000000000000000000000000000", - ... 'makerAssetAmount': 1, - ... 'takerAssetAmount': 1, - ... 'makerFee': 0, - ... 'takerFee': 0, - ... 'expirationTimeSeconds': 1, - ... 'salt': 1, - ... 'makerAssetData': (0).to_bytes(1, byteorder='big') * 20, - ... 'takerAssetData': (0).to_bytes(1, byteorder='big') * 20, - ... 'makerFeeAssetData': (0).to_bytes(1, byteorder='big') * 20, - ... 'takerFeeAssetData': (0).to_bytes(1, byteorder='big') * 20, - ... }, - ... chain_id=50 - ... )) - {'chainId': 50, - 'exchangeAddress': '0x0000000000000000000000000000000000000000', - 'expirationTimeSeconds': '1', - 'feeRecipientAddress': '0x0000000000000000000000000000000000000000', - 'makerAddress': '0x0000000000000000000000000000000000000000', - 'makerAssetAmount': '1', - 'makerAssetData': '0x0000000000000000000000000000000000000000', - 'makerFee': '0', - 'makerFeeAssetData': '0x0000000000000000000000000000000000000000', - 'salt': '1', - 'senderAddress': '0x0000000000000000000000000000000000000000', - 'takerAddress': '0x0000000000000000000000000000000000000000', - 'takerAssetAmount': '1', - 'takerAssetData': '0x0000000000000000000000000000000000000000', - 'takerFee': '0', - 'takerFeeAssetData': '0x0000000000000000000000000000000000000000'} - """ - jsdict = cast(Dict, copy(order)) - - def encode_bytes(bytes_or_str: Union[bytes, str]) -> bytes: - def ensure_hex_prefix(hex_str: str): - if hex_str[0:2] != "0x": - hex_str = "0x" + hex_str - return hex_str - - return ensure_hex_prefix( - cast(bytes, bytes_or_str).hex() - if isinstance(bytes_or_str, bytes) - else bytes_or_str - ) - - jsdict["makerAssetData"] = encode_bytes(order["makerAssetData"]) - jsdict["takerAssetData"] = encode_bytes(order["takerAssetData"]) - jsdict["makerFeeAssetData"] = encode_bytes(order["makerFeeAssetData"]) - jsdict["takerFeeAssetData"] = encode_bytes(order["takerFeeAssetData"]) - - jsdict["exchangeAddress"] = exchange_address - - jsdict["expirationTimeSeconds"] = str(order["expirationTimeSeconds"]) - - jsdict["makerAssetAmount"] = str(order["makerAssetAmount"]) - jsdict["takerAssetAmount"] = str(order["takerAssetAmount"]) - - jsdict["makerFee"] = str(order["makerFee"]) - jsdict["takerFee"] = str(order["takerFee"]) - - jsdict["salt"] = str(order["salt"]) - - jsdict["chainId"] = chain_id - - if signature is not None: - jsdict["signature"] = signature - - assert_valid(jsdict, "/orderSchema") - - return jsdict - - -def jsdict_to_order(jsdict: dict) -> Order: - r"""Convert a JSON-schema-compatible dict order to a Web3-compatible struct. - - More specifically, do explicit encoding of the `bytes`:code: fields, and - parse integers from strings. - - >>> import pprint - >>> pprint.pprint(jsdict_to_order( - ... { - ... 'makerAddress': "0x0000000000000000000000000000000000000000", - ... 'takerAddress': "0x0000000000000000000000000000000000000000", - ... 'feeRecipientAddress': "0x0000000000000000000000000000000000000000", - ... 'senderAddress': "0x0000000000000000000000000000000000000000", - ... 'makerAssetAmount': "1000000000000000000", - ... 'takerAssetAmount': "1000000000000000000", - ... 'makerFee': "0", - ... 'takerFee': "0", - ... 'expirationTimeSeconds': "12345", - ... 'salt': "12345", - ... 'makerAssetData': "0x0000000000000000000000000000000000000000", - ... 'takerAssetData': "0x0000000000000000000000000000000000000000", - ... 'makerFeeAssetData': "0x0000000000000000000000000000000000000000", - ... 'takerFeeAssetData': "0x0000000000000000000000000000000000000000", - ... 'exchangeAddress': "0x0000000000000000000000000000000000000000", - ... 'chainId': 50 - ... }, - ... )) - {'chainId': 50, - 'expirationTimeSeconds': 12345, - 'feeRecipientAddress': '0x0000000000000000000000000000000000000000', - 'makerAddress': '0x0000000000000000000000000000000000000000', - 'makerAssetAmount': 1000000000000000000, - 'makerAssetData': b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - b'\x00\x00\x00\x00\x00\x00\x00\x00', - 'makerFee': 0, - 'makerFeeAssetData': b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - b'\x00\x00\x00\x00\x00\x00\x00\x00', - 'salt': 12345, - 'senderAddress': '0x0000000000000000000000000000000000000000', - 'takerAddress': '0x0000000000000000000000000000000000000000', - 'takerAssetAmount': 1000000000000000000, - 'takerAssetData': b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - b'\x00\x00\x00\x00\x00\x00\x00\x00', - 'takerFee': 0, - 'takerFeeAssetData': b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - b'\x00\x00\x00\x00\x00\x00\x00\x00'} - """ # noqa: E501 (line too long) - assert_valid(jsdict, "/orderSchema") - - order = cast(Order, copy(jsdict)) - - order["makerAssetData"] = bytes.fromhex( - remove_0x_prefix(jsdict["makerAssetData"]) - ) - order["makerFeeAssetData"] = bytes.fromhex( - remove_0x_prefix(jsdict["makerFeeAssetData"]) - ) - order["takerAssetData"] = bytes.fromhex( - remove_0x_prefix(jsdict["takerAssetData"]) - ) - order["takerFeeAssetData"] = bytes.fromhex( - remove_0x_prefix(jsdict["takerFeeAssetData"]) - ) - - order["makerAssetAmount"] = int(jsdict["makerAssetAmount"]) - order["takerAssetAmount"] = int(jsdict["takerAssetAmount"]) - - order["makerFee"] = int(jsdict["makerFee"]) - order["takerFee"] = int(jsdict["takerFee"]) - - order["expirationTimeSeconds"] = int(jsdict["expirationTimeSeconds"]) - - order["salt"] = int(jsdict["salt"]) - - del order["exchangeAddress"] # type: ignore - # silence mypy pending release of - # https://github.com/python/mypy/issues/3550 - - return order diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/order_validator/.gitkeep b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/order_validator/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/py.typed b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/py.typed deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/tx_params.py b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/tx_params.py deleted file mode 100644 index 226a1f908e..0000000000 --- a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/tx_params.py +++ /dev/null @@ -1,42 +0,0 @@ -"""Transaction parameters for use with contract wrappers.""" - -from typing import Optional - -import attr - - -@attr.s(kw_only=True) -class TxParams: - """Transaction parameters for use with contract wrappers. - - :param from_: default None, string of account address to initiate tx from - :param value: default None, integer of amount of ETH in Wei for transfer - :param gas: default None, integer maximum amount of ETH in Wei for gas - :param grasPrice: default None, integer price of unit of gas - :param nonce: default None, integer nonce for account - """ - - from_: Optional[str] = attr.ib(default=None) - value: Optional[int] = attr.ib( - default=None, converter=attr.converters.optional(int) - ) - gas: Optional[int] = attr.ib( - default=None, converter=attr.converters.optional(int) - ) - gas_price: Optional[int] = attr.ib( - default=None, converter=attr.converters.optional(int) - ) - nonce: Optional[int] = attr.ib( - default=None, converter=attr.converters.optional(int) - ) - - def as_dict(self): - """Get transaction params as dict appropriate for web3.""" - res = {k: v for k, v in attr.asdict(self).items() if v is not None} - if "from_" in res: - res["from"] = res["from_"] - del res["from_"] - if "gas_price" in res: - res["gasPrice"] = res["gas_price"] - del res["gas_price"] - return res diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/weth9/.gitkeep b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/weth9/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/zrx_token/.gitkeep b/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/zrx_token/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_wrappers/stubs/distutils/__init__.pyi b/python-packages/contract_wrappers/stubs/distutils/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_wrappers/stubs/distutils/command/__init__.pyi b/python-packages/contract_wrappers/stubs/distutils/command/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_wrappers/stubs/distutils/command/clean.pyi b/python-packages/contract_wrappers/stubs/distutils/command/clean.pyi deleted file mode 100644 index 46a42ddb13..0000000000 --- a/python-packages/contract_wrappers/stubs/distutils/command/clean.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from distutils.core import Command - -class clean(Command): - def initialize_options(self: clean) -> None: ... - def finalize_options(self: clean) -> None: ... - def run(self: clean) -> None: ... - ... diff --git a/python-packages/contract_wrappers/stubs/eth_account/__init__.pyi b/python-packages/contract_wrappers/stubs/eth_account/__init__.pyi deleted file mode 100644 index 5caed9e96f..0000000000 --- a/python-packages/contract_wrappers/stubs/eth_account/__init__.pyi +++ /dev/null @@ -1 +0,0 @@ -class Account: ... diff --git a/python-packages/contract_wrappers/stubs/eth_account/local.pyi b/python-packages/contract_wrappers/stubs/eth_account/local.pyi deleted file mode 100644 index d0b3515699..0000000000 --- a/python-packages/contract_wrappers/stubs/eth_account/local.pyi +++ /dev/null @@ -1,3 +0,0 @@ -class LocalAccount: - address: str - ... diff --git a/python-packages/contract_wrappers/stubs/eth_utils/__init__.pyi b/python-packages/contract_wrappers/stubs/eth_utils/__init__.pyi deleted file mode 100644 index c541dc5e42..0000000000 --- a/python-packages/contract_wrappers/stubs/eth_utils/__init__.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from typing import Union - -def to_checksum_address(address: str) -> str: ... - -def remove_0x_prefix(hex_string: str) -> str: ... - -def is_address(address: Union[str, bytes]) -> bool: ... diff --git a/python-packages/contract_wrappers/stubs/hexbytes/__init__.pyi b/python-packages/contract_wrappers/stubs/hexbytes/__init__.pyi deleted file mode 100644 index bc88efe52a..0000000000 --- a/python-packages/contract_wrappers/stubs/hexbytes/__init__.pyi +++ /dev/null @@ -1 +0,0 @@ -class HexBytes: ... diff --git a/python-packages/contract_wrappers/stubs/pytest/__init__.pyi b/python-packages/contract_wrappers/stubs/pytest/__init__.pyi deleted file mode 100644 index d9209ab5b9..0000000000 --- a/python-packages/contract_wrappers/stubs/pytest/__init__.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from typing import Callable - -def fixture(scope: str) -> Callable: - ... - -class ExceptionInfo: - ... - -def raises(exception: Exception) -> ExceptionInfo: ... \ No newline at end of file diff --git a/python-packages/contract_wrappers/stubs/setuptools/__init__.pyi b/python-packages/contract_wrappers/stubs/setuptools/__init__.pyi deleted file mode 100644 index 8ea8d32b7e..0000000000 --- a/python-packages/contract_wrappers/stubs/setuptools/__init__.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from distutils.dist import Distribution -from typing import Any, List - -def setup(**attrs: Any) -> Distribution: ... - -class Command: ... - -def find_packages(where: str) -> List[str]: ... diff --git a/python-packages/contract_wrappers/stubs/setuptools/command/__init__.pyi b/python-packages/contract_wrappers/stubs/setuptools/command/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_wrappers/stubs/setuptools/command/test.pyi b/python-packages/contract_wrappers/stubs/setuptools/command/test.pyi deleted file mode 100644 index c5ec770ad3..0000000000 --- a/python-packages/contract_wrappers/stubs/setuptools/command/test.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from setuptools import Command - -class test(Command): ... diff --git a/python-packages/contract_wrappers/stubs/sha3/__init__.pyi b/python-packages/contract_wrappers/stubs/sha3/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_wrappers/stubs/web3/__init__.pyi b/python-packages/contract_wrappers/stubs/web3/__init__.pyi deleted file mode 100644 index 1dfa4bb5f5..0000000000 --- a/python-packages/contract_wrappers/stubs/web3/__init__.pyi +++ /dev/null @@ -1,67 +0,0 @@ -from typing import Any, Callable, Dict, List, Optional, Union - -from hexbytes import HexBytes -from eth_account.local import LocalAccount -from web3 import datastructures -from web3.contract import Contract -from web3.providers.base import BaseProvider - - -class Web3: - class HTTPProvider(BaseProvider): - ... - - def __init__(self, provider: BaseProvider) -> None: ... - - @staticmethod - def sha3( - primitive: Optional[Union[bytes, int, None]] = None, - text: Optional[str] = None, - hexstr: Optional[str] = None - ) -> bytes: ... - - @staticmethod - def isAddress(address: str) -> bool: ... - - class middleware_stack: - @staticmethod - def get(key: str) -> Callable: ... - - def inject( - self, middleware_func: object, layer: object - ) -> None: ... - - ... - - middleware_onion: middleware_stack - - class net: - version: str - ... - - - class Eth: - defaultAccount: str - accounts: List[str] - chainId: int - ... - - class account: - @staticmethod - def privateKeyToAccount(private_key: str) -> LocalAccount: ... - ... - - @staticmethod - def getTransactionReceipt(tx_hash: Union[HexBytes, bytes]) -> Any: ... - - @staticmethod - def contract(address: str, abi: Dict) -> Contract: ... - ... - - @staticmethod - def isAddress(address: str) -> bool: ... - ... - - eth: Eth - - ... diff --git a/python-packages/contract_wrappers/stubs/web3/contract.pyi b/python-packages/contract_wrappers/stubs/web3/contract.pyi deleted file mode 100644 index 6f575e5b39..0000000000 --- a/python-packages/contract_wrappers/stubs/web3/contract.pyi +++ /dev/null @@ -1,17 +0,0 @@ -from typing import Any - - -class Contract: - def call(self): ... - - functions: Any - - events: Any - ... - - -class ContractFunction: - def __call__(self, *args, **kwargs): - ... - - ... diff --git a/python-packages/contract_wrappers/stubs/web3/datastructures.pyi b/python-packages/contract_wrappers/stubs/web3/datastructures.pyi deleted file mode 100644 index fac8f29268..0000000000 --- a/python-packages/contract_wrappers/stubs/web3/datastructures.pyi +++ /dev/null @@ -1,5 +0,0 @@ -class NamedElementOnion: - ... - -class AttributeDict: - ... \ No newline at end of file diff --git a/python-packages/contract_wrappers/stubs/web3/exceptions.pyi b/python-packages/contract_wrappers/stubs/web3/exceptions.pyi deleted file mode 100644 index 83abf973d1..0000000000 --- a/python-packages/contract_wrappers/stubs/web3/exceptions.pyi +++ /dev/null @@ -1,2 +0,0 @@ -class BadFunctionCallOutput(Exception): - ... diff --git a/python-packages/contract_wrappers/stubs/web3/gas_strategies/__init__.pyi b/python-packages/contract_wrappers/stubs/web3/gas_strategies/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_wrappers/stubs/web3/gas_strategies/rpc.pyi b/python-packages/contract_wrappers/stubs/web3/gas_strategies/rpc.pyi deleted file mode 100644 index 34d58f9786..0000000000 --- a/python-packages/contract_wrappers/stubs/web3/gas_strategies/rpc.pyi +++ /dev/null @@ -1,2 +0,0 @@ -def rpc_gas_price_strategy(): - ... diff --git a/python-packages/contract_wrappers/stubs/web3/providers/__init__.pyi b/python-packages/contract_wrappers/stubs/web3/providers/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/contract_wrappers/stubs/web3/providers/base.pyi b/python-packages/contract_wrappers/stubs/web3/providers/base.pyi deleted file mode 100644 index 82ca9e3da1..0000000000 --- a/python-packages/contract_wrappers/stubs/web3/providers/base.pyi +++ /dev/null @@ -1,2 +0,0 @@ -class BaseProvider: - ... diff --git a/python-packages/contract_wrappers/test/__init__.py b/python-packages/contract_wrappers/test/__init__.py deleted file mode 100644 index 30ad154b25..0000000000 --- a/python-packages/contract_wrappers/test/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Tests of zero_ex.contract_wrappers.""" diff --git a/python-packages/contract_wrappers/test/conftest.py b/python-packages/contract_wrappers/test/conftest.py deleted file mode 100644 index a0c7c8aa8c..0000000000 --- a/python-packages/contract_wrappers/test/conftest.py +++ /dev/null @@ -1,70 +0,0 @@ -"""Fixtures for pytest.""" - -import pytest -from eth_utils import to_checksum_address -from web3 import Web3 - -from zero_ex.order_utils import asset_data_utils -from zero_ex.contract_addresses import chain_to_addresses, ChainId -from zero_ex.contract_artifacts import abi_by_name - - -@pytest.fixture(scope="module") -def ganache_provider(): - """Get a ganache web3 provider.""" - return Web3.HTTPProvider(endpoint_uri="http://127.0.0.1:8545") - - -@pytest.fixture(scope="module") -def web3_instance(ganache_provider): # pylint: disable=redefined-outer-name - """Get a web3 instance.""" - return Web3(ganache_provider) - - -@pytest.fixture(scope="module") -def web3_eth(web3_instance): # pylint: disable=redefined-outer-name - """Get web3 instance's eth member.""" - return web3_instance.eth # pylint: disable=no-member - - -@pytest.fixture(scope="module") -def accounts(web3_eth): # pylint: disable=redefined-outer-name - """Get the accounts associated with the test web3_eth instance.""" - return web3_eth.accounts - - -@pytest.fixture(scope="module") -def erc20_proxy_address(): - """Get the 0x ERC20 Proxy address.""" - return chain_to_addresses(ChainId.GANACHE).erc20_proxy - - -@pytest.fixture(scope="module") -def weth_asset_data(): # pylint: disable=redefined-outer-name - """Get 0x asset data for Wrapped Ether (WETH) token.""" - return asset_data_utils.encode_erc20( - chain_to_addresses(ChainId.GANACHE).ether_token - ) - - -@pytest.fixture(scope="module") -def weth_instance(web3_eth): # pylint: disable=redefined-outer-name - """Get an instance of the WrapperEther contract.""" - return web3_eth.contract( - address=to_checksum_address( - chain_to_addresses(ChainId.GANACHE).ether_token - ), - abi=abi_by_name("WETH9"), - ) - - -@pytest.fixture(scope="module") -def zrx_address(): - """Get address of ZRX token for Ganache chain.""" - return chain_to_addresses(ChainId.GANACHE).zrx_token - - -@pytest.fixture(scope="module") -def zrx_asset_data(zrx_address): # pylint: disable=redefined-outer-name - """Get 0x asset data for ZRX token.""" - return asset_data_utils.encode_erc20(zrx_address) diff --git a/python-packages/contract_wrappers/test/test_base_contract_method.py b/python-packages/contract_wrappers/test/test_base_contract_method.py deleted file mode 100644 index 78e7140950..0000000000 --- a/python-packages/contract_wrappers/test/test_base_contract_method.py +++ /dev/null @@ -1,15 +0,0 @@ -"""Tests for :class:`ContractMethod`.""" - -import pytest - -from zero_ex.contract_addresses import chain_to_addresses, ChainId -from zero_ex.contract_wrappers.bases import ContractMethod - - -@pytest.fixture(scope="module") -def contract_wrapper(ganache_provider): - """Get a ContractMethod instance for testing.""" - return ContractMethod( - web3_or_provider=ganache_provider, - contract_address=chain_to_addresses(ChainId.GANACHE).ether_token, - ) diff --git a/python-packages/contract_wrappers/test/test_erc20_wrapper.py b/python-packages/contract_wrappers/test/test_erc20_wrapper.py deleted file mode 100644 index 01044322f6..0000000000 --- a/python-packages/contract_wrappers/test/test_erc20_wrapper.py +++ /dev/null @@ -1,76 +0,0 @@ -"""Tests for ERC20Token wrapper.""" - -from decimal import Decimal - -import pytest - -from zero_ex.contract_addresses import chain_to_addresses, ChainId -from zero_ex.contract_wrappers import TxParams -from zero_ex.contract_wrappers.erc20_token import ERC20Token - - -MAX_ALLOWANCE = int("{:.0f}".format(Decimal(2) ** 256 - 1)) - - -@pytest.fixture(scope="module") -def erc20_wrapper(ganache_provider): - """Get an instance of ERC20Token wrapper class for testing.""" - return ERC20Token( - ganache_provider, chain_to_addresses(ChainId.GANACHE).ether_token - ) - - -def test_erc20_wrapper__balance_of( - accounts, - erc20_wrapper, # pylint: disable=redefined-outer-name - weth_instance, # pylint: disable=redefined-outer-name -): - """Test getting baance of an account for an ERC20 token.""" - acc1_original_weth_balance = erc20_wrapper.balance_of.call(accounts[0]) - acc2_original_weth_balance = erc20_wrapper.balance_of.call(accounts[1]) - - expected_difference = 1 * 10 ** 18 - - weth_instance.functions.deposit().transact( - {"from": accounts[0], "value": expected_difference} - ) - weth_instance.functions.deposit().transact( - {"from": accounts[1], "value": expected_difference} - ) - acc1_weth_balance = erc20_wrapper.balance_of.call(accounts[0]) - acc2_weth_balance = erc20_wrapper.balance_of.call(accounts[1]) - - assert ( - acc1_weth_balance - acc1_original_weth_balance == expected_difference - ) - assert ( - acc2_weth_balance - acc2_original_weth_balance == expected_difference - ) - - -def test_erc20_wrapper__approve( - accounts, - erc20_proxy_address, - erc20_wrapper, # pylint: disable=redefined-outer-name -): - """Test approving one account to spend balance from another account.""" - erc20_wrapper.approve.send_transaction( - erc20_proxy_address, - MAX_ALLOWANCE, - tx_params=TxParams(from_=accounts[0]), - ) - erc20_wrapper.approve.send_transaction( - erc20_proxy_address, - MAX_ALLOWANCE, - tx_params=TxParams(from_=accounts[1]), - ) - - acc_1_weth_allowance = erc20_wrapper.allowance.call( - accounts[0], erc20_proxy_address - ) - acc_2_weth_allowance = erc20_wrapper.allowance.call( - accounts[1], erc20_proxy_address - ) - - assert acc_1_weth_allowance == MAX_ALLOWANCE - assert acc_2_weth_allowance == MAX_ALLOWANCE diff --git a/python-packages/contract_wrappers/test/test_exchange_wrapper.py b/python-packages/contract_wrappers/test/test_exchange_wrapper.py deleted file mode 100644 index c0b67e9600..0000000000 --- a/python-packages/contract_wrappers/test/test_exchange_wrapper.py +++ /dev/null @@ -1,279 +0,0 @@ -"""Test 0x Exchnage wrapper.""" - -import random - -import pytest -from eth_utils import remove_0x_prefix -from web3 import Web3 -from web3.gas_strategies.rpc import rpc_gas_price_strategy - -from zero_ex.contract_addresses import chain_to_addresses, ChainId -from zero_ex.contract_wrappers import TxParams -from zero_ex.contract_wrappers.exchange import Exchange -from zero_ex.contract_wrappers.exchange.types import Order -from zero_ex.json_schemas import assert_valid -from zero_ex.order_utils import ( - asset_data_utils, - generate_order_hash_hex, - sign_hash, -) - - -@pytest.fixture(scope="module") -def exchange_wrapper(ganache_provider): - """Get an Exchange wrapper instance.""" - return Exchange( - web3_or_provider=ganache_provider, - contract_address=chain_to_addresses(ChainId.GANACHE).exchange, - ) - - -def create_test_order( - maker_address, - maker_asset_amount, - maker_asset_data, - taker_asset_amount, - taker_asset_data, -): - """Create a test order.""" - order = Order( - makerAddress=maker_address, - takerAddress="0x0000000000000000000000000000000000000000", - feeRecipientAddress="0x0000000000000000000000000000000000000000", - senderAddress="0x0000000000000000000000000000000000000000", - makerAssetAmount=maker_asset_amount, - takerAssetAmount=taker_asset_amount, - makerFee=0, - takerFee=0, - expirationTimeSeconds=100000000000000, - salt=random.randint(1, 1000000000), - makerAssetData=maker_asset_data, - takerAssetData=taker_asset_data, - makerFeeAssetData=asset_data_utils.encode_erc20("0x" + "00" * 20), - takerFeeAssetData=asset_data_utils.encode_erc20("0x" + "00" * 20), - ) - return order - - -def assert_fill_log(fill_log, maker, taker, order, order_hash): - """assert that the fill log matches the order details""" - assert fill_log.makerAddress == maker - assert fill_log.takerAddress == taker - assert fill_log.feeRecipientAddress == order["feeRecipientAddress"] - assert fill_log.senderAddress == taker - assert fill_log.orderHash == bytes.fromhex(remove_0x_prefix(order_hash)) - assert fill_log.makerAssetFilledAmount == order["makerAssetAmount"] - assert fill_log.takerAssetFilledAmount == order["takerAssetAmount"] - assert fill_log.makerFeePaid == order["makerFee"] - assert fill_log.takerFeePaid == order["takerFee"] - assert fill_log.makerAssetData == order["makerAssetData"] - assert fill_log.takerAssetData == order["takerAssetData"] - - -def test_exchange_wrapper__fill_order( - accounts, - exchange_wrapper, # pylint: disable=redefined-outer-name - ganache_provider, - weth_asset_data, - zrx_asset_data, -): - """Test filling an order.""" - taker = accounts[0] - maker = accounts[1] - exchange_address = exchange_wrapper.contract_address - order = create_test_order(maker, 1, weth_asset_data, 1, zrx_asset_data) - order_hash = generate_order_hash_hex( - order=order, exchange_address=exchange_address, chain_id=1337 - ) - order_signature = sign_hash(ganache_provider, maker, order_hash) - - web3 = Web3(ganache_provider) - web3.eth.setGasPriceStrategy( # pylint: disable=no-member - rpc_gas_price_strategy - ) - - fill_results = exchange_wrapper.fill_order.call( - order=order, - taker_asset_fill_amount=order["takerAssetAmount"], - signature=order_signature, - tx_params=TxParams( - from_=taker, - value=web3.eth.generateGasPrice() # pylint: disable=no-member - * 150000, - ), - ) - assert fill_results["makerAssetFilledAmount"] == 1 - assert fill_results["takerAssetFilledAmount"] == 1 - assert fill_results["makerFeePaid"] == 0 - assert fill_results["takerFeePaid"] == 0 - assert ( - fill_results["protocolFeePaid"] - == web3.eth.generateGasPrice() * 150000 # pylint: disable=no-member - ) - - tx_hash = exchange_wrapper.fill_order.send_transaction( - order=order, - taker_asset_fill_amount=order["takerAssetAmount"], - signature=order_signature, - tx_params=TxParams( - from_=taker, - value=web3.eth.generateGasPrice() # pylint: disable=no-member - * 150000, - ), - ) - assert_valid(tx_hash.hex(), "/hexSchema") - - fill_event = exchange_wrapper.get_fill_event(tx_hash) - assert_fill_log(fill_event[0].args, maker, taker, order, order_hash) - - -def test_exchange_wrapper__fill_order__build_then_send( - accounts, - exchange_wrapper, # pylint: disable=redefined-outer-name - ganache_provider, - weth_asset_data, - zrx_asset_data, -): - """Test filling an order.""" - taker = accounts[0] - maker = accounts[1] - exchange_address = exchange_wrapper.contract_address - order = create_test_order(maker, 1, weth_asset_data, 1, zrx_asset_data) - order_hash = generate_order_hash_hex( - order=order, exchange_address=exchange_address, chain_id=1337 - ) - order_signature = sign_hash(ganache_provider, maker, order_hash) - - web3 = Web3(ganache_provider) - web3.eth.setGasPriceStrategy( # pylint: disable=no-member - rpc_gas_price_strategy - ) - - tx_hash = Web3(ganache_provider).eth.sendTransaction( - exchange_wrapper.fill_order.build_transaction( - order=order, - taker_asset_fill_amount=order["takerAssetAmount"], - signature=order_signature, - tx_params=TxParams( - from_=taker, - value=web3.eth.generateGasPrice() # pylint: disable=no-member - * 150000, - ), - ) - ) - - assert_valid(tx_hash.hex(), "/hexSchema") - - fill_event = exchange_wrapper.get_fill_event(tx_hash) - assert_fill_log(fill_event[0].args, maker, taker, order, order_hash) - - -def test_exchange_wrapper__fill_order__without_from_tx_param( - accounts, - exchange_wrapper, # pylint: disable=redefined-outer-name - ganache_provider, - weth_asset_data, - zrx_asset_data, -): - """Test filling an order.""" - maker = accounts[1] - exchange_address = exchange_wrapper.contract_address - order = create_test_order(maker, 1, weth_asset_data, 1, zrx_asset_data) - order_hash = generate_order_hash_hex( - order=order, exchange_address=exchange_address, chain_id=1337 - ) - order_signature = sign_hash(ganache_provider, maker, order_hash) - - web3 = Web3(ganache_provider) - web3.eth.setGasPriceStrategy( # pylint: disable=no-member - rpc_gas_price_strategy - ) - - exchange_wrapper._web3_eth.defaultAccount = ( # pylint: disable=protected-access - None - ) - exchange_wrapper._web3_eth.accounts.clear() # pylint: disable=protected-access - - built_tx = exchange_wrapper.fill_order.build_transaction( - order=order, - taker_asset_fill_amount=order["takerAssetAmount"], - signature=order_signature, - tx_params=TxParams( - value=web3.eth.generateGasPrice() # pylint: disable=no-member - * 150000, - ), - ) - assert ( - built_tx["data"][:824] - == "0x9b44d5560000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000003a00000000000000000000000006ecbe1db9ef729cbe972c83fb886247691fb6beb000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005af3107a40000000000000000000000000000000000000000000000000" - ) - - -# pylint: disable=too-many-locals -def test_exchange_wrapper__batch_fill_orders( - accounts, - exchange_wrapper, # pylint: disable=redefined-outer-name - ganache_provider, - weth_asset_data, -): - """Test filling a batch of orders.""" - taker = accounts[0] - maker = accounts[1] - exchange_address = exchange_wrapper.contract_address - orders = [] - order_1 = create_test_order(maker, 1, weth_asset_data, 1, weth_asset_data) - order_2 = create_test_order(maker, 1, weth_asset_data, 1, weth_asset_data) - orders.append(order_1) - orders.append(order_2) - order_hashes = [ - generate_order_hash_hex( - order=order, exchange_address=exchange_address, chain_id=1337 - ) - for order in orders - ] - order_signatures = [ - sign_hash(ganache_provider, maker, order_hash) - for order_hash in order_hashes - ] - taker_amounts = [order["takerAssetAmount"] for order in orders] - - web3 = Web3(ganache_provider) - web3.eth.setGasPriceStrategy( # pylint: disable=no-member - rpc_gas_price_strategy - ) - - tx_hash = exchange_wrapper.batch_fill_orders.send_transaction( - orders=orders, - taker_asset_fill_amounts=taker_amounts, - signatures=order_signatures, - tx_params=TxParams( - from_=taker, - value=2 - * web3.eth.generateGasPrice() # pylint: disable=no-member - * 150000, - ), - ) - assert_valid(tx_hash.hex(), "/hexSchema") - - fill_events = exchange_wrapper.get_fill_event(tx_hash) - for index, order in enumerate(orders): - assert_fill_log( - fill_events[index].args, maker, taker, order, order_hashes[index] - ) - - -def test_two_instantiations_with_web3_objects(web3_instance): - """Test that instantiating two Exchange objects doesn't raise. - - When instantiating an Exchange object with a web3 client (rather than a - provider) there was a bug encountered where web3.py was giving an error - when trying to install the rich-revert-handling middleware on the web3 - client, an error saying "can't install this same middleware instance - again." Test that that bug isn't occurring. - """ - exchange = Exchange( # pylint: disable=unused-variable - web3_instance, chain_to_addresses(ChainId.GANACHE).exchange - ) - exchange2 = Exchange( # pylint: disable=unused-variable - web3_instance, chain_to_addresses(ChainId.GANACHE).exchange - ) diff --git a/python-packages/contract_wrappers/tox.ini b/python-packages/contract_wrappers/tox.ini deleted file mode 100644 index c3e7029329..0000000000 --- a/python-packages/contract_wrappers/tox.ini +++ /dev/null @@ -1,26 +0,0 @@ -# tox (https://tox.readthedocs.io/) is a tool for running tests -# in multiple virtualenvs. This configuration file will run the -# test suite on all supported python versions. To use it, "pip install tox" -# and then run "tox" from this directory. - -[tox] -envlist = py37 - -[testenv] -commands = - pip install -e .[dev] - python setup.py test - -[testenv:run_tests_against_test_deployment] -commands = - # install dependencies from real PyPI - pip install 0x-contract-addresses 0x-contract-artifacts 0x-json-schemas 0x-order-utils 0x-web3 attrs eth_utils hypothesis>=3.31.2 mypy_extensions pytest - # install package-under-test from test PyPI - pip install --index-url https://test.pypi.org/legacy/ 0x-contract-wrappers - pytest test - -[testenv:run_tests_against_deployment] -setenv = PY_IGNORE_IMPORTMISMATCH = 1 -commands = - pip install 0x-contract-wrappers[dev] - pytest --doctest-modules src test diff --git a/python-packages/install b/python-packages/install deleted file mode 100755 index 73d88fec27..0000000000 --- a/python-packages/install +++ /dev/null @@ -1,13 +0,0 @@ -#!/usr/bin/env python - -"""Install all packages in non-editable mode (no -e on pip install).""" - -from os import path -import subprocess - -# install all packages -subprocess.check_call( - ( - path.join(".", "cmd_pkgs_in_dep_order.py") + " pip install .[dev]" - ).split() -) diff --git a/python-packages/install_editable b/python-packages/install_editable deleted file mode 100755 index ad7700f2bd..0000000000 --- a/python-packages/install_editable +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env python - -"""Script to install all packages in editable mode (pip install -e .).""" - -from os import path -import subprocess - -# Install all packages, WITHOUT dev dependencies first, because some packages -# have dev-only dependencies on other local pacakges, to support tests and -# examples, and if we don't do this then those dev-only cross-dependencies will -# trigger premature dependency satisfaction, via PyPI rather than the local -# filesystem, completely messing up our "install." -subprocess.check_call( - ( - path.join(".", "cmd_pkgs_in_dep_order.py") + " pip install -e ." - ).split() -) - -# Now that the dev-only cross-dependencies will be considered already -# satisfied, due to the previous installation of all the pacakges in the -# local filestystem, go ahead and install the (rest of the) dev dependencies. -subprocess.check_call( - ( - path.join(".", "cmd_pkgs_in_dep_order.py") + " pip install -e .[dev]" - ).split() -) diff --git a/python-packages/json_schemas/.discharge.json b/python-packages/json_schemas/.discharge.json deleted file mode 100644 index 66d95679fc..0000000000 --- a/python-packages/json_schemas/.discharge.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "domain": "0x-json-schemas-py", - "build_command": "python setup.py build_sphinx", - "upload_directory": "build/docs/html", - "index_key": "index.html", - "error_key": "index.html", - "trailing_slashes": true, - "cache": 3600, - "aws_profile": "default", - "aws_region": "us-east-1", - "cdn": false, - "dns_configured": true -} diff --git a/python-packages/json_schemas/.pylintrc b/python-packages/json_schemas/.pylintrc deleted file mode 100644 index 937bc6313b..0000000000 --- a/python-packages/json_schemas/.pylintrc +++ /dev/null @@ -1,3 +0,0 @@ -[MESSAGES CONTROL] -disable=C0330,line-too-long,fixme,too-few-public-methods,too-many-ancestors -# C0330 is "bad hanging indent". we use indents per `black`. diff --git a/python-packages/json_schemas/CHANGELOG.md b/python-packages/json_schemas/CHANGELOG.md deleted file mode 100644 index 11e3321994..0000000000 --- a/python-packages/json_schemas/CHANGELOG.md +++ /dev/null @@ -1,16 +0,0 @@ -# Changelog - -## 1.2.0 - 2019-12-03 - -- Removed dev dependency on package `0x-contract-wrappers` -- Migrated examples to using new version of `0x-contract-addresses`. - -## 1.1.0 - 2019-08-09 - -- Added `verifyingContractAddress` to `/zeroExTransactionSchema`. -- Expanded documentation. -- Permit mixed-case addresses. - -## 1.0.0 - 2019-01-09 - -- Initial release. diff --git a/python-packages/json_schemas/README.md b/python-packages/json_schemas/README.md deleted file mode 100644 index 29b18baead..0000000000 --- a/python-packages/json_schemas/README.md +++ /dev/null @@ -1,43 +0,0 @@ -## 0x-json-schemas - -0x JSON schemas for those developing on top of 0x protocol. - -Read the [documentation](http://0x-json-schemas-py.s3-website-us-east-1.amazonaws.com/) - -## Installing - -```bash -pip install 0x-json-schemas -``` - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install Code and Dependencies - -```bash -pip install -e .[dev] -``` - -### Test - -`./setup.py test`. - -### Clean - -`./setup.py clean --all` - -### Lint - -`./setup.py lint` - -### Build Documentation - -`./setup.py build_sphinx` - -### More - -See `./setup.py --help-commands` for more info. diff --git a/python-packages/json_schemas/setup.py b/python-packages/json_schemas/setup.py deleted file mode 100755 index 6c97f94e8d..0000000000 --- a/python-packages/json_schemas/setup.py +++ /dev/null @@ -1,221 +0,0 @@ -#!/usr/bin/env python - -"""setuptools module for json_schemas package.""" - -# pylint: disable=import-outside-toplevel -# we import things outside of top-level because 3rd party libs may not yet be -# installed when you invoke this script - -import distutils.command.build_py -from distutils.command.clean import clean -import subprocess # nosec -from shutil import copytree, rmtree -from os import environ, path -from sys import argv, exit # pylint: disable=redefined-builtin - -from setuptools import find_packages, setup -from setuptools.command.test import test as TestCommand - - -class PreInstallCommand(distutils.command.build_py.build_py): - """Custom setuptools command class for pulling in schemas.""" - - description = "Pull in the schemas that live in the TypeScript package." - - def run(self): - """Copy files from TS area to local src.""" - pkgdir = path.dirname(path.realpath(argv[0])) - rmtree( - path.join(pkgdir, "src", "zero_ex", "json_schemas", "schemas"), - ignore_errors=True, - ) - copytree( - path.join( - pkgdir, "..", "..", "packages", "json-schemas", "schemas" - ), - path.join(pkgdir, "src", "zero_ex", "json_schemas", "schemas"), - ) - - -class TestCommandExtension(TestCommand): - """Run pytest tests.""" - - def run_tests(self): - """Invoke pytest.""" - import pytest - - exit(pytest.main(["--doctest-modules", "-rapP"])) - # show short test summary at end ^ - - -class LintCommand(distutils.command.build_py.build_py): - """Custom setuptools command class for running linters.""" - - description = "Run linters" - - def run(self): - """Run linter shell commands.""" - lint_commands = [ - # formatter: - "black --line-length 79 --check --diff src test setup.py".split(), - # style guide checker (formerly pep8): - "pycodestyle src test setup.py".split(), - # docstring style checker: - "pydocstyle src test setup.py".split(), - # static type checker: - "mypy src test setup.py".split(), - # security issue checker: - "bandit -r src ./setup.py".split(), - # general linter: - "pylint src test setup.py".split(), - # pylint takes relatively long to run, so it runs last, to enable - # fast failures. - ] - - # tell mypy where to find interface stubs for 3rd party libs - environ["MYPYPATH"] = path.join( - path.dirname(path.realpath(argv[0])), "stubs" - ) - - for lint_command in lint_commands: - print( - "Running lint command `", " ".join(lint_command).strip(), "`" - ) - subprocess.check_call(lint_command) # nosec - - -class CleanCommandExtension(clean): - """Custom command to do custom cleanup.""" - - def run(self): - """Run the regular clean, followed by our custom commands.""" - super().run() - rmtree("build", ignore_errors=True) - rmtree("dist", ignore_errors=True) - rmtree(".mypy_cache", ignore_errors=True) - rmtree(".tox", ignore_errors=True) - rmtree(".pytest_cache", ignore_errors=True) - rmtree("src/0x_json_schemas.egg-info", ignore_errors=True) - - -class TestPublishCommand(distutils.command.build_py.build_py): - """Custom command to publish to test.pypi.org.""" - - description = ( - "Publish dist/* to test.pypi.org. Run sdist & bdist_wheel first." - ) - - def run(self): - """Run twine to upload to test.pypi.org.""" - subprocess.check_call( # nosec - ( - "twine upload --repository-url https://test.pypi.org/legacy/" - + " --verbose dist/*" - ).split() - ) - - -class PublishCommand(distutils.command.build_py.build_py): - """Custom command to publish to pypi.org.""" - - description = "Publish dist/* to pypi.org. Run sdist & bdist_wheel first." - - def run(self): - """Run twine to upload to pypi.org.""" - subprocess.check_call("twine upload dist/*".split()) # nosec - - -class PublishDocsCommand(distutils.command.build_py.build_py): - """Custom command to publish docs to S3.""" - - description = ( - "Publish docs to " - + "http://0x-json-schemas-py.s3-website-us-east-1.amazonaws.com/" - ) - - def run(self): - """Run npm package `discharge` to build & upload docs.""" - subprocess.check_call("discharge deploy".split()) # nosec - - -with open("README.md", "r") as file_handle: - README_MD = file_handle.read() - - -setup( - name="0x-json-schemas", - version="2.1.0", - description="JSON schemas for 0x applications", - long_description=README_MD, - long_description_content_type="text/markdown", - url=( - "https://github.com/0xProject/0x-monorepo/tree/development" - + "/python-packages/json_schemas" - ), - author="F. Eugene Aumson", - author_email="feuGeneA@users.noreply.github.com", - cmdclass={ - "pre_install": PreInstallCommand, - "clean": CleanCommandExtension, - "lint": LintCommand, - "test": TestCommandExtension, - "test_publish": TestPublishCommand, - "publish": PublishCommand, - "publish_docs": PublishDocsCommand, - }, - install_requires=["jsonschema", "mypy_extensions", "stringcase"], - extras_require={ - "dev": [ - "0x-contract-addresses", - "bandit", - "black", - "coverage", - "coveralls", - "eth_utils", - "mypy<=0.770", # see https://github.com/python/mypy/issues/8953 - "mypy_extensions", - "pycodestyle", - "pydocstyle", - "pylint", - "pytest", - "sphinx", - "tox", - "twine", - ] - }, - python_requires=">=3.6, <4", - package_data={"zero_ex.json_schemas": ["py.typed", "schemas/*"]}, - package_dir={"": "src"}, - license="Apache 2.0", - keywords=( - "ethereum cryptocurrency 0x decentralized blockchain dex exchange" - ), - namespace_packages=["zero_ex"], - packages=find_packages("src"), - classifiers=[ - "Development Status :: 2 - Pre-Alpha", - "Intended Audience :: Developers", - "Intended Audience :: Financial and Insurance Industry", - "License :: OSI Approved :: Apache Software License", - "Natural Language :: English", - "Operating System :: OS Independent", - "Programming Language :: Python", - "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3.6", - "Programming Language :: Python :: 3.7", - "Topic :: Internet :: WWW/HTTP", - "Topic :: Office/Business :: Financial", - "Topic :: Other/Nonlisted Topic", - "Topic :: Security :: Cryptography", - "Topic :: Software Development :: Libraries", - "Topic :: Utilities", - ], - zip_safe=False, # required per mypy - command_options={ - "build_sphinx": { - "source_dir": ("setup.py", "src"), - "build_dir": ("setup.py", "build/docs"), - "warning_is_error": ("setup.py", "true"), - } - }, -) diff --git a/python-packages/json_schemas/src/conf.py b/python-packages/json_schemas/src/conf.py deleted file mode 100644 index 1ae1493e36..0000000000 --- a/python-packages/json_schemas/src/conf.py +++ /dev/null @@ -1,54 +0,0 @@ -"""Configuration file for the Sphinx documentation builder.""" - -# Reference: http://www.sphinx-doc.org/en/master/config - -from typing import List -import pkg_resources - - -# pylint: disable=invalid-name -# because these variables are not named in upper case, as globals should be. - -project = "0x-json-schemas" -# pylint: disable=redefined-builtin -copyright = "2018, ZeroEx, Intl." -author = "F. Eugene Aumson" -version = pkg_resources.get_distribution("0x-json-schemas").version -release = "" # The full version, including alpha/beta/rc tags - -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.doctest", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.viewcode", -] - -templates_path = ["doc_templates"] - -source_suffix = ".rst" -# eg: source_suffix = [".rst", ".md"] - -master_doc = "index" # The master toctree document. - -language = None - -exclude_patterns: List[str] = [] - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = None - -html_theme = "alabaster" - -html_static_path = ["doc_static"] -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". - -# Output file base name for HTML help builder. -htmlhelp_basename = "json_schemaspydoc" - -# -- Extension configuration: - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = {"https://docs.python.org/": None} diff --git a/python-packages/json_schemas/src/doc_static/.gitkeep b/python-packages/json_schemas/src/doc_static/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/json_schemas/src/index.rst b/python-packages/json_schemas/src/index.rst deleted file mode 100644 index 3de809aa3c..0000000000 --- a/python-packages/json_schemas/src/index.rst +++ /dev/null @@ -1,18 +0,0 @@ -.. source for the sphinx-generated build/docs/web/index.html - -Python zero_ex.json_schemas -=========================== - -.. toctree:: - :maxdepth: 2 - :caption: Contents: - -.. automodule:: zero_ex.json_schemas - :members: - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` diff --git a/python-packages/json_schemas/src/zero_ex/__init__.py b/python-packages/json_schemas/src/zero_ex/__init__.py deleted file mode 100644 index 3fe1300cfb..0000000000 --- a/python-packages/json_schemas/src/zero_ex/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -"""0x Python API.""" -__import__("pkg_resources").declare_namespace(__name__) # type: ignore diff --git a/python-packages/json_schemas/src/zero_ex/json_schemas/__init__.py b/python-packages/json_schemas/src/zero_ex/json_schemas/__init__.py deleted file mode 100644 index 7e4f0e2058..0000000000 --- a/python-packages/json_schemas/src/zero_ex/json_schemas/__init__.py +++ /dev/null @@ -1,119 +0,0 @@ -"""0x JSON schemas and associated utilities. - -Setup ------ - -Install the package with pip:: - - pip install 0x-json-schemas - -""" - -from os import path -import json -from typing import Mapping - -from pkg_resources import resource_string -import jsonschema -from stringcase import snakecase - - -class _LocalRefResolver(jsonschema.RefResolver): - """Resolve package-local JSON schema id's.""" - - def __init__(self): - """Initialize a new instance.""" - jsonschema.RefResolver.__init__(self, "", "") - - @staticmethod - def resolve_from_url(url: str) -> str: - """Resolve the given URL. - - :param url: a string representing the URL of the JSON schema to fetch. - :returns: a string representing the deserialized JSON schema - :raises jsonschema.ValidationError: when the resource associated with - `url` does not exist. - """ - ref = url.replace("file://", "") - return json.loads( - resource_string( - "zero_ex.json_schemas", - f"schemas/{snakecase(ref.lstrip('/'))}.json", - ) - ) - - -# Instantiate the `_LocalRefResolver()` only once so that `assert_valid()` can -# perform multiple schema validations without reading from disk the schema -# every time. -_LOCAL_RESOLVER = _LocalRefResolver() - - -def assert_valid(data: Mapping, schema_id: str) -> None: - """Validate the given `data` against the specified `schema`. - - :param data: Python dictionary to be validated as a JSON object. - :param schema_id: id property of the JSON schema to validate against. Must - be one of those listed in `the 0x JSON schema files - `_. - - Raises an exception if validation fails. - - >>> from zero_ex.json_schemas import assert_valid - >>> from zero_ex.contract_addresses import chain_to_addresses, ChainId - >>> from eth_utils import remove_0x_prefix - >>> import random - >>> from datetime import datetime, timedelta - >>> assert_valid( - ... {'makerAddress': '0x5409ed021d9299bf6814279a6a1411a7e866a631', - ... 'takerAddress': '0x0000000000000000000000000000000000000000', - ... 'senderAddress': '0x0000000000000000000000000000000000000000', - ... 'exchangeAddress': '0x4f833a24e1f95d70f028921e27040ca56e09ab0b', - ... 'feeRecipientAddress': ( - ... '0x0000000000000000000000000000000000000000' - ... ), - ... 'makerAssetData': ( - ... chain_to_addresses(ChainId.MAINNET).zrx_token - ... ), - ... 'takerAssetData': ( - ... chain_to_addresses(ChainId.MAINNET).ether_token - ... ), - ... 'salt': random.randint(1, 100000000000000000), - ... 'makerFee': 0, - ... 'makerFeeAssetData': '0x' + '00'*20, - ... 'takerFee': 0, - ... 'takerFeeAssetData': '0x' + '00'*20, - ... 'makerAssetAmount': 1000000000000000000, - ... 'takerAssetAmount': 500000000000000000000, - ... 'expirationTimeSeconds': round( - ... (datetime.utcnow() + timedelta(days=1)).timestamp() - ... ), - ... 'chainId': 50 - ... }, - ... "/orderSchema" - ... ) - """ - _, schema = _LOCAL_RESOLVER.resolve(schema_id) - jsonschema.validate(data, schema, resolver=_LOCAL_RESOLVER) - - -def assert_valid_json(data: str, schema_id: str) -> None: - """Validate the given `data` against the specified `schema`. - - :param data: JSON string to be validated. - :param schema_id: id property of the JSON schema to validate against. Must - be one of those listed in `the 0x JSON schema files - `_. - - Raises an exception if validation fails. - - >>> assert_valid_json( - ... '''{ - ... "v": 27, - ... "r": "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - ... "s": "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" - ... }''', - ... '/ecSignatureSchema', - ... ) - """ # noqa: E501 (line too long) - assert_valid(json.loads(data), schema_id) diff --git a/python-packages/json_schemas/src/zero_ex/json_schemas/py.typed b/python-packages/json_schemas/src/zero_ex/json_schemas/py.typed deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/json_schemas/stubs/distutils/__init__.pyi b/python-packages/json_schemas/stubs/distutils/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/json_schemas/stubs/distutils/command/__init__.pyi b/python-packages/json_schemas/stubs/distutils/command/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/json_schemas/stubs/distutils/command/clean.pyi b/python-packages/json_schemas/stubs/distutils/command/clean.pyi deleted file mode 100644 index 46a42ddb13..0000000000 --- a/python-packages/json_schemas/stubs/distutils/command/clean.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from distutils.core import Command - -class clean(Command): - def initialize_options(self: clean) -> None: ... - def finalize_options(self: clean) -> None: ... - def run(self: clean) -> None: ... - ... diff --git a/python-packages/json_schemas/stubs/jsonschema/__init__.pyi b/python-packages/json_schemas/stubs/jsonschema/__init__.pyi deleted file mode 100644 index 442e2f65e5..0000000000 --- a/python-packages/json_schemas/stubs/jsonschema/__init__.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Any, Dict, Tuple - - -class RefResolver: - def resolve(self, url: str) -> Tuple[str, Dict]: - ... - - -class ValidationError(Exception): pass - -def validate(instance: Any, schema: Dict, cls=None, *args, **kwargs) -> None: pass diff --git a/python-packages/json_schemas/stubs/jsonschema/exceptions.pyi b/python-packages/json_schemas/stubs/jsonschema/exceptions.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/json_schemas/stubs/pytest/__init__.pyi b/python-packages/json_schemas/stubs/pytest/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/json_schemas/stubs/pytest/raises.pyi b/python-packages/json_schemas/stubs/pytest/raises.pyi deleted file mode 100644 index 2e3b29f3dc..0000000000 --- a/python-packages/json_schemas/stubs/pytest/raises.pyi +++ /dev/null @@ -1 +0,0 @@ -def raises(exception: Exception) -> ExceptionInfo: ... diff --git a/python-packages/json_schemas/stubs/setuptools/__init__.pyi b/python-packages/json_schemas/stubs/setuptools/__init__.pyi deleted file mode 100644 index 8ea8d32b7e..0000000000 --- a/python-packages/json_schemas/stubs/setuptools/__init__.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from distutils.dist import Distribution -from typing import Any, List - -def setup(**attrs: Any) -> Distribution: ... - -class Command: ... - -def find_packages(where: str) -> List[str]: ... diff --git a/python-packages/json_schemas/stubs/setuptools/command/__init__.pyi b/python-packages/json_schemas/stubs/setuptools/command/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/json_schemas/stubs/setuptools/command/test.pyi b/python-packages/json_schemas/stubs/setuptools/command/test.pyi deleted file mode 100644 index c5ec770ad3..0000000000 --- a/python-packages/json_schemas/stubs/setuptools/command/test.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from setuptools import Command - -class test(Command): ... diff --git a/python-packages/json_schemas/stubs/stringcase/__init__.pyi b/python-packages/json_schemas/stubs/stringcase/__init__.pyi deleted file mode 100644 index 56d784cf5b..0000000000 --- a/python-packages/json_schemas/stubs/stringcase/__init__.pyi +++ /dev/null @@ -1,2 +0,0 @@ -def snakecase(_: str): - ... diff --git a/python-packages/json_schemas/test/__init__.py b/python-packages/json_schemas/test/__init__.py deleted file mode 100644 index ce724e1805..0000000000 --- a/python-packages/json_schemas/test/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Tests of zero_ex.json_schemas.""" diff --git a/python-packages/json_schemas/test/test_json_schemas.py b/python-packages/json_schemas/test/test_json_schemas.py deleted file mode 100644 index bba37f333a..0000000000 --- a/python-packages/json_schemas/test/test_json_schemas.py +++ /dev/null @@ -1,44 +0,0 @@ -"""Tests of zero_ex.json_schemas""" - - -from zero_ex.json_schemas import _LOCAL_RESOLVER, assert_valid - - -NULL_ADDRESS = "0x0000000000000000000000000000000000000000" - -EMPTY_ORDER = { - "makerAddress": NULL_ADDRESS, - "takerAddress": NULL_ADDRESS, - "senderAddress": NULL_ADDRESS, - "feeRecipientAddress": NULL_ADDRESS, - "makerAssetData": NULL_ADDRESS, - "takerAssetData": NULL_ADDRESS, - "salt": "0", - "makerFee": "0", - "makerFeeAssetData": NULL_ADDRESS, - "takerFee": "0", - "takerFeeAssetData": NULL_ADDRESS, - "makerAssetAmount": "0", - "takerAssetAmount": "0", - "expirationTimeSeconds": "0", - "exchangeAddress": NULL_ADDRESS, - "chainId": 50, -} - - -def test_assert_valid_caches_resources(): - """Test that the JSON ref resolver in `assert_valid()` caches resources - - In order to test the cache we much access the private class of - `json_schemas` and reset the LRU cache on `_LocalRefResolver`. - For this to happen, we need to disable errror `W0212` - on _LOCAL_RESOLVER - """ - _LOCAL_RESOLVER._remote_cache.cache_clear() # pylint: disable=W0212 - - assert_valid(EMPTY_ORDER, "/orderSchema") - cache_info = ( - _LOCAL_RESOLVER._remote_cache.cache_info() # pylint: disable=W0212 - ) - assert cache_info.currsize == 4 - assert cache_info.hits > 0 diff --git a/python-packages/json_schemas/tox.ini b/python-packages/json_schemas/tox.ini deleted file mode 100644 index 87ec5e8473..0000000000 --- a/python-packages/json_schemas/tox.ini +++ /dev/null @@ -1,26 +0,0 @@ -# tox (https://tox.readthedocs.io/) is a tool for running tests -# in multiple virtualenvs. This configuration file will run the -# test suite on all supported python versions. To use it, "pip install tox" -# and then run "tox" from this directory. - -[tox] -envlist = py37 - -[testenv] -commands = - pip install -e .[dev] - python setup.py test - -[testenv:run_tests_against_test_deployment] -commands = - # install dependencies from real PyPI - pip install jsonschema mypy_extensions pytest - # install package-under-test from test PyPI - pip install --index-url https://test.pypi.org/legacy/ 0x-json-schemas - pytest test - -[testenv:run_tests_against_deployment] -setenv = PY_IGNORE_IMPORTMISMATCH = 1 -commands = - pip install 0x-json-schemas[dev] - pytest --doctest-modules src test diff --git a/python-packages/lint b/python-packages/lint deleted file mode 100755 index e9d12a296b..0000000000 --- a/python-packages/lint +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env bash - -./parallel ./setup.py lint diff --git a/python-packages/middlewares/.discharge.json b/python-packages/middlewares/.discharge.json deleted file mode 100644 index 352aa16499..0000000000 --- a/python-packages/middlewares/.discharge.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "domain": "0x-middlewares-py", - "build_command": "python setup.py build_sphinx", - "upload_directory": "build/docs/html", - "index_key": "index.html", - "error_key": "index.html", - "trailing_slashes": true, - "cache": 3600, - "aws_profile": "default", - "aws_region": "us-east-1", - "cdn": false, - "dns_configured": true -} diff --git a/python-packages/middlewares/.pylintrc b/python-packages/middlewares/.pylintrc deleted file mode 100644 index 937bc6313b..0000000000 --- a/python-packages/middlewares/.pylintrc +++ /dev/null @@ -1,3 +0,0 @@ -[MESSAGES CONTROL] -disable=C0330,line-too-long,fixme,too-few-public-methods,too-many-ancestors -# C0330 is "bad hanging indent". we use indents per `black`. diff --git a/python-packages/middlewares/CHANGELOG.md b/python-packages/middlewares/CHANGELOG.md deleted file mode 100644 index eaa6befdd3..0000000000 --- a/python-packages/middlewares/CHANGELOG.md +++ /dev/null @@ -1,5 +0,0 @@ -# Changelog - -## 1.0.0 - 2019-12-03 - -- Initial release. diff --git a/python-packages/middlewares/README.md b/python-packages/middlewares/README.md deleted file mode 100644 index a219fd1f5d..0000000000 --- a/python-packages/middlewares/README.md +++ /dev/null @@ -1,46 +0,0 @@ -## 0x-middlewares - -Web3 middlewares for 0x applications. - -Read the [documentation](http://0x-middlewares-py.s3-website-us-east-1.amazonaws.com/) - -## Installing - -```bash -pip install 0x-middlewares -``` - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install Code and Dependencies - -Ensure that you have installed Python >=3.6 and Docker. Then: - -```bash -pip install -e .[dev] -``` - -### Test - -Tests depend on running a local ethereum JSON-RPC server. For convenience, a docker container is provided that has ganache-cli. -A shortcut is provided to run that docker container: `./setup.py ganache`. With that running, the tests can be run with `./setup.py test`. - -### Clean - -`./setup.py clean --all` - -### Lint - -`./setup.py lint` - -### Build Documentation - -`./setup.py build_sphinx` - -### More - -See `./setup.py --help-commands` for more info. diff --git a/python-packages/middlewares/setup.py b/python-packages/middlewares/setup.py deleted file mode 100755 index ce4dd692cf..0000000000 --- a/python-packages/middlewares/setup.py +++ /dev/null @@ -1,222 +0,0 @@ -#!/usr/bin/env python - -"""setuptools module for middlewares package.""" - -# pylint: disable=import-outside-toplevel -# we import things outside of top-level because 3rd party libs may not yet be -# installed when you invoke this script - -import subprocess # nosec -from shutil import rmtree -from os import environ, path -from sys import argv, exit # pylint: disable=redefined-builtin - -from distutils.command.clean import clean -import distutils.command.build_py -from setuptools import find_packages, setup -from setuptools.command.test import test as TestCommand - - -class TestCommandExtension(TestCommand): - """Run pytest tests.""" - - def run_tests(self): - """Invoke pytest.""" - import pytest - - exit(pytest.main(["--doctest-modules", "-rapP"])) - # show short test summary at end ^ - - -class LintCommand(distutils.command.build_py.build_py): - """Custom setuptools command class for running linters.""" - - description = "Run linters" - - def run(self): - """Run linter shell commands.""" - lint_commands = [ - # formatter: - "black --line-length 79 --check --diff src test setup.py".split(), - # style guide checker (formerly pep8): - "pycodestyle src test setup.py".split(), - # docstring style checker: - "pydocstyle src test setup.py".split(), - # static type checker: - "mypy src test setup.py".split(), - # security issue checker: - "bandit -r src ./setup.py".split(), - # general linter: - "pylint src test setup.py".split(), - # pylint takes relatively long to run, so it runs last, to enable - # fast failures. - ] - - # tell mypy where to find interface stubs for 3rd party libs - environ["MYPYPATH"] = path.join( - path.dirname(path.realpath(argv[0])), "stubs" - ) - - for lint_command in lint_commands: - print( - "Running lint command `", " ".join(lint_command).strip(), "`" - ) - subprocess.check_call(lint_command) # nosec - - -class CleanCommandExtension(clean): - """Custom command to do custom cleanup.""" - - def run(self): - """Run the regular clean, followed by our custom commands.""" - super().run() - rmtree("build", ignore_errors=True) - rmtree("dist", ignore_errors=True) - rmtree(".mypy_cache", ignore_errors=True) - rmtree(".tox", ignore_errors=True) - rmtree(".pytest_cache", ignore_errors=True) - rmtree("src/0x_middlewares.egg-info", ignore_errors=True) - - -class TestPublishCommand(distutils.command.build_py.build_py): - """Custom command to publish to test.pypi.org.""" - - description = ( - "Publish dist/* to test.pypi.org. Run sdist & bdist_wheel first." - ) - - def run(self): - """Run twine to upload to test.pypi.org.""" - subprocess.check_call( # nosec - ( - "twine upload --repository-url https://test.pypi.org/legacy/" - + " --verbose dist/*" - ).split() - ) - - -class PublishCommand(distutils.command.build_py.build_py): - """Custom command to publish to pypi.org.""" - - description = "Publish dist/* to pypi.org. Run sdist & bdist_wheel first." - - def run(self): - """Run twine to upload to pypi.org.""" - subprocess.check_call("twine upload dist/*".split()) # nosec - - -class PublishDocsCommand(distutils.command.build_py.build_py): - """Custom command to publish docs to S3.""" - - description = ( - "Publish docs to " - + "http://0x-middlewares-py.s3-website-us-east-1.amazonaws.com/" - ) - - def run(self): - """Run npm package `discharge` to build & upload docs.""" - subprocess.check_call("discharge deploy".split()) # nosec - - -class GanacheCommand(distutils.command.build_py.build_py): - """Custom command to publish to pypi.org.""" - - description = "Run ganache daemon to support tests." - - def run(self): - """Run ganache.""" - cmd_line = ( - "docker run -d -p 8545:8545 0xorg/ganache-cli:2.2.2" - ).split() - subprocess.call(cmd_line) # nosec - - -with open("README.md", "r") as file_handle: - README_MD = file_handle.read() - - -setup( - name="0x-middlewares", - version="1.0.0", - description="Web3 middlewares for 0x applications", - long_description=README_MD, - long_description_content_type="text/markdown", - url=( - "https://github.com/0xproject/0x-monorepo/tree/development" - "/python-packages/middlewares" - ), - author="Michael Huang", - author_email="michaelhly@users.noreply.github.com", - cmdclass={ - "clean": CleanCommandExtension, - "lint": LintCommand, - "test": TestCommandExtension, - "test_publish": TestPublishCommand, - "publish": PublishCommand, - "publish_docs": PublishDocsCommand, - "ganache": GanacheCommand, - }, - install_requires=[ - "eth-account", - "eth-keys", - "hexbytes", - "mypy_extensions", - ], - extras_require={ - "dev": [ - "0x-contract-addresses", - "0x-contract-wrappers", - "0x-order-utils", - "web3", - "bandit", - "black", - "coverage", - "coveralls", - "eth_utils", - "mypy<=0.770", # see https://github.com/python/mypy/issues/8953 - "mypy_extensions", - "pycodestyle", - "pydocstyle", - "pylint", - "pytest", - "sphinx", - "tox", - "twine", - ] - }, - python_requires=">=3.6, <4", - package_data={"zero_ex.middlewares": ["py.typed"]}, - package_dir={"": "src"}, - license="Apache 2.0", - keywords=( - "ethereum cryptocurrency 0x decentralized blockchain dex exchange" - ), - namespace_packages=["zero_ex"], - packages=find_packages("src"), - classifiers=[ - "Development Status :: 2 - Pre-Alpha", - "Intended Audience :: Developers", - "Intended Audience :: Financial and Insurance Industry", - "License :: OSI Approved :: Apache Software License", - "Natural Language :: English", - "Operating System :: OS Independent", - "Programming Language :: Python", - "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3.6", - "Programming Language :: Python :: 3.7", - "Topic :: Internet :: WWW/HTTP", - "Topic :: Office/Business :: Financial", - "Topic :: Other/Nonlisted Topic", - "Topic :: Security :: Cryptography", - "Topic :: Software Development :: Libraries", - "Topic :: Utilities", - ], - zip_safe=False, # required per mypy - command_options={ - "build_sphinx": { - "source_dir": ("setup.py", "src"), - "build_dir": ("setup.py", "build/docs"), - "warning_is_error": ("setup.py", "true"), - } - }, -) diff --git a/python-packages/middlewares/src/conf.py b/python-packages/middlewares/src/conf.py deleted file mode 100644 index 880a6afbc8..0000000000 --- a/python-packages/middlewares/src/conf.py +++ /dev/null @@ -1,54 +0,0 @@ -"""Configuration file for the Sphinx documentation builder.""" - -# Reference: http://www.sphinx-doc.org/en/master/config - -from typing import List -import pkg_resources - - -# pylint: disable=invalid-name -# because these variables are not named in upper case, as globals should be. - -project = "0x-middlewares" -# pylint: disable=redefined-builtin -copyright = "2019, ZeroEx, Intl." -author = "Michael Hwang" -version = pkg_resources.get_distribution("0x-middlewares").version -release = "" # The full version, including alpha/beta/rc tags - -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.doctest", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.viewcode", -] - -templates_path = ["doc_templates"] - -source_suffix = ".rst" -# eg: source_suffix = [".rst", ".md"] - -master_doc = "index" # The master toctree document. - -language = None - -exclude_patterns: List[str] = [] - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = None - -html_theme = "alabaster" - -html_static_path = ["doc_static"] -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". - -# Output file base name for HTML help builder. -htmlhelp_basename = "middlewarespydoc" - -# -- Extension configuration: - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = {"https://docs.python.org/": None} diff --git a/python-packages/middlewares/src/doc_static/.gitkeep b/python-packages/middlewares/src/doc_static/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/middlewares/src/doc_templates/.gitkeep b/python-packages/middlewares/src/doc_templates/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/middlewares/src/index.rst b/python-packages/middlewares/src/index.rst deleted file mode 100644 index 9ef2efeccd..0000000000 --- a/python-packages/middlewares/src/index.rst +++ /dev/null @@ -1,25 +0,0 @@ -.. source for the sphinx-generated build/docs/web/index.html - -Python zero_ex.middlewares -========================== - -.. toctree:: - :maxdepth: 2 - :caption: Contents: - -.. automodule:: zero_ex.middlewares - :members: - -zero_ex.middlewares.local_message_signer ----------------------------------------- - -.. automodule:: zero_ex.middlewares.local_message_signer - :members: - - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` diff --git a/python-packages/middlewares/src/zero_ex/__init__.py b/python-packages/middlewares/src/zero_ex/__init__.py deleted file mode 100644 index 3fe1300cfb..0000000000 --- a/python-packages/middlewares/src/zero_ex/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -"""0x Python API.""" -__import__("pkg_resources").declare_namespace(__name__) # type: ignore diff --git a/python-packages/middlewares/src/zero_ex/middlewares/__init__.py b/python-packages/middlewares/src/zero_ex/middlewares/__init__.py deleted file mode 100644 index 30b103dc78..0000000000 --- a/python-packages/middlewares/src/zero_ex/middlewares/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -"""Web3 middlewares for 0x applications. - -Setup ------ - -Install the package with pip:: - - pip install 0x-middlewares - -""" diff --git a/python-packages/middlewares/src/zero_ex/middlewares/local_message_signer.py b/python-packages/middlewares/src/zero_ex/middlewares/local_message_signer.py deleted file mode 100644 index 2ebb94b73a..0000000000 --- a/python-packages/middlewares/src/zero_ex/middlewares/local_message_signer.py +++ /dev/null @@ -1,107 +0,0 @@ -"""Middleware that captures all 'eth_sign' requests to the JSON-RPC-Server. - -An adaptation of the signing middleware from `web3.py -`_. -This middleware intercepts all 'eth_sign' requests to -an ethereum JSON RPC-Server and signs messages with a local private key. -""" - -from functools import singledispatch -from typing import Dict, List, Set, Tuple, Union -from eth_account import Account, messages -from eth_account.signers.local import LocalAccount -from eth_keys.datatypes import PrivateKey -from hexbytes import HexBytes - - -@singledispatch -def _to_account(private_key_or_account): - """Get a `LocalAccount` instance from a private_key or a `LocalAccount`. - - Note that this function is overloaded based on the type on input. This - implementation is the base case where none of the supported types are - matched and we throw an exception. - """ - raise TypeError( - "key must be one of the types:" - "eth_keys.datatype.PrivateKey, " - "eth_account.local.LocalAccount, " - "or raw private key as a hex string or byte string. " - "Was of type {0}".format(type(private_key_or_account)) - ) - - -def _private_key_to_account(private_key): - """Get the account associated with the private key.""" - if isinstance(private_key, PrivateKey): - private_key = private_key.to_hex() - else: - private_key = HexBytes(private_key).hex() - return Account().privateKeyToAccount(private_key) - - -_to_account.register(LocalAccount, lambda x: x) -_to_account.register(PrivateKey, _private_key_to_account) -_to_account.register(str, _private_key_to_account) -_to_account.register(bytes, _private_key_to_account) - - -def construct_local_message_signer( - private_key_or_account: Union[ - Union[LocalAccount, PrivateKey, str], - List[Union[LocalAccount, PrivateKey, str]], - Tuple[Union[LocalAccount, PrivateKey, str]], - Set[Union[LocalAccount, PrivateKey, str]], - ] -): - """Construct a local messager signer middleware. - - :param private_key_or_account: a single private key or a tuple, - list, or set of private keys. Keys can be any of the following - formats: - - - An `eth_account.LocalAccount`:code: object - - An `eth_keys.PrivateKey`:code: object - - A raw private key as a hex `string`:code: or as `bytes`:code: - :returns: callable local_message_signer_middleware - - >>> private_key=( - ... "f2f48ee19680706196e2e339e5da3491186e0c4c5030670656b0e0164837257d" - ... ) - >>> from web3 import Web3, HTTPProvider - >>> Web3( - ... HTTPProvider("https://mainnet.infura.io/v3/API_KEY") - ... ).middleware_onion.add( - ... construct_local_message_signer(private_key) - ... ) - - """ - if not isinstance(private_key_or_account, (list, tuple, set)): - private_key_or_account = [private_key_or_account] - accounts = [_to_account(pkoa) for pkoa in private_key_or_account] - address_to_accounts: Dict[str, LocalAccount] = { - account.address: account for account in accounts - } - - def local_message_signer_middleware( - make_request, web3 - ): # pylint: disable=unused-argument - def middleware(method, params): - if method != "eth_sign": - return make_request(method, params) - account_address, message = params[:2] - account = address_to_accounts[account_address] - # We will assume any string which looks like a hex is expected - # to be converted to hex. Non-hexable strings are forcibly - # converted by encoding them to utf-8 - try: - message = HexBytes(message) - except Exception: # pylint: disable=broad-except - message = HexBytes(message.encode("utf-8")) - msg_hash_hexbytes = messages.defunct_hash_message(message) - ec_signature = account.signHash(msg_hash_hexbytes) - return {"result": ec_signature.signature} - - return middleware - - return local_message_signer_middleware diff --git a/python-packages/middlewares/src/zero_ex/middlewares/py.typed b/python-packages/middlewares/src/zero_ex/middlewares/py.typed deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/middlewares/stubs/distutils/__init__.pyi b/python-packages/middlewares/stubs/distutils/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/middlewares/stubs/distutils/command/__init__.pyi b/python-packages/middlewares/stubs/distutils/command/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/middlewares/stubs/distutils/command/clean.pyi b/python-packages/middlewares/stubs/distutils/command/clean.pyi deleted file mode 100644 index 46a42ddb13..0000000000 --- a/python-packages/middlewares/stubs/distutils/command/clean.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from distutils.core import Command - -class clean(Command): - def initialize_options(self: clean) -> None: ... - def finalize_options(self: clean) -> None: ... - def run(self: clean) -> None: ... - ... diff --git a/python-packages/middlewares/stubs/eth_account/__init__.pyi b/python-packages/middlewares/stubs/eth_account/__init__.pyi deleted file mode 100644 index 5caed9e96f..0000000000 --- a/python-packages/middlewares/stubs/eth_account/__init__.pyi +++ /dev/null @@ -1 +0,0 @@ -class Account: ... diff --git a/python-packages/middlewares/stubs/eth_account/messages.pyi b/python-packages/middlewares/stubs/eth_account/messages.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/middlewares/stubs/eth_account/signers/__init__.pyi b/python-packages/middlewares/stubs/eth_account/signers/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/middlewares/stubs/eth_account/signers/local.pyi b/python-packages/middlewares/stubs/eth_account/signers/local.pyi deleted file mode 100644 index 72b351fe5f..0000000000 --- a/python-packages/middlewares/stubs/eth_account/signers/local.pyi +++ /dev/null @@ -1 +0,0 @@ -class LocalAccount: ... diff --git a/python-packages/middlewares/stubs/eth_keys/__init__.pyi b/python-packages/middlewares/stubs/eth_keys/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/middlewares/stubs/eth_keys/datatypes.pyi b/python-packages/middlewares/stubs/eth_keys/datatypes.pyi deleted file mode 100644 index 8d2a8dd32c..0000000000 --- a/python-packages/middlewares/stubs/eth_keys/datatypes.pyi +++ /dev/null @@ -1 +0,0 @@ -class PrivateKey: ... diff --git a/python-packages/middlewares/stubs/eth_utils/__init__.pyi b/python-packages/middlewares/stubs/eth_utils/__init__.pyi deleted file mode 100644 index 3343950068..0000000000 --- a/python-packages/middlewares/stubs/eth_utils/__init__.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from typing import Union - -def to_checksum_address(value: Union[str, bytes]) -> str: ... diff --git a/python-packages/middlewares/stubs/hexbytes/HexBytes.pyi b/python-packages/middlewares/stubs/hexbytes/HexBytes.pyi deleted file mode 100644 index bc88efe52a..0000000000 --- a/python-packages/middlewares/stubs/hexbytes/HexBytes.pyi +++ /dev/null @@ -1 +0,0 @@ -class HexBytes: ... diff --git a/python-packages/middlewares/stubs/hexbytes/__init__.pyi b/python-packages/middlewares/stubs/hexbytes/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/middlewares/stubs/pytest/__init__.pyi b/python-packages/middlewares/stubs/pytest/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/middlewares/stubs/pytest/raises.pyi b/python-packages/middlewares/stubs/pytest/raises.pyi deleted file mode 100644 index 2e3b29f3dc..0000000000 --- a/python-packages/middlewares/stubs/pytest/raises.pyi +++ /dev/null @@ -1 +0,0 @@ -def raises(exception: Exception) -> ExceptionInfo: ... diff --git a/python-packages/middlewares/stubs/setuptools/__init__.pyi b/python-packages/middlewares/stubs/setuptools/__init__.pyi deleted file mode 100644 index 8ea8d32b7e..0000000000 --- a/python-packages/middlewares/stubs/setuptools/__init__.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from distutils.dist import Distribution -from typing import Any, List - -def setup(**attrs: Any) -> Distribution: ... - -class Command: ... - -def find_packages(where: str) -> List[str]: ... diff --git a/python-packages/middlewares/stubs/setuptools/command/__init__.pyi b/python-packages/middlewares/stubs/setuptools/command/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/middlewares/stubs/setuptools/command/test.pyi b/python-packages/middlewares/stubs/setuptools/command/test.pyi deleted file mode 100644 index c5ec770ad3..0000000000 --- a/python-packages/middlewares/stubs/setuptools/command/test.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from setuptools import Command - -class test(Command): ... diff --git a/python-packages/middlewares/stubs/web3/__init__.pyi b/python-packages/middlewares/stubs/web3/__init__.pyi deleted file mode 100644 index e18564de84..0000000000 --- a/python-packages/middlewares/stubs/web3/__init__.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from typing import Dict, Optional, Union - -from web3.utils import datatypes -from web3.providers.base import BaseProvider - -class Web3: - def __init__(self, provider: BaseProvider) -> None: ... - -class HTTPProvider(BaseProvider): - ... diff --git a/python-packages/middlewares/stubs/web3/exceptions.pyi b/python-packages/middlewares/stubs/web3/exceptions.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/middlewares/stubs/web3/providers/__init__.pyi b/python-packages/middlewares/stubs/web3/providers/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/middlewares/stubs/web3/providers/base.pyi b/python-packages/middlewares/stubs/web3/providers/base.pyi deleted file mode 100644 index 7e6eaf3cbd..0000000000 --- a/python-packages/middlewares/stubs/web3/providers/base.pyi +++ /dev/null @@ -1 +0,0 @@ -class BaseProvider: ... diff --git a/python-packages/middlewares/stubs/web3/utils/__init__.pyi b/python-packages/middlewares/stubs/web3/utils/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/middlewares/stubs/web3/utils/datatypes.pyi b/python-packages/middlewares/stubs/web3/utils/datatypes.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/middlewares/test/__init__.py b/python-packages/middlewares/test/__init__.py deleted file mode 100644 index 88975131fe..0000000000 --- a/python-packages/middlewares/test/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Tests of zero_x.middlewares.""" diff --git a/python-packages/middlewares/test/test_local_message_signer.py b/python-packages/middlewares/test/test_local_message_signer.py deleted file mode 100644 index 469bf38e31..0000000000 --- a/python-packages/middlewares/test/test_local_message_signer.py +++ /dev/null @@ -1,52 +0,0 @@ -"""Tests of 0x.middlewares.local_message_signer.""" - -from eth_utils import to_checksum_address -from web3 import Web3, HTTPProvider - -from zero_ex.contract_addresses import chain_to_addresses, ChainId -from zero_ex.middlewares.local_message_signer import ( - construct_local_message_signer, -) -from zero_ex.order_utils import generate_order_hash_hex, sign_hash - - -def test_local_message_signer__sign_order(): - """Test signing order with the local_message_signer middleware""" - expected_signature = ( - "0x1c8bdfbb3ce3ed0f38c5a358a7f49ad5f21ea9857224c2fe98c458f2fa25551d4" - "d6db0157d9dfe9f9fadb8dedabb7786352843357f4ec8d0fbcbeeb619b1091f5803" - ) - address = "0x5409ED021D9299bf6814279A6A1411A7e866A631" - exchange = chain_to_addresses(ChainId.GANACHE).exchange - private_key = ( - "f2f48ee19680706196e2e339e5da3491186e0c4c5030670656b0e0164837257d" - ) - ganache = HTTPProvider("http://127.0.0.1:8545") - web3_instance = Web3(ganache) - web3_instance.middleware_onion.add( - construct_local_message_signer(private_key) - ) - order = { - "makerAddress": "0x0000000000000000000000000000000000000000", - "takerAddress": "0x0000000000000000000000000000000000000000", - "senderAddress": "0x0000000000000000000000000000000000000000", - "feeRecipientAddress": "0x0000000000000000000000000000000000000000", - "makerAssetData": (b"\x00") * 20, - "makerFeeAssetData": (b"\x00") * 20, - "takerAssetData": (b"\x00") * 20, - "takerFeeAssetData": (b"\x00") * 20, - "salt": 0, - "makerFee": 0, - "takerFee": 0, - "makerAssetAmount": 0, - "takerAssetAmount": 0, - "expirationTimeSeconds": 0, - } - assert ( - sign_hash( - web3_instance, - to_checksum_address(address), - generate_order_hash_hex(order, exchange, chain_id=1337), - ) - == expected_signature - ) diff --git a/python-packages/middlewares/tox.ini b/python-packages/middlewares/tox.ini deleted file mode 100644 index 41fafb026a..0000000000 --- a/python-packages/middlewares/tox.ini +++ /dev/null @@ -1,26 +0,0 @@ -# tox (https://tox.readthedocs.io/) is a tool for running tests -# in multiple virtualenvs. This configuration file will run the -# test suite on all supported python versions. To use it, "pip install tox" -# and then run "tox" from this directory. - -[tox] -envlist = py37 - -[testenv] -commands = - pip install -e .[dev] - python setup.py test - -[testenv:run_tests_against_test_deployment] -commands = - # install dependencies from real PyPI - pip install eth-account eth-keys hexbytes hypothesis>=3.31.2 mypy_extensions - # install package-under-test from test PyPI - pip install --index-url https://test.pypi.org/legacy/ 0x-middlewares - pytest test - -[testenv:run_tests_against_deployment] -setenv = PY_IGNORE_IMPORTMISMATCH = 1 -commands = - pip install 0x-middlewares[dev] - pytest --doctest-modules test diff --git a/python-packages/order_utils/.discharge.json b/python-packages/order_utils/.discharge.json deleted file mode 100644 index 2b14aa0239..0000000000 --- a/python-packages/order_utils/.discharge.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "domain": "0x-order-utils-py", - "build_command": "python setup.py build_sphinx", - "upload_directory": "build/docs/html", - "index_key": "index.html", - "error_key": "index.html", - "trailing_slashes": true, - "cache": 3600, - "aws_profile": "default", - "aws_region": "us-east-1", - "cdn": false, - "dns_configured": true -} diff --git a/python-packages/order_utils/.pylintrc b/python-packages/order_utils/.pylintrc deleted file mode 100644 index 937bc6313b..0000000000 --- a/python-packages/order_utils/.pylintrc +++ /dev/null @@ -1,3 +0,0 @@ -[MESSAGES CONTROL] -disable=C0330,line-too-long,fixme,too-few-public-methods,too-many-ancestors -# C0330 is "bad hanging indent". we use indents per `black`. diff --git a/python-packages/order_utils/CHANGELOG.md b/python-packages/order_utils/CHANGELOG.md deleted file mode 100644 index 53faea41e4..0000000000 --- a/python-packages/order_utils/CHANGELOG.md +++ /dev/null @@ -1,27 +0,0 @@ -# Changelog - -## 4.0.0 - 2019-12-03 - -- Upgraded to protocol version 3. -- `is_valid_signature()` now returns just a boolean. (Formerly, it returned a tuple consisting of the boolean and a reason string.) -- Allow `sign_hash()` to be called with EITHER a Web3.py `BaseProvider` OR an already-instantiated `Web3` client object. -- Migrated to new version of `0x-contract-addresses`. - -## 3.0.1 - 2019-08-09 - -- Fixed dependencies: changed `deprecated` from being an extras_require["dev"] dependency to being an install_requires dependency, since it's required not just for doc generation but also just to import the package. - -## 3.0.0 - 2019-08-08 - -- Major breaking changes: removal of definitions for Order, OrderInfo, order_to_jsdict, jsdict_to_order, all of which have been moved to contract_wrappers.exchange.types; removal of signature validation; migration from v4 to v5 of Web3.py - -## 2.0.0 - 2019-04-30 - -- Changed `ERC20AssetData` and `ERC721AssetData` to inherit from `NamedTuple` rather than `TypedDict`. -- Deprecated methods `encode_erc20_asset_data()` and `encode_erc721_asset_data()`, in favor of new methods `encode_erc20()` and `encode_erc721()`. The old methods return a string, which is less than convenient for building orders using the provided `Order` type, which expects asset data to be `bytes`. The new methods return `bytes`. -- Expanded documentation. -- Stopped using deprecated web3.py interface `contract.call()` in favor of `contract.functions.X.call()`. This provides compatibility with the upcoming 5.x release of web3.py, and it also eliminates some runtime warning messages. - -## 1.1.1 - 2019-02-26 - -- Replaced dependency on web3 with dependency on 0x-web3, to ease coexistence of those two packages. diff --git a/python-packages/order_utils/LICENSE b/python-packages/order_utils/LICENSE deleted file mode 100644 index 9096fefaaa..0000000000 --- a/python-packages/order_utils/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright 2017 ZeroEx Inc. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. \ No newline at end of file diff --git a/python-packages/order_utils/README.md b/python-packages/order_utils/README.md deleted file mode 100644 index 2181c7a119..0000000000 --- a/python-packages/order_utils/README.md +++ /dev/null @@ -1,45 +0,0 @@ -## 0x-order-utils - -0x order-related utilities for those developing on top of 0x protocol. - -Read the [documentation](http://0x-order-utils-py.s3-website-us-east-1.amazonaws.com/) - -## Installing - -```bash -pip install 0x-order-utils -``` - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install Code and Dependencies - -Ensure that you have installed Python >=3.6 and Docker. Then: - -```bash -pip install -e .[dev] -``` - -### Test - -Tests depend on a running ganache instance with the 0x contracts deployed in it. For convenience, a docker container is provided that has ganache-cli and a snapshot containing the necessary contracts. A shortcut is provided to run that docker container: `./setup.py ganache`. With that running, the tests can be run with `./setup.py test`. - -### Clean - -`./setup.py clean --all` - -### Lint - -`./setup.py lint` - -### Build Documentation - -`./setup.py build_sphinx` - -### More - -See `./setup.py --help-commands` for more info. diff --git a/python-packages/order_utils/setup.py b/python-packages/order_utils/setup.py deleted file mode 100755 index 82ff20e10f..0000000000 --- a/python-packages/order_utils/setup.py +++ /dev/null @@ -1,242 +0,0 @@ -#!/usr/bin/env python - -"""setuptools module for order_utils package.""" - -# pylint: disable=import-outside-toplevel -# we import things outside of top-level because 3rd party libs may not yet be -# installed when you invoke this script - -import subprocess # nosec -from shutil import rmtree -from os import environ, path -from pathlib import Path -from sys import argv, exit # pylint: disable=redefined-builtin - -from distutils.command.clean import clean -import distutils.command.build_py -from setuptools import find_packages, setup -from setuptools.command.test import test as TestCommand - - -class TestCommandExtension(TestCommand): - """Run pytest tests.""" - - def run_tests(self): - """Invoke pytest.""" - import pytest - - exit(pytest.main(["--doctest-modules", "-rapP"])) - # show short test summary at end ^ - - -class LintCommand(distutils.command.build_py.build_py): - """Custom setuptools command class for running linters.""" - - description = "Run linters" - - def run(self): - """Run linter shell commands.""" - lint_commands = [ - # formatter: - "black --line-length 79 --check --diff src test setup.py".split(), - # style guide checker (formerly pep8): - "pycodestyle src test setup.py".split(), - # docstring style checker: - "pydocstyle src test setup.py".split(), - # static type checker: - "mypy src test setup.py".split(), - # security issue checker: - "bandit -r src ./setup.py".split(), - # general linter: - "pylint src test setup.py".split(), - # pylint takes relatively long to run, so it runs last, to enable - # fast failures. - ] - - # tell mypy where to find interface stubs for 3rd party libs - environ["MYPYPATH"] = path.join( - path.dirname(path.realpath(argv[0])), "stubs" - ) - - # HACK(gene): until eth_abi releases - # https://github.com/ethereum/eth-abi/pull/107 , we need to simply - # create an empty file `py.typed` in the eth_abi package directory. - import eth_abi - - eth_abi_dir = path.dirname(path.realpath(eth_abi.__file__)) - Path(path.join(eth_abi_dir, "py.typed")).touch() - - # HACK(gene): until eth_utils fixes - # https://github.com/ethereum/eth-utils/issues/140 , we need to simply - # create an empty file `py.typed` in the eth_abi package directory. - import eth_utils - - eth_utils_dir = path.dirname(path.realpath(eth_utils.__file__)) - Path(path.join(eth_utils_dir, "py.typed")).touch() - - for lint_command in lint_commands: - print( - "Running lint command `", " ".join(lint_command).strip(), "`" - ) - subprocess.check_call(lint_command) # nosec - - -class CleanCommandExtension(clean): - """Custom command to do custom cleanup.""" - - def run(self): - """Run the regular clean, followed by our custom commands.""" - super().run() - rmtree("build", ignore_errors=True) - rmtree("dist", ignore_errors=True) - rmtree(".coverage", ignore_errors=True) - rmtree(".eggs", ignore_errors=True) - rmtree(".mypy_cache", ignore_errors=True) - rmtree(".tox", ignore_errors=True) - rmtree(".pytest_cache", ignore_errors=True) - rmtree("src/0x_order_utils.egg-info", ignore_errors=True) - - -class TestPublishCommand(distutils.command.build_py.build_py): - """Custom command to publish to test.pypi.org.""" - - description = ( - "Publish dist/* to test.pypi.org. Run sdist & bdist_wheel first." - ) - - def run(self): - """Run twine to upload to test.pypi.org.""" - subprocess.check_call( # nosec - ( - "twine upload --repository-url https://test.pypi.org/legacy/" - + " --verbose dist/*" - ).split() - ) - - -class PublishCommand(distutils.command.build_py.build_py): - """Custom command to publish to pypi.org.""" - - description = "Publish dist/* to pypi.org. Run sdist & bdist_wheel first." - - def run(self): - """Run twine to upload to pypi.org.""" - subprocess.check_call("twine upload dist/*".split()) # nosec - - -class PublishDocsCommand(distutils.command.build_py.build_py): - """Custom command to publish docs to S3.""" - - description = ( - "Publish docs to " - + "http://0x-order-utils-py.s3-website-us-east-1.amazonaws.com/" - ) - - def run(self): - """Run npm package `discharge` to build & upload docs.""" - subprocess.check_call("discharge deploy".split()) # nosec - - -class GanacheCommand(distutils.command.build_py.build_py): - """Custom command to publish to pypi.org.""" - - description = "Run ganache daemon to support tests." - - def run(self): - """Run ganache.""" - cmd_line = ( - "docker run -d -p 8545:8545 0xorg/ganache-cli:2.2.2" - ).split() - subprocess.call(cmd_line) # nosec - - -with open("README.md", "r") as file_handle: - README_MD = file_handle.read() - - -setup( - name="0x-order-utils", - version="4.0.0", - description="Order utilities for 0x applications", - long_description=README_MD, - long_description_content_type="text/markdown", - url=( - "https://github.com/0xProject/0x-monorepo/tree/development" - "/python-packages/order_utils" - ), - author="F. Eugene Aumson", - author_email="feuGeneA@users.noreply.github.com", - cmdclass={ - "clean": CleanCommandExtension, - "lint": LintCommand, - "test": TestCommandExtension, - "test_publish": TestPublishCommand, - "publish": PublishCommand, - "publish_docs": PublishDocsCommand, - "ganache": GanacheCommand, - }, - install_requires=[ - "0x-contract-addresses", - "0x-contract-artifacts", - "0x-json-schemas", - "deprecated", - "web3", - "eth-abi", - "eth_typing", - "eth_utils", - "mypy_extensions", - ], - extras_require={ - "dev": [ - "0x-contract-wrappers", - "bandit", - "black", - "coverage", - "coveralls", - "mypy<=0.770", # see https://github.com/python/mypy/issues/8953 - "mypy_extensions", - "pycodestyle", - "pydocstyle", - "pylint", - "pytest", - "sphinx", - "tox", - "twine", - ] - }, - python_requires=">=3.6, <4", - package_data={"zero_ex.order_utils": ["py.typed"]}, - package_dir={"": "src"}, - license="Apache 2.0", - keywords=( - "ethereum cryptocurrency 0x decentralized blockchain dex exchange" - ), - namespace_packages=["zero_ex"], - packages=find_packages("src"), - classifiers=[ - "Development Status :: 2 - Pre-Alpha", - "Intended Audience :: Developers", - "Intended Audience :: Financial and Insurance Industry", - "License :: OSI Approved :: Apache Software License", - "Natural Language :: English", - "Operating System :: OS Independent", - "Programming Language :: Python", - "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3.6", - "Programming Language :: Python :: 3.7", - "Topic :: Internet :: WWW/HTTP", - "Topic :: Office/Business :: Financial", - "Topic :: Other/Nonlisted Topic", - "Topic :: Security :: Cryptography", - "Topic :: Software Development :: Libraries", - "Topic :: Utilities", - ], - zip_safe=False, # required per mypy - command_options={ - "build_sphinx": { - "source_dir": ("setup.py", "src"), - "build_dir": ("setup.py", "build/docs"), - "warning_is_error": ("setup.py", "true"), - } - }, -) diff --git a/python-packages/order_utils/src/conf.py b/python-packages/order_utils/src/conf.py deleted file mode 100644 index 6b6776d014..0000000000 --- a/python-packages/order_utils/src/conf.py +++ /dev/null @@ -1,54 +0,0 @@ -"""Configuration file for the Sphinx documentation builder.""" - -# Reference: http://www.sphinx-doc.org/en/master/config - -from typing import List -import pkg_resources - - -# pylint: disable=invalid-name -# because these variables are not named in upper case, as globals should be. - -project = "0x-order-utils" -# pylint: disable=redefined-builtin -copyright = "2018, ZeroEx, Intl." -author = "F. Eugene Aumson" -version = pkg_resources.get_distribution("0x-order-utils").version -release = "" # The full version, including alpha/beta/rc tags - -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.doctest", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.viewcode", -] - -templates_path = ["doc_templates"] - -source_suffix = ".rst" -# eg: source_suffix = [".rst", ".md"] - -master_doc = "index" # The master toctree document. - -language = None - -exclude_patterns: List[str] = [] - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = None - -html_theme = "alabaster" - -html_static_path = ["doc_static"] -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". - -# Output file base name for HTML help builder. -htmlhelp_basename = "order_utilspydoc" - -# -- Extension configuration: - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = {"https://docs.python.org/": None} diff --git a/python-packages/order_utils/src/doc_static/.gitkeep b/python-packages/order_utils/src/doc_static/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/order_utils/src/doc_templates/.gitkeep b/python-packages/order_utils/src/doc_templates/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/order_utils/src/index.rst b/python-packages/order_utils/src/index.rst deleted file mode 100644 index f2df2e3a93..0000000000 --- a/python-packages/order_utils/src/index.rst +++ /dev/null @@ -1,24 +0,0 @@ -.. source for the sphinx-generated build/docs/web/index.html - -Python zero_ex.order_utils -========================== - -.. toctree:: - :maxdepth: 2 - :caption: Contents: - -.. automodule:: zero_ex.order_utils - :members: - -zero_ex.order_utils.asset_data_utils ------------------------------------- - -.. automodule:: zero_ex.order_utils.asset_data_utils - :members: - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` diff --git a/python-packages/order_utils/src/zero_ex/__init__.py b/python-packages/order_utils/src/zero_ex/__init__.py deleted file mode 100644 index 3fe1300cfb..0000000000 --- a/python-packages/order_utils/src/zero_ex/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -"""0x Python API.""" -__import__("pkg_resources").declare_namespace(__name__) # type: ignore diff --git a/python-packages/order_utils/src/zero_ex/dev_utils/__init__.py b/python-packages/order_utils/src/zero_ex/dev_utils/__init__.py deleted file mode 100644 index b6a224d2ce..0000000000 --- a/python-packages/order_utils/src/zero_ex/dev_utils/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Dev utils to be shared across 0x projects and packages.""" diff --git a/python-packages/order_utils/src/zero_ex/dev_utils/abi_utils.py b/python-packages/order_utils/src/zero_ex/dev_utils/abi_utils.py deleted file mode 100644 index cb062e32ad..0000000000 --- a/python-packages/order_utils/src/zero_ex/dev_utils/abi_utils.py +++ /dev/null @@ -1,101 +0,0 @@ -"""Ethereum ABI utilities. - -Builds on the eth-abi package, adding some convenience methods like those found -in npmjs.com/package/ethereumjs-abi. Ideally, all of this code should be -pushed upstream into eth-abi. -""" - -import re -from typing import Any, List - -from mypy_extensions import TypedDict - -from eth_abi import encode_abi -from web3 import Web3 - -from .type_assertions import assert_is_string, assert_is_list - - -class MethodSignature(TypedDict, total=False): - """Object interface to an ABI method signature.""" - - method: str - args: List[str] - - -def parse_signature(signature: str) -> MethodSignature: - """Parse a method signature into its constituent parts. - - >>> parse_signature("ERC20Token(address)") - {'method': 'ERC20Token', 'args': ['address']} - """ - assert_is_string(signature, "signature") - - matches = re.match(r"^(\w+)\((.+)\)$", signature) - if matches is None: - raise ValueError(f"Invalid method signature {signature}") - return {"method": matches[1], "args": matches[2].split(",")} - - -def elementary_name(name: str) -> str: - """Convert from short to canonical names; barely implemented. - - Modeled after ethereumjs-abi's ABI.elementaryName(), but only implemented - to support our particular use case and a few other simple ones. - - >>> elementary_name("address") - 'address' - >>> elementary_name("uint") - 'uint256' - """ - assert_is_string(name, "name") - - return { - "int": "int256", - "uint": "uint256", - "fixed": "fixed128x128", - "ufixed": "ufixed128x128", - }.get(name, name) - - -def event_id(name: str, types: List[str]) -> str: - """Return the Keccak-256 hash of the given method. - - >>> event_id("ERC20Token", ["address"]) - '0xf47261b06eedbfce68afd46d0f3c27c60b03faad319eaf33103611cf8f6456ad' - """ - assert_is_string(name, "name") - assert_is_list(types, "types") - - signature = f"{name}({','.join(list(map(elementary_name, types)))})" - return Web3.sha3(text=signature).hex() - - -def method_id(name: str, types: List[str]) -> str: - """Return the 4-byte method identifier. - - >>> method_id("ERC20Token", ["address"]) - '0xf47261b0' - """ - assert_is_string(name, "name") - assert_is_list(types, "types") - - return event_id(name, types)[0:10] - - -def simple_encode(method: str, *args: Any) -> bytes: - r"""Encode a method ABI. - - >>> simple_encode("ERC20Token(address)", "0x1dc4c1cefef38a777b15aa20260a54e584b16c48") - b'\xf4ra\xb0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x1d\xc4\xc1\xce\xfe\xf3\x8aw{\x15\xaa &\nT\xe5\x84\xb1lH' - """ # noqa: E501 (line too long) - assert_is_string(method, "method") - - signature: MethodSignature = parse_signature(method) - - return bytes.fromhex( - ( - method_id(signature["method"], signature["args"]) - + encode_abi(signature["args"], args).hex() - )[2:] - ) diff --git a/python-packages/order_utils/src/zero_ex/dev_utils/type_assertions.py b/python-packages/order_utils/src/zero_ex/dev_utils/type_assertions.py deleted file mode 100644 index 4681315a8b..0000000000 --- a/python-packages/order_utils/src/zero_ex/dev_utils/type_assertions.py +++ /dev/null @@ -1,87 +0,0 @@ -"""Assertions for runtime type checking of function arguments.""" - -from typing import Any - -from eth_utils import is_address -from web3.providers.base import BaseProvider - - -def assert_is_string(value: Any, name: str) -> None: - """If :param value: isn't of type str, raise a TypeError. - - >>> try: assert_is_string(123, 'var') - ... except TypeError as type_error: print(str(type_error)) - ... - expected variable 'var', with value 123, to have type 'str', not 'int' - """ - if not isinstance(value, str): - raise TypeError( - f"expected variable '{name}', with value {str(value)}, to have" - + f" type 'str', not '{type(value).__name__}'" - ) - - -def assert_is_list(value: Any, name: str) -> None: - """If :param value: isn't of type list, raise a TypeError. - - >>> try: assert_is_list(123, 'var') - ... except TypeError as type_error: print(str(type_error)) - ... - expected variable 'var', with value 123, to have type 'list', not 'int' - """ - if not isinstance(value, list): - raise TypeError( - f"expected variable '{name}', with value {str(value)}, to have" - + f" type 'list', not '{type(value).__name__}'" - ) - - -def assert_is_int(value: Any, name: str) -> None: - """If :param value: isn't of type int, raise a TypeError. - - >>> try: assert_is_int('asdf', 'var') - ... except TypeError as type_error: print(str(type_error)) - ... - expected variable 'var', with value asdf, to have type 'int', not 'str' - """ - if not isinstance(value, int): - raise TypeError( - f"expected variable '{name}', with value {str(value)}, to have" - + f" type 'int', not '{type(value).__name__}'" - ) - - -def assert_is_hex_string(value: Any, name: str) -> None: - """Assert that :param value: is a string of hex chars. - - If :param value: isn't a str, raise a TypeError. If it is a string but - contains non-hex characters ("0x" prefix permitted), raise a ValueError. - """ - assert_is_string(value, name) - int(value, 16) # raises a ValueError if value isn't a base-16 str - - -def assert_is_address(value: Any, name: str) -> None: - """Assert that `value` is a valid Ethereum address. - - If `value` isn't a hex string, raise a TypeError. If it isn't a valid - Ethereum address, raise a ValueError. - """ - assert_is_hex_string(value, name) - if not is_address(value): - raise ValueError( - f"Expected variable '{name}' to be a valid Ethereum" - + " address, but it's not." - ) - - -def assert_is_provider(value: Any, name: str) -> None: - """Assert that `value` is a Web3 provider. - - If `value` isn't a Web3 provider, raise a TypeError. - """ - if not isinstance(value, BaseProvider): - raise TypeError( - f"Expected variable '{name}' to be an instance of a Web3 provider," - + " but it's not." - ) diff --git a/python-packages/order_utils/src/zero_ex/order_utils/__init__.py b/python-packages/order_utils/src/zero_ex/order_utils/__init__.py deleted file mode 100644 index be30682f7b..0000000000 --- a/python-packages/order_utils/src/zero_ex/order_utils/__init__.py +++ /dev/null @@ -1,399 +0,0 @@ -r"""Order utilities for 0x applications. - -Setup ------ - -Install the package with pip:: - - pip install 0x-order-utils - -Some methods require the caller to pass in a `Web3.BaseProvider`:code: object. -For local testing one may construct such a provider pointing at an instance of -`ganache-cli `_ which has the 0x -contracts deployed on it. For convenience, a docker container is provided for -just this purpose. To start it:: - - docker run -d -p 8545:8545 0xorg/ganache-cli - -""" - -from enum import auto, Enum -import json -from typing import cast, Tuple, Union - -from pkg_resources import resource_string -from mypy_extensions import TypedDict - -from eth_typing import HexStr -from eth_utils import keccak, remove_0x_prefix, to_bytes, to_checksum_address -from web3 import Web3 -import web3.exceptions -from web3.providers.base import BaseProvider -from web3.contract import Contract - -from zero_ex.contract_addresses import chain_to_addresses, ChainId -import zero_ex.contract_artifacts -from zero_ex.contract_wrappers.exchange import Exchange -from zero_ex.contract_wrappers.exchange.types import Order -from zero_ex.contract_wrappers.order_conversions import order_to_jsdict -from zero_ex.dev_utils.type_assertions import ( - assert_is_address, - assert_is_hex_string, - assert_is_provider, -) -from zero_ex.json_schemas import assert_valid - - -class _Constants: - """Static data used by order utilities.""" - - null_address = "0x0000000000000000000000000000000000000000" - - eip191_header = b"\x19\x01" - - eip712_domain_separator_schema_hash = keccak( - b"EIP712Domain(" - + b"string name," - + b"string version," - + b"uint256 chainId," - + b"address verifyingContract" - + b")" - ) - - eip712_domain_struct_header = ( - eip712_domain_separator_schema_hash - + keccak(b"0x Protocol") - + keccak(b"3.0.0") - ) - - eip712_order_schema_hash = keccak( - b"Order(" - + b"address makerAddress," - + b"address takerAddress," - + b"address feeRecipientAddress," - + b"address senderAddress," - + b"uint256 makerAssetAmount," - + b"uint256 takerAssetAmount," - + b"uint256 makerFee," - + b"uint256 takerFee," - + b"uint256 expirationTimeSeconds," - + b"uint256 salt," - + b"bytes makerAssetData," - + b"bytes takerAssetData," - + b"bytes makerFeeAssetData," - + b"bytes takerFeeAssetData" - + b")" - ) - - class SignatureType(Enum): - """Enumeration of known signature types.""" - - ILLEGAL = 0 - INVALID = auto() - EIP712 = auto() - ETH_SIGN = auto() - WALLET = auto() - VALIDATOR = auto() - PRE_SIGNED = auto() - N_SIGNATURE_TYPES = auto() - - -def generate_order_hash_hex( - order: Order, exchange_address: str, chain_id: int -) -> str: - """Calculate the hash of the given order as a hexadecimal string. - - :param order: The order to be hashed. Must conform to `the 0x order JSON schema `_. - :param exchange_address: The address to which the 0x Exchange smart - contract has been deployed. - :returns: A string, of ASCII hex digits, representing the order hash. - - Inputs and expected result below were copied from - @0x/order-utils/test/order_hash_test.ts - - >>> generate_order_hash_hex( - ... Order( - ... makerAddress="0x0000000000000000000000000000000000000000", - ... takerAddress="0x0000000000000000000000000000000000000000", - ... feeRecipientAddress="0x0000000000000000000000000000000000000000", - ... senderAddress="0x0000000000000000000000000000000000000000", - ... makerAssetAmount="0", - ... takerAssetAmount="0", - ... makerFee="0", - ... takerFee="0", - ... expirationTimeSeconds="0", - ... salt="0", - ... makerAssetData=((0).to_bytes(1, byteorder='big') * 20), - ... takerAssetData=((0).to_bytes(1, byteorder='big') * 20), - ... makerFeeAssetData=((0).to_bytes(1, byteorder='big') * 20), - ... takerFeeAssetData=((0).to_bytes(1, byteorder='big') * 20), - ... ), - ... exchange_address="0x1dc4c1cefef38a777b15aa20260a54e584b16c48", - ... chain_id=1337 - ... ) - 'cb36e4fedb36508fb707e2c05e21bffc7a72766ccae93f8ff096693fff7f1714' - """ # noqa: E501 (line too long) - assert_is_address(exchange_address, "exchange_address") - assert_valid( - order_to_jsdict(order, chain_id, exchange_address), "/orderSchema" - ) - - def pad_20_bytes_to_32(twenty_bytes: bytes): - return bytes(12) + twenty_bytes - - def int_to_32_big_endian_bytes(i: int): - return i.to_bytes(32, byteorder="big") - - eip712_domain_struct_hash = keccak( - _Constants.eip712_domain_struct_header - + int_to_32_big_endian_bytes(int(chain_id)) - + pad_20_bytes_to_32(to_bytes(hexstr=exchange_address)) - ) - - def ensure_bytes(str_or_bytes: Union[str, bytes]) -> bytes: - return ( - to_bytes(hexstr=cast(bytes, str_or_bytes)) - if isinstance(str_or_bytes, str) - else str_or_bytes - ) - - eip712_order_struct_hash = keccak( - _Constants.eip712_order_schema_hash - + pad_20_bytes_to_32(to_bytes(hexstr=order["makerAddress"])) - + pad_20_bytes_to_32(to_bytes(hexstr=order["takerAddress"])) - + pad_20_bytes_to_32(to_bytes(hexstr=order["feeRecipientAddress"])) - + pad_20_bytes_to_32(to_bytes(hexstr=order["senderAddress"])) - + int_to_32_big_endian_bytes(int(order["makerAssetAmount"])) - + int_to_32_big_endian_bytes(int(order["takerAssetAmount"])) - + int_to_32_big_endian_bytes(int(order["makerFee"])) - + int_to_32_big_endian_bytes(int(order["takerFee"])) - + int_to_32_big_endian_bytes(int(order["expirationTimeSeconds"])) - + int_to_32_big_endian_bytes(int(order["salt"])) - + keccak(ensure_bytes(order["makerAssetData"])) - + keccak(ensure_bytes(order["takerAssetData"])) - + keccak(ensure_bytes(order["makerFeeAssetData"])) - + keccak(ensure_bytes(order["takerFeeAssetData"])) - ) - - return keccak( - _Constants.eip191_header - + eip712_domain_struct_hash - + eip712_order_struct_hash - ).hex() - - -def is_valid_signature( - provider: BaseProvider, data: str, signature: str, signer_address: str -) -> bool: - """Check the validity of the supplied signature. - - Check if the supplied `signature`:code: corresponds to signing `data`:code: - with the private key corresponding to `signer_address`:code:. - - :param provider: A Web3 provider able to access the 0x Exchange contract. - :param data: The hex encoded data signed by the supplied signature. - :param signature: The hex encoded signature. - :param signer_address: The hex encoded address that signed the data to - produce the supplied signature. - :returns: Tuple consisting of a boolean and a string. Boolean is true if - valid, false otherwise. If false, the string describes the reason. - - >>> is_valid_signature( - ... Web3.HTTPProvider("http://127.0.0.1:8545"), - ... '0x6927e990021d23b1eb7b8789f6a6feaf98fe104bb0cf8259421b79f9a34222b0', - ... '0x1B61a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351bc3340349190569279751135161d22529dc25add4f6069af05be04cacbda2ace225403', - ... '0x5409ed021d9299bf6814279a6a1411a7e866a631', - ... ) - True - """ # noqa: E501 (line too long) - assert_is_provider(provider, "provider") - assert_is_hex_string(data, "data") - assert_is_hex_string(signature, "signature") - assert_is_address(signer_address, "signer_address") - - return Exchange( - provider, - chain_to_addresses( - ChainId( - int(Web3(provider).eth.chainId) # pylint: disable=no-member - ) - ).exchange, - ).is_valid_hash_signature.call( - bytes.fromhex(remove_0x_prefix(HexStr(data))), - to_checksum_address(signer_address), - bytes.fromhex(remove_0x_prefix(HexStr(signature))), - ) - - -class ECSignature(TypedDict): - """Object representation of an elliptic curve signature's parameters.""" - - v: int - r: str - s: str - - -def _parse_signature_hex_as_vrs(signature_hex: str) -> ECSignature: - """Parse signature hex as a concatentation of EC parameters ordered V, R, S. - - >>> _parse_signature_hex_as_vrs('0x1b117902c86dfb95fe0d1badd983ee166ad259b27acb220174cbb4460d872871137feabdfe76e05924b484789f79af4ee7fa29ec006cedce1bbf369320d034e10b03') - {'v': 27, 'r': '117902c86dfb95fe0d1badd983ee166ad259b27acb220174cbb4460d87287113', 's': '7feabdfe76e05924b484789f79af4ee7fa29ec006cedce1bbf369320d034e10b'} - """ # noqa: E501 (line too long) - signature: ECSignature = { - "v": int(signature_hex[2:4], 16), - "r": signature_hex[4:68], - "s": signature_hex[68:132], - } - if signature["v"] == 0 or signature["v"] == 1: - signature["v"] = signature["v"] + 27 - return signature - - -def _parse_signature_hex_as_rsv(signature_hex: str) -> ECSignature: - """Parse signature hex as a concatentation of EC parameters ordered R, S, V. - - >>> _parse_signature_hex_as_rsv('0x117902c86dfb95fe0d1badd983ee166ad259b27acb220174cbb4460d872871137feabdfe76e05924b484789f79af4ee7fa29ec006cedce1bbf369320d034e10b00') - {'r': '117902c86dfb95fe0d1badd983ee166ad259b27acb220174cbb4460d87287113', 's': '7feabdfe76e05924b484789f79af4ee7fa29ec006cedce1bbf369320d034e10b', 'v': 27} - """ # noqa: E501 (line too long) - signature: ECSignature = { - "r": signature_hex[2:66], - "s": signature_hex[66:130], - "v": int(signature_hex[130:132], 16), - } - if signature["v"] == 0 or signature["v"] == 1: - signature["v"] = signature["v"] + 27 - return signature - - -def _convert_ec_signature_to_vrs_hex(signature: ECSignature) -> str: - """Convert elliptic curve signature object to hex hash string. - - >>> _convert_ec_signature_to_vrs_hex( - ... { - ... 'r': '117902c86dfb95fe0d1badd983ee166ad259b27acb220174cbb4460d87287113', - ... 's': '7feabdfe76e05924b484789f79af4ee7fa29ec006cedce1bbf369320d034e10b', - ... 'v': 27 - ... } - ... ) - '0x1b117902c86dfb95fe0d1badd983ee166ad259b27acb220174cbb4460d872871137feabdfe76e05924b484789f79af4ee7fa29ec006cedce1bbf369320d034e10b' - """ # noqa: E501 (line too long) - return ( - "0x" - + signature["v"].to_bytes(1, byteorder="big").hex() - + signature["r"] - + signature["s"] - ) - - -def sign_hash( - web3_or_provider: Union[Web3, BaseProvider], - signer_address: str, - hash_hex: str, -) -> str: - """Sign a message with the given hash, and return the signature. - - :param web3_or_provider: Either an instance of `web3.Web3`:code: or - `web3.providers.base.BaseProvider`:code: - :param signer_address: The address of the signing account. - :param hash_hex: A hex string representing the hash, like that returned - from `generate_order_hash_hex()`:code:. - :returns: A string, of ASCII hex digits, representing the signature. - - >>> provider = Web3.HTTPProvider("http://127.0.0.1:8545") - >>> sign_hash( - ... provider, - ... Web3(provider).geth.personal.listAccounts()[0], - ... '0x34decbedc118904df65f379a175bb39ca18209d6ce41d5ed549d54e6e0a95004', - ... ) - '0x1b117902c86dfb95fe0d1badd983ee166ad259b27acb220174cbb4460d872871137feabdfe76e05924b484789f79af4ee7fa29ec006cedce1bbf369320d034e10b03' - """ # noqa: E501 (line too long) - web3_instance = None - if isinstance(web3_or_provider, BaseProvider): - web3_instance = Web3(web3_or_provider) - elif isinstance(web3_or_provider, Web3): - web3_instance = web3_or_provider - else: - raise TypeError( - "Expected parameter 'web3_or_provider' to be an instance of either" - + " Web3 or BaseProvider" - ) - - assert_is_address(signer_address, "signer_address") - assert_is_hex_string(hash_hex, "hash_hex") - - # false positive from pylint: disable=no-member - signature = web3_instance.eth.sign( # type: ignore - signer_address, hexstr=hash_hex.replace("0x", "") - ).hex() - - valid_v_param_values = [27, 28] - - # HACK: There is no consensus on whether the signatureHex string should be - # formatted as v + r + s OR r + s + v, and different clients (even - # different versions of the same client) return the signature params in - # different orders. In order to support all client implementations, we - # parse the signature in both ways, and evaluate if either one is a valid - # signature. r + s + v is the most prevalent format from eth_sign, so we - # attempt this first. - - ec_signature = _parse_signature_hex_as_rsv(signature) - if ec_signature["v"] in valid_v_param_values: - signature_as_vrst_hex = ( - _convert_ec_signature_to_vrs_hex(ec_signature) - + _Constants.SignatureType.ETH_SIGN.value.to_bytes( - 1, byteorder="big" - ).hex() - ) - - valid = is_valid_signature( - web3_instance.provider, - hash_hex, - signature_as_vrst_hex, - signer_address, - ) - - if valid is True: - return signature_as_vrst_hex - - ec_signature = _parse_signature_hex_as_vrs(signature) - if ec_signature["v"] in valid_v_param_values: - signature_as_vrst_hex = ( - _convert_ec_signature_to_vrs_hex(ec_signature) - + _Constants.SignatureType.ETH_SIGN.value.to_bytes( - 1, byteorder="big" - ).hex() - ) - valid = is_valid_signature( - web3_instance.provider, - hash_hex, - signature_as_vrst_hex, - signer_address, - ) - - if valid is True: - return signature_as_vrst_hex - - raise RuntimeError( - "Signature returned from web3 provider is in an unknown format. " - + "Signature was: {signature}" - ) - - -def sign_hash_to_bytes( - web3_or_provider: Union[Web3, BaseProvider], - signer_address: str, - hash_hex: str, -) -> bytes: - """Sign a message with the given hash, and return the signature. - - >>> provider = Web3.HTTPProvider("http://127.0.0.1:8545") - >>> sign_hash_to_bytes( - ... provider, - ... Web3(provider).geth.personal.listAccounts()[0], - ... '0x34decbedc118904df65f379a175bb39ca18209d6ce41d5ed549d54e6e0a95004', - ... ).decode(encoding='utf_8') - '1b117902c86dfb95fe0d1badd983ee166ad259b27acb220174cbb4460d872871137feabdfe76e05924b484789f79af4ee7fa29ec006cedce1bbf369320d034e10b03' - """ # noqa: E501 (line too long) - return remove_0x_prefix( - HexStr(sign_hash(web3_or_provider, signer_address, hash_hex)) - ).encode(encoding="utf_8") diff --git a/python-packages/order_utils/src/zero_ex/order_utils/asset_data_utils.py b/python-packages/order_utils/src/zero_ex/order_utils/asset_data_utils.py deleted file mode 100644 index 12849da595..0000000000 --- a/python-packages/order_utils/src/zero_ex/order_utils/asset_data_utils.py +++ /dev/null @@ -1,186 +0,0 @@ -"""Asset data encoding and decoding utilities.""" - -from typing import NamedTuple - -import eth_abi -from deprecated.sphinx import deprecated - -from zero_ex.dev_utils import abi_utils -from zero_ex.dev_utils.type_assertions import assert_is_string, assert_is_int - - -ERC20_ASSET_DATA_BYTE_LENGTH = 36 -ERC721_ASSET_DATA_MINIMUM_BYTE_LENGTH = 53 -SELECTOR_LENGTH = 10 - - -class ERC20AssetData(NamedTuple): - """Object interface to ERC20 asset data.""" - - asset_proxy_id: str - """Asset proxy identifier.""" - - token_address: str - """Token address""" - - -class ERC721AssetData(NamedTuple): - """Object interface to ERC721 asset data.""" - - asset_proxy_id: str - """Asset proxy identifier.""" - - token_address: str - """Token address""" - - token_id: int - """Token identifier.""" - - -@deprecated(reason='use `"0x"+encode_erc20().hex()` instead') -def encode_erc20_asset_data(token_address: str) -> str: - """Encode an ERC20 token address into an asset data string. - - :param token_address: the ERC20 token's contract address. - :returns: hex encoded asset data string, usable in the makerAssetData or - takerAssetData fields in a 0x order. - - >>> encode_erc20_asset_data('0x1dc4c1cefef38a777b15aa20260a54e584b16c48') - '0xf47261b00000000000000000000000001dc4c1cefef38a777b15aa20260a54e584b16c48' - """ - assert_is_string(token_address, "token_address") - - return ( - "0x" - + abi_utils.simple_encode("ERC20Token(address)", token_address).hex() - ) - - -def encode_erc20(token_address: str) -> bytes: - """Encode an ERC20 token address into asset data bytes. - - :param token_address: the ERC20 token's contract address. - :returns: hex encoded asset data string, usable in the makerAssetData or - takerAssetData fields in a 0x order. - - >>> encode_erc20('0x1dc4c1cefef38a777b15aa20260a54e584b16c48').hex() - 'f47261b00000000000000000000000001dc4c1cefef38a777b15aa20260a54e584b16c48' - """ - assert_is_string(token_address, "token_address") - - return abi_utils.simple_encode("ERC20Token(address)", token_address) - - -def decode_erc20_asset_data(asset_data: str) -> ERC20AssetData: - """Decode an ERC20 asset data hex string. - - :param asset_data: String produced by prior call to encode_erc20_asset_data() - - >>> decode_erc20_asset_data("0xf47261b00000000000000000000000001dc4c1cefef38a777b15aa20260a54e584b16c48") - ERC20AssetData(asset_proxy_id='0xf47261b0', token_address='0x1dc4c1cefef38a777b15aa20260a54e584b16c48') - """ # noqa: E501 (line too long) - assert_is_string(asset_data, "asset_data") - - if len(asset_data) < ERC20_ASSET_DATA_BYTE_LENGTH: - raise ValueError( - "Could not decode ERC20 Proxy Data. Expected length of encoded" - + f" data to be at least {str(ERC20_ASSET_DATA_BYTE_LENGTH)}." - + f" Got {str(len(asset_data))}." - ) - - asset_proxy_id: str = asset_data[0:SELECTOR_LENGTH] - if asset_proxy_id != abi_utils.method_id("ERC20Token", ["address"]): - raise ValueError( - "Could not decode ERC20 Proxy Data. Expected Asset Proxy Id to be" - + f" ERC20 ({abi_utils.method_id('ERC20Token', ['address'])})" - + f" but got {asset_proxy_id}." - ) - - # workaround for https://github.com/PyCQA/pylint/issues/1498 - # pylint: disable=unsubscriptable-object - token_address = eth_abi.decode_abi( - ["address"], bytes.fromhex(asset_data[SELECTOR_LENGTH:]) - )[0] - - return ERC20AssetData( - asset_proxy_id=asset_proxy_id, token_address=token_address - ) - - -@deprecated(reason='use `"0x"+encode_erc721().hex()` instead') -def encode_erc721_asset_data(token_address: str, token_id: int) -> str: - """Encode an ERC721 asset data hex string. - - :param token_address: the ERC721 token's contract address. - :param token_id: the identifier of the asset's instance of the token. - :returns: hex encoded asset data string, usable in the makerAssetData or - takerAssetData fields in a 0x order. - - >>> encode_erc721_asset_data('0x1dc4c1cefef38a777b15aa20260a54e584b16c48', 1) - '0x025717920000000000000000000000001dc4c1cefef38a777b15aa20260a54e584b16c480000000000000000000000000000000000000000000000000000000000000001' - """ # noqa: E501 (line too long) - assert_is_string(token_address, "token_address") - assert_is_int(token_id, "token_id") - - return ( - "0x" - + abi_utils.simple_encode( - "ERC721Token(address,uint256)", token_address, token_id - ).hex() - ) - - -def encode_erc721(token_address: str, token_id: int) -> bytes: - """Encode an ERC721 token address into asset data bytes. - - :param token_address: the ERC721 token's contract address. - :param token_id: the identifier of the asset's instance of the token. - :returns: hex encoded asset data string, usable in the makerAssetData or - takerAssetData fields in a 0x order. - - >>> encode_erc721('0x1dc4c1cefef38a777b15aa20260a54e584b16c48', 1).hex() - '025717920000000000000000000000001dc4c1cefef38a777b15aa20260a54e584b16c480000000000000000000000000000000000000000000000000000000000000001' - """ # noqa: E501 (line too long) - assert_is_string(token_address, "token_address") - assert_is_int(token_id, "token_id") - - return abi_utils.simple_encode( - "ERC721Token(address,uint256)", token_address, token_id - ) - - -def decode_erc721_asset_data(asset_data: str) -> ERC721AssetData: - """Decode an ERC721 asset data hex string. - - >>> decode_erc721_asset_data('0x025717920000000000000000000000001dc4c1cefef38a777b15aa20260a54e584b16c480000000000000000000000000000000000000000000000000000000000000001') - ERC721AssetData(asset_proxy_id='0x02571792', token_address='0x1dc4c1cefef38a777b15aa20260a54e584b16c48', token_id=1) - """ # noqa: E501 (line too long) - assert_is_string(asset_data, "asset_data") - - if len(asset_data) < ERC721_ASSET_DATA_MINIMUM_BYTE_LENGTH: - raise ValueError( - "Could not decode ERC721 Asset Data. Expected length of encoded" - + f"data to be at least {ERC721_ASSET_DATA_MINIMUM_BYTE_LENGTH}. " - + f"Got {len(asset_data)}." - ) - - asset_proxy_id: str = asset_data[0:SELECTOR_LENGTH] - if asset_proxy_id != abi_utils.method_id( - "ERC721Token", ["address", "uint256"] - ): - raise ValueError( - "Could not decode ERC721 Asset Data. Expected Asset Proxy Id to be" - + " ERC721 (" - + f"{abi_utils.method_id('ERC721Token', ['address', 'uint256'])}" - + f"), but got {asset_proxy_id}" - ) - - (token_address, token_id) = eth_abi.decode_abi( - ["address", "uint256"], bytes.fromhex(asset_data[SELECTOR_LENGTH:]) - ) - - return ERC721AssetData( - asset_proxy_id=asset_proxy_id, - token_address=token_address, - token_id=token_id, - ) diff --git a/python-packages/order_utils/src/zero_ex/order_utils/py.typed b/python-packages/order_utils/src/zero_ex/order_utils/py.typed deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/order_utils/stubs/deprecated/__init__.pyi b/python-packages/order_utils/stubs/deprecated/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/order_utils/stubs/deprecated/sphinx/__init__.pyi b/python-packages/order_utils/stubs/deprecated/sphinx/__init__.pyi deleted file mode 100644 index 17abdffde4..0000000000 --- a/python-packages/order_utils/stubs/deprecated/sphinx/__init__.pyi +++ /dev/null @@ -1,2 +0,0 @@ -def deprecated(*args, **kwargs): - ... diff --git a/python-packages/order_utils/stubs/distutils/__init__.pyi b/python-packages/order_utils/stubs/distutils/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/order_utils/stubs/distutils/command/__init__.pyi b/python-packages/order_utils/stubs/distutils/command/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/order_utils/stubs/distutils/command/clean.pyi b/python-packages/order_utils/stubs/distutils/command/clean.pyi deleted file mode 100644 index 46a42ddb13..0000000000 --- a/python-packages/order_utils/stubs/distutils/command/clean.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from distutils.core import Command - -class clean(Command): - def initialize_options(self: clean) -> None: ... - def finalize_options(self: clean) -> None: ... - def run(self: clean) -> None: ... - ... diff --git a/python-packages/order_utils/stubs/pytest/__init__.pyi b/python-packages/order_utils/stubs/pytest/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/order_utils/stubs/pytest/raises.pyi b/python-packages/order_utils/stubs/pytest/raises.pyi deleted file mode 100644 index 2e3b29f3dc..0000000000 --- a/python-packages/order_utils/stubs/pytest/raises.pyi +++ /dev/null @@ -1 +0,0 @@ -def raises(exception: Exception) -> ExceptionInfo: ... diff --git a/python-packages/order_utils/stubs/setuptools/__init__.pyi b/python-packages/order_utils/stubs/setuptools/__init__.pyi deleted file mode 100644 index 8ea8d32b7e..0000000000 --- a/python-packages/order_utils/stubs/setuptools/__init__.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from distutils.dist import Distribution -from typing import Any, List - -def setup(**attrs: Any) -> Distribution: ... - -class Command: ... - -def find_packages(where: str) -> List[str]: ... diff --git a/python-packages/order_utils/stubs/setuptools/command/__init__.pyi b/python-packages/order_utils/stubs/setuptools/command/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/order_utils/stubs/setuptools/command/test.pyi b/python-packages/order_utils/stubs/setuptools/command/test.pyi deleted file mode 100644 index c5ec770ad3..0000000000 --- a/python-packages/order_utils/stubs/setuptools/command/test.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from setuptools import Command - -class test(Command): ... diff --git a/python-packages/order_utils/stubs/sha3/__init__.pyi b/python-packages/order_utils/stubs/sha3/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/order_utils/stubs/web3/__init__.pyi b/python-packages/order_utils/stubs/web3/__init__.pyi deleted file mode 100644 index 913a0431aa..0000000000 --- a/python-packages/order_utils/stubs/web3/__init__.pyi +++ /dev/null @@ -1,42 +0,0 @@ -from typing import Dict, List, Optional, Union - -from web3.contract import Contract -from web3.providers.base import BaseProvider - - -class Web3: - class HTTPProvider(BaseProvider): - ... - - def __init__(self, provider: BaseProvider) -> None: ... - - @staticmethod - def sha3( - primitive: Optional[Union[bytes, int, None]] = None, - text: Optional[str] = None, - hexstr: Optional[str] = None - ) -> bytes: ... - - class net: - version: str - ... - - class Eth: - @staticmethod - def contract(address: str, abi: Dict) -> Contract: ... - chainId: int - ... - - eth: Eth - - class geth: - class personal: - @staticmethod - def listAccounts() -> List[str]: - ... - ... - ... - - provider: BaseProvider - - ... diff --git a/python-packages/order_utils/stubs/web3/contract.pyi b/python-packages/order_utils/stubs/web3/contract.pyi deleted file mode 100644 index 826fa5590c..0000000000 --- a/python-packages/order_utils/stubs/web3/contract.pyi +++ /dev/null @@ -1,12 +0,0 @@ -from typing import Callable - - -class ContractFunctions: - def __getattr__(self, function_name) -> Callable: - ... - ... - - -class Contract: - functions: ContractFunctions - ... diff --git a/python-packages/order_utils/stubs/web3/exceptions.pyi b/python-packages/order_utils/stubs/web3/exceptions.pyi deleted file mode 100644 index 83abf973d1..0000000000 --- a/python-packages/order_utils/stubs/web3/exceptions.pyi +++ /dev/null @@ -1,2 +0,0 @@ -class BadFunctionCallOutput(Exception): - ... diff --git a/python-packages/order_utils/stubs/web3/providers/__init__.pyi b/python-packages/order_utils/stubs/web3/providers/__init__.pyi deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/order_utils/stubs/web3/providers/base.pyi b/python-packages/order_utils/stubs/web3/providers/base.pyi deleted file mode 100644 index 82ca9e3da1..0000000000 --- a/python-packages/order_utils/stubs/web3/providers/base.pyi +++ /dev/null @@ -1,2 +0,0 @@ -class BaseProvider: - ... diff --git a/python-packages/order_utils/test/__init__.py b/python-packages/order_utils/test/__init__.py deleted file mode 100644 index ec5b114aa2..0000000000 --- a/python-packages/order_utils/test/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Tests of zero_x.order_utils.""" diff --git a/python-packages/order_utils/test/test_abi_utils.py b/python-packages/order_utils/test/test_abi_utils.py deleted file mode 100644 index 49a2a4f205..0000000000 --- a/python-packages/order_utils/test/test_abi_utils.py +++ /dev/null @@ -1,53 +0,0 @@ -"""Tests of 0x.abi_utils.""" - -import pytest - -from zero_ex.dev_utils.abi_utils import ( - elementary_name, - event_id, - method_id, - parse_signature, - simple_encode, -) - - -def test_parse_signature_type_error(): - """Test that passing in wrong types raises TypeError.""" - with pytest.raises(TypeError): - parse_signature(123) - - -def test_parse_signature_bad_input(): - """Test that passing a non-signature string raises a ValueError.""" - with pytest.raises(ValueError): - parse_signature("a string that's not even close to a signature") - - -def test_elementary_name_type_error(): - """Test that passing in wrong types raises TypeError.""" - with pytest.raises(TypeError): - elementary_name(123) - - -def test_event_id_type_error(): - """Test that passing in wrong types raises TypeError.""" - with pytest.raises(TypeError): - event_id(123, []) - - with pytest.raises(TypeError): - event_id("valid string", 123) - - -def test_method_id_type_error(): - """Test that passing in wrong types raises TypeError.""" - with pytest.raises(TypeError): - method_id(123, []) - - with pytest.raises(TypeError): - method_id("ERC20Token", 123) - - -def test_simple_encode_type_error(): - """Test that passing in wrong types raises TypeError.""" - with pytest.raises(TypeError): - simple_encode(123) diff --git a/python-packages/order_utils/test/test_asset_data_utils.py b/python-packages/order_utils/test/test_asset_data_utils.py deleted file mode 100644 index 0793687145..0000000000 --- a/python-packages/order_utils/test/test_asset_data_utils.py +++ /dev/null @@ -1,72 +0,0 @@ -"""Tests of 0x.order_utils.asset_data_utils.""" - -import pytest - -from zero_ex.order_utils.asset_data_utils import ( - decode_erc20_asset_data, - decode_erc721_asset_data, - encode_erc20_asset_data, - encode_erc721_asset_data, - ERC20_ASSET_DATA_BYTE_LENGTH, - ERC721_ASSET_DATA_MINIMUM_BYTE_LENGTH, -) - - -def test_encode_erc20_asset_data_type_error(): - """Test that passing in a non-string raises a TypeError.""" - with pytest.raises(TypeError): - encode_erc20_asset_data(123) - - -def test_decode_erc20_asset_data_type_error(): - """Test that passing in a non-string raises a TypeError.""" - with pytest.raises(TypeError): - decode_erc20_asset_data(123) - - -def test_decode_erc20_asset_data_too_short(): - """Test that passing an insufficiently long string raises a ValueError.""" - with pytest.raises(ValueError): - decode_erc20_asset_data(" " * (ERC20_ASSET_DATA_BYTE_LENGTH - 1)) - - -def test_decode_erc20_asset_data_invalid_proxy_id(): - """Test that passing data with an invalid proxy ID raises a ValueError.""" - with pytest.raises(ValueError): - decode_erc20_asset_data( - "0xffffffff" + (" " * ERC20_ASSET_DATA_BYTE_LENGTH) - ) - - -def test_encode_erc721_asset_data_type_error_on_token_address(): - """Test that passing a non-string for token_address raises a TypeError.""" - with pytest.raises(TypeError): - encode_erc721_asset_data(123, 123) - - -def test_encode_erc721_asset_data_type_error_on_token_id(): - """Test that passing a non-int for token_id raises a TypeError.""" - with pytest.raises(TypeError): - encode_erc721_asset_data("asdf", "asdf") - - -def test_decode_erc721_asset_data_type_error(): - """Test that passing a non-string for asset_data raises a TypeError.""" - with pytest.raises(TypeError): - decode_erc721_asset_data(123) - - -def test_decode_erc721_asset_data_with_asset_data_too_short(): - """Test that passing in too short of a string raises a ValueError.""" - with pytest.raises(ValueError): - decode_erc721_asset_data( - " " * (ERC721_ASSET_DATA_MINIMUM_BYTE_LENGTH - 1) - ) - - -def test_decode_erc721_asset_data_invalid_proxy_id(): - """Test that passing in too short of a string raises a ValueError.""" - with pytest.raises(ValueError): - decode_erc721_asset_data( - "0xffffffff" + " " * (ERC721_ASSET_DATA_MINIMUM_BYTE_LENGTH - 1) - ) diff --git a/python-packages/order_utils/test/test_generate_order_hash_hex.py b/python-packages/order_utils/test/test_generate_order_hash_hex.py deleted file mode 100644 index cb6dca35c7..0000000000 --- a/python-packages/order_utils/test/test_generate_order_hash_hex.py +++ /dev/null @@ -1,33 +0,0 @@ -"""Test zero_ex.order_utils.get_order_hash_hex().""" - -from zero_ex.order_utils import generate_order_hash_hex - - -def test_get_order_hash_hex__empty_order(): - """Test the hashing of an uninitialized order.""" - expected_hash_hex = ( - "331cb7e07a757bae130702da6646c26531798c92bcfaf671817268fd2c188531" - ) - actual_hash_hex = generate_order_hash_hex( - { - "makerAddress": "0x0000000000000000000000000000000000000000", - "takerAddress": "0x0000000000000000000000000000000000000000", - "senderAddress": "0x0000000000000000000000000000000000000000", - "feeRecipientAddress": ( - "0x0000000000000000000000000000000000000000" - ), - "makerAssetData": (b"\x00") * 20, - "takerAssetData": (b"\x00") * 20, - "makerFeeAssetData": (b"\x00") * 20, - "takerFeeAssetData": (b"\x00") * 20, - "salt": 0, - "makerFee": 0, - "takerFee": 0, - "makerAssetAmount": 0, - "takerAssetAmount": 0, - "expirationTimeSeconds": 0, - }, - "0x1dc4c1cefef38a777b15aa20260a54e584b16c48", - 50, - ) - assert actual_hash_hex == expected_hash_hex diff --git a/python-packages/order_utils/test/test_signature_utils.py b/python-packages/order_utils/test/test_signature_utils.py deleted file mode 100644 index 7bcd090169..0000000000 --- a/python-packages/order_utils/test/test_signature_utils.py +++ /dev/null @@ -1,169 +0,0 @@ -"""Tests of zero_ex.order_utils.signature_utils.""" - -import pytest -from web3 import Web3 - -from zero_ex.contract_wrappers.exchange.exceptions import ( - SignatureError, - SignatureErrorCodes, -) -from zero_ex.order_utils import is_valid_signature, sign_hash_to_bytes - - -def test_is_valid_signature__provider_wrong_type(): - """Test that giving a non-HTTPProvider raises a TypeError.""" - with pytest.raises(TypeError): - is_valid_signature( - 123, - "0x6927e990021d23b1eb7b8789f6a6feaf98fe104bb0cf8259421b79f9a34222b" - + "0", - "0x1B61a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351b" - + "c3340349190569279751135161d22529dc25add4f6069af05be04cacbda2ace" - + "225403", - "0x5409ed021d9299bf6814279a6a1411a7e866a631", - ) - - -def test_is_valid_signature__data_not_string(): - """Test that giving non-string `data` raises a TypeError.""" - with pytest.raises(TypeError): - is_valid_signature( - Web3.HTTPProvider("http://127.0.0.1:8545"), - 123, - "0x1B61a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351b" - + "c3340349190569279751135161d22529dc25add4f6069af05be04cacbda2ace" - + "225403", - "0x5409ed021d9299bf6814279a6a1411a7e866a631", - ) - - -def test_is_valid_signature__data_not_hex_string(): - """Test that giving non-hex-string `data` raises a ValueError.""" - with pytest.raises(ValueError): - is_valid_signature( - Web3.HTTPProvider("http://127.0.0.1:8545"), - "jjj", - "0x1B61a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351b" - + "c3340349190569279751135161d22529dc25add4f6069af05be04cacbda2ace" - + "225403", - "0x5409ed021d9299bf6814279a6a1411a7e866a631", - ) - - -def test_is_valid_signature__signature_not_string(): - """Test that passng a non-string signature raises a TypeError.""" - with pytest.raises(TypeError): - is_valid_signature( - Web3.HTTPProvider("http://127.0.0.1:8545"), - "0x6927e990021d23b1eb7b8789f6a6feaf98fe104bb0cf8259421b79f9a34222b" - + "0", - 123, - "0x5409ed021d9299bf6814279a6a1411a7e866a631", - ) - - -def test_is_valid_signature__signature_not_hex_string(): - """Test that passing a non-hex-string signature raises a ValueError.""" - with pytest.raises(ValueError): - is_valid_signature( - Web3.HTTPProvider("http://127.0.0.1:8545"), - "0x6927e990021d23b1eb7b8789f6a6feaf98fe104bb0cf8259421b79f9a34222b" - + "0", - "jjj", - "0x5409ed021d9299bf6814279a6a1411a7e866a631", - ) - - -def test_is_valid_signature__signer_address_not_string(): - """Test that giving a non-address `signer_address` raises a ValueError.""" - with pytest.raises(TypeError): - is_valid_signature( - Web3.HTTPProvider("http://127.0.0.1:8545"), - "0x6927e990021d23b1eb7b8789f6a6feaf98fe104bb0cf8259421b79f9a34222b" - + "0", - "0x1B61a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351b" - + "c3340349190569279751135161d22529dc25add4f6069af05be04cacbda2ace" - + "225403", - 123, - ) - - -def test_is_valid_signature__signer_address_not_hex_string(): - """Test that giving a non-hex-str `signer_address` raises a ValueError.""" - with pytest.raises(ValueError): - is_valid_signature( - Web3.HTTPProvider("http://127.0.0.1:8545"), - "0x6927e990021d23b1eb7b8789f6a6feaf98fe104bb0cf8259421b79f9a34222b" - + "0", - "0x1B61a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351b" - + "c3340349190569279751135161d22529dc25add4f6069af05be04cacbda2ace" - + "225403", - "jjj", - ) - - -def test_is_valid_signature__signer_address_not_valid_address(): - """Test that giving a non-address for `signer_address` raises an error.""" - with pytest.raises(ValueError): - is_valid_signature( - Web3.HTTPProvider("http://127.0.0.1:8545"), - "0x6927e990021d23b1eb7b8789f6a6feaf98fe104bb0cf8259421b79f9a34222b" - + "0", - "0x1B61a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351b" - + "c3340349190569279751135161d22529dc25add4f6069af05be04cacbda2ace" - + "225403", - "0xff", - ) - - -def test_is_valid_signature__unsupported_sig_types(): - """Test that passing in a sig w/invalid type raises error. - - To induce this error, the last byte of the signature is tweaked from 03 to - ff.""" - try: - is_valid_signature( - Web3.HTTPProvider("http://127.0.0.1:8545"), - "0x6927e990021d23b1eb7b8789f6a6feaf98fe104bb0cf8259421b79f9a34222" - + "b0", - "0x1B61a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351b" - + "c3340349190569279751135161d22529dc25add4f6069af05be04cacbda2ace" - + "225401", - "0x5409ed021d9299bf6814279a6a1411a7e866a631", - ) - except SignatureError as signature_error: - assert ( - signature_error.errorCode - == SignatureErrorCodes.INVALID_LENGTH.value - ) - else: - pytest.fail("Expected exception") - - -def test_sign_hash_to_bytes_and_validate__golden_path(): - """Test the happy path through sign_hash_to_bytes().""" - provider = Web3.HTTPProvider("http://127.0.0.1:8545") - - signing_address = Web3( # pylint: disable=no-member - provider - ).geth.personal.listAccounts()[0] - - order_hash_hex = ( - "0x34decbedc118904df65f379a175bb39ca18209d6ce41d5ed549d54e6e0a95004" - ) - - signature = sign_hash_to_bytes(provider, signing_address, order_hash_hex) - - assert ( - signature - == b"1b117902c86dfb95fe0d1badd983ee166ad259b27acb220174cbb4460d872871137feabdfe76e05924b484789f79af4ee7fa29ec006cedce1bbf369320d034e10b03" # noqa: E501 (line too long) - ) - - is_valid = is_valid_signature( - Web3.HTTPProvider("http://127.0.0.1:8545"), - order_hash_hex, - signature.decode("utf-8"), - signing_address, - ) - - assert is_valid is True diff --git a/python-packages/order_utils/tox.ini b/python-packages/order_utils/tox.ini deleted file mode 100644 index c51a7e14f0..0000000000 --- a/python-packages/order_utils/tox.ini +++ /dev/null @@ -1,26 +0,0 @@ -# tox (https://tox.readthedocs.io/) is a tool for running tests -# in multiple virtualenvs. This configuration file will run the -# test suite on all supported python versions. To use it, "pip install tox" -# and then run "tox" from this directory. - -[tox] -envlist = py37 - -[testenv] -commands = - pip install -e .[dev] - python setup.py test - -[testenv:run_tests_against_test_deployment] -commands = - # install dependencies from real PyPI - pip install eth-abi mypy_extensions web3 pytest - # install package-under-test from test PyPI - pip install --index-url https://test.pypi.org/legacy/ 0x-order-utils - pytest test - -[testenv:run_tests_against_deployment] -setenv = PY_IGNORE_IMPORTMISMATCH = 1 -commands = - pip install 0x-order-utils[dev] - pytest --doctest-modules src test diff --git a/python-packages/parallel b/python-packages/parallel deleted file mode 100755 index 0f374bb950..0000000000 --- a/python-packages/parallel +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python - -"""Run the given command in all packages in parallel. - -Handy for quick verification test runs, but annoying in that all of the output -is interleaved. - -$ ./parallel ./setup.py lint - -This will `cd` into each package, run `./setup.py lint`, then `cd ..`, all in -parallel, in a separate process for each package. The number of processes is -decided by ProcessPoolExecutor. Replace "lint" with any of "test", "clean", -"build_sphinx" (for docs), etc. - -Also consider: - -$ ./parallel pip install -e .[dev] # install all the packages in editable mode - -$ ./parallel pip uninstall $(basename $(pwd)) - ->>>""" - -from concurrent.futures import ProcessPoolExecutor, wait -from os import chdir -from subprocess import CalledProcessError, check_output, STDOUT -from sys import argv - -PACKAGES = [ - "contract_addresses", - "contract_artifacts", - "contract_wrappers", - "json_schemas", - "sra_client", - "order_utils", - "middlewares", -] - -def run_cmd_on_package(package: str): - """cd to the package dir, ./setup.py lint, cd ..""" - chdir(package) - command = f"{' '.join(argv[1:])}" - try: - check_output(command.split(), stderr=STDOUT) - except CalledProcessError as error: - raise RuntimeError( - f"Failure return code received from command `{command}` in package" - + f" {package}, which produced the following output:\n" - + f"{error.output.decode('utf-8')}") from error - finally: - chdir("..") - -with ProcessPoolExecutor() as executor: - for future in executor.map(run_cmd_on_package, PACKAGES): - # iterate over map()'s return value, to resolve the futures. - # but we don't actually care what the return values are, so just `pass`. - # if any exceptions were raised by the underlying task, they'll be - # raised as the iteration encounters them. - pass diff --git a/python-packages/pre_install b/python-packages/pre_install deleted file mode 100755 index 24ed40a633..0000000000 --- a/python-packages/pre_install +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env python - -"""Run setup.py command `pre_install` for all packages that have one.""" - -from os import chdir, path -import subprocess - -from concurrent.futures import ProcessPoolExecutor -from os import chdir -from subprocess import check_call -from sys import argv - -PACKAGES = [ - "contract_wrappers", - "contract_addresses", - "contract_artifacts", - "json_schemas", -] - -def run_cmd_on_package(package: str): - """cd to the package dir, ./setup.py pre_install, cd ..""" - chdir(package) - check_call(f"{path.join('.', 'setup.py')} pre_install".split()) - chdir("..") - -ProcessPoolExecutor().map(run_cmd_on_package, PACKAGES) diff --git a/python-packages/prep_for_staging_doc_publish b/python-packages/prep_for_staging_doc_publish deleted file mode 100755 index 83ac518963..0000000000 --- a/python-packages/prep_for_staging_doc_publish +++ /dev/null @@ -1,5 +0,0 @@ -find ./ \ - -name .discharge.json \ - -exec sed -i \ - -e "s/\(domain.*\)\",$/\1-staging\",/" \ - {} \; diff --git a/python-packages/sra_client/.discharge.json b/python-packages/sra_client/.discharge.json deleted file mode 100644 index ce2e1558c6..0000000000 --- a/python-packages/sra_client/.discharge.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "domain": "0x-sra-client-py", - "build_command": "python setup.py build_sphinx", - "upload_directory": "build/docs/html", - "index_key": "index.html", - "error_key": "index.html", - "cache": 3600, - "aws_profile": "default", - "aws_region": "us-east-1", - "cdn": false, - "dns_configured": true -} diff --git a/python-packages/sra_client/.pylintrc b/python-packages/sra_client/.pylintrc deleted file mode 100644 index ef108c01fc..0000000000 --- a/python-packages/sra_client/.pylintrc +++ /dev/null @@ -1,4 +0,0 @@ -[MESSAGES CONTROL] -disable=C0330,line-too-long,fixme,too-few-public-methods,too-many-ancestors -# C0330 is "bad hanging indent". we use indents per `black`. - diff --git a/python-packages/sra_client/CHANGELOG.md b/python-packages/sra_client/CHANGELOG.md deleted file mode 100644 index 264e7d0b05..0000000000 --- a/python-packages/sra_client/CHANGELOG.md +++ /dev/null @@ -1,25 +0,0 @@ -# Changelog - -## 5.0.0 - TBD - -- Renamed class DefaultApi to RelayerApi, and changed its construction parameters. -- Updated documentation to include schemas for request payloads and responses, and to demonstrate the RelayerApi.get_order_config() method. -- Fixed bug with numeric types not being handled properly for asset data trade info and order config methods. - -## 4.0.0 - 2019-12-03 - -- Migrated from v2 to v3 of the 0x protocol. - -## 3.0.0 - 2019-08-08 - -- Migrated from v4 to v5 of Web3.py. - -## 2.0.0 - 2019-04-30 - -- Moved module `sra_client` into `zero_ex` namespace. -- Fixed regular expression that validates numeric values. Before, validation would fail for all of: maker and taker fees, maker and taker asset amounts, salt, and expiration time. -- Expanded documentation. - -## 1.0.0 - 2018-12-11 - -- Initial release. diff --git a/python-packages/sra_client/README.md b/python-packages/sra_client/README.md deleted file mode 100644 index 50fdb87e1e..0000000000 --- a/python-packages/sra_client/README.md +++ /dev/null @@ -1,368 +0,0 @@ -# 0x-sra-client - -A Python client for interacting with servers conforming to [the Standard Relayer API specification](https://github.com/0xProject/0x-monorepo/tree/development/packages/sra-spec). - -Read the [documentation](http://0x-sra-client-py.s3-website-us-east-1.amazonaws.com/) - -# Schemas - -The [JSON schemas](http://json-schema.org/) for the API payloads and responses can be found in [@0xproject/json-schemas](https://github.com/0xProject/0x-monorepo/tree/development/packages/json-schemas). Examples of each payload and response can be found in the 0x.js library's [test suite](https://github.com/0xProject/0x-monorepo/blob/development/packages/json-schemas/test/schema_test.ts#L1). - -```bash -pip install 0x-json-schemas -``` - -You can easily validate your API's payloads and responses using the [0x-json-schemas](https://github.com/0xProject/0x.js/tree/development/python-packages/json_schemas) package: - -```python -from zero_ex.json_schemas import assert_valid -from zero_ex.order_utils import Order - -order: Order = { - 'makerAddress': "0x0000000000000000000000000000000000000000", - 'takerAddress': "0x0000000000000000000000000000000000000000", - 'feeRecipientAddress': "0x0000000000000000000000000000000000000000", - 'senderAddress': "0x0000000000000000000000000000000000000000", - 'makerAssetAmount': "1000000000000000000", - 'takerAssetAmount': "1000000000000000000", - 'makerFee': "0", - 'takerFee': "0", - 'expirationTimeSeconds': "12345", - 'salt': "12345", - 'makerAssetData': "0x0000000000000000000000000000000000000000", - 'takerAssetData': "0x0000000000000000000000000000000000000000", - 'exchangeAddress': "0x0000000000000000000000000000000000000000", -} - -assert_valid(order, "/orderSchema") -``` - -# Pagination - -Requests that return potentially large collections should respond to the **?page** and **?perPage** parameters. For example: - -```bash -$ curl https://api.example-relayer.com/v2/asset_pairs?page=3&perPage=20 -``` - -Page numbering should be 1-indexed, not 0-indexed. If a query provides an unreasonable (ie. too high) `perPage` value, the response can return a validation error as specified in the [errors section](#section/Errors). If the query specifies a `page` that does not exist (ie. there are not enough `records`), the response should just return an empty `records` array. - -All endpoints that are paginated should return a `total`, `page`, `perPage` and a `records` value in the top level of the collection. The value of `total` should be the total number of records for a given query, whereas `records` should be an array representing the response to the query for that page. `page` and `perPage`, are the same values that were specified in the request. See the note in [miscellaneous](#section/Misc.) about formatting `snake_case` vs. `lowerCamelCase`. - -These requests include the [`/v2/asset_pairs`](#operation/getAssetPairs), [`/v2/orders`](#operation/getOrders), [`/v2/fee_recipients`](#operation/getFeeRecipients) and [`/v2/orderbook`](#operation/getOrderbook) endpoints. - -# Network Id - -All requests should be able to specify a **?networkId** query param for all supported networks. For example: - -```bash -$ curl https://api.example-relayer.com/v2/asset_pairs?networkId=1 -``` - -If the query param is not provided, it should default to **1** (mainnet). - -Networks and their Ids: - -| Network Id | Network Name | -| ---------- | ------------ | -| 1 | Mainnet | -| 42 | Kovan | -| 3 | Ropsten | -| 4 | Rinkeby | - -If a certain network is not supported, the response should **400** as specified in the [error response](#section/Errors) section. For example: - -```json -{ - \"code\": 100, - \"reason\": \"Validation failed\", - \"validationErrors\": [ - { - \"field\": \"networkId\", - \"code\": 1006, - \"reason\": \"Network id 42 is not supported\" - } - ] -} -``` - -# Link Header - -A [Link Header](https://tools.ietf.org/html/rfc5988) can be included in a response to provide clients with more context about paging -For example: - -```bash -Link: ; rel=\"next\", -; rel=\"last\" -``` - -This `Link` response header contains one or more Hypermedia link relations. - -The possible `rel` values are: - -| Name | Description | -| ----- | ------------------------------------------------------------- | -| next | The link relation for the immediate next page of results. | -| last | The link relation for the last page of results. | -| first | The link relation for the first page of results. | -| prev | The link relation for the immediate previous page of results. | - -# Rate Limits - -Rate limit guidance for clients can be optionally returned in the response headers: - -| Header Name | Description | -| --------------------- | ---------------------------------------------------------------------------- | -| X-RateLimit-Limit | The maximum number of requests you're permitted to make per hour. | -| X-RateLimit-Remaining | The number of requests remaining in the current rate limit window. | -| X-RateLimit-Reset | The time at which the current rate limit window resets in UTC epoch seconds. | - -For example: - -```bash -$ curl -i https://api.example-relayer.com/v2/asset_pairs -HTTP/1.1 200 OK -Date: Mon, 20 Oct 2017 12:30:06 GMT -Status: 200 OK -X-RateLimit-Limit: 60 -X-RateLimit-Remaining: 56 -X-RateLimit-Reset: 1372700873 -``` - -When a rate limit is exceeded, a status of **429 Too Many Requests** should be returned. - -# Errors - -Unless the spec defines otherwise, errors to bad requests should respond with HTTP 4xx or status codes. - -## Common error codes - -| Code | Reason | -| ---- | --------------------------------------- | -| 400 | Bad Request – Invalid request format | -| 404 | Not found | -| 429 | Too many requests - Rate limit exceeded | -| 500 | Internal Server Error | -| 501 | Not Implemented | - -## Error reporting format - -For all **400** responses, see the [error response schema](https://github.com/0xProject/0x-monorepo/blob/development/packages/json-schemas/schemas/relayer_api_error_response_schema.ts#L1). - -```json -{ - \"code\": 101, - \"reason\": \"Validation failed\", - \"validationErrors\": [ - { - \"field\": \"maker\", - \"code\": 1002, - \"reason\": \"Invalid address\" - } - ] -} -``` - -General error codes: - -```bash -100 - Validation Failed -101 - Malformed JSON -102 - Order submission disabled -103 - Throttled -``` - -Validation error codes: - -```bash -1000 - Required field -1001 - Incorrect format -1002 - Invalid address -1003 - Address not supported -1004 - Value out of range -1005 - Invalid signature or hash -1006 - Unsupported option -``` - -# Asset Data Encoding - -As we now support multiple [token transfer proxies](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#assetproxy), the identifier of which proxy to use for the token transfer must be encoded, along with the token information. Each proxy in 0x v2 has a unique identifier. If you're using 0x.js there will be helper methods for this [encoding](https://0x.org/docs/tools/0x.js#zeroEx-encodeERC20AssetData) and [decoding](https://0x.org/docs/tools/0x.js#zeroEx-decodeAssetProxyId). - -The identifier for the Proxy uses a similar scheme to [ABI function selectors](https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI#function-selector). - -```js -// ERC20 Proxy ID 0xf47261b0 -bytes4(keccak256('ERC20Token(address)')); -// ERC721 Proxy ID 0x02571792 -bytes4(keccak256('ERC721Token(address,uint256)')); -``` - -Asset data is encoded using [ABI encoding](https://solidity.readthedocs.io/en/develop/abi-spec.html). - -For example, encoding the ERC20 token contract (address: 0x1dc4c1cefef38a777b15aa20260a54e584b16c48) using the ERC20 Transfer Proxy (id: 0xf47261b0) would be: - -```bash -0xf47261b00000000000000000000000001dc4c1cefef38a777b15aa20260a54e584b16c48 -``` - -Encoding the ERC721 token contract (address: `0x371b13d97f4bf77d724e78c16b7dc74099f40e84`), token id (id: `99`, which hex encoded is `0x63`) and the ERC721 Transfer Proxy (id: 0x02571792) would be: - -```bash -0x02571792000000000000000000000000371b13d97f4bf77d724e78c16b7dc74099f40e840000000000000000000000000000000000000000000000000000000000000063 -``` - -For more information see [the Asset Proxy](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#erc20proxy) section of the v2 spec and the [Ethereum ABI Spec](https://solidity.readthedocs.io/en/develop/abi-spec.html). - -# Meta Data in Order Responses - -In v2 of the standard relayer API we added the `metaData` field. It is meant to provide a standard place for relayers to put optional, custom or non-standard fields that may of interest to the consumer of the API. - -A good example of such a field is `remainingTakerAssetAmount`, which is a convenience field that communicates how much of a 0x order is potentially left to be filled. Unlike the other fields in a 0x order, it is not guaranteed to be correct as it is derived from whatever mechanism the implementer (ie. the relayer) is using. While convenient for prototyping and low stakes situations, we recommend validating the value of the field by checking the state of the blockchain yourself. - -# Misc. - -- All requests and responses should be of **application/json** content type -- All token amounts are sent in amounts of the smallest level of precision (base units). (e.g if a token has 18 decimal places, selling 1 token would show up as selling `'1000000000000000000'` units by this API). -- All addresses are sent as lower-case (non-checksummed) Ethereum addresses with the `0x` prefix. -- All parameters are to be written in `lowerCamelCase`. - -This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: - -- API version: 2.0.0 -- Package version: 1.0.0 -- Build package: org.openapitools.codegen.languages.PythonClientCodegen - -## Requirements. - -Python 2.7 and 3.4+ - -## Installation & Usage - -### pip install - -If the python package is hosted on Github, you can install directly from Github - -```sh -pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git -``` - -(you may need to run `pip` with root permission: `sudo pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git`) - -Then import the package: - -```python -import sra_client -``` - -### Setuptools - -Install via [Setuptools](http://pypi.python.org/pypi/setuptools). - -```sh -python setup.py install --user -``` - -(or `sudo python setup.py install` to install the package for all users) - -Then import the package: - -```python -import sra_client -``` - -## Getting Started - -Please follow the [installation procedure](#installation--usage) and then run the following: - -```python -from __future__ import print_function -import time -import sra_client -from sra_client.rest import ApiException -from pprint import pprint - -# create an instance of the API class -api_instance = sra_client.DefaultApi(sra_client.ApiClient(configuration)) -asset_data_a = 0xf47261b04c32345ced77393b3530b1eed0f346429d # str | The assetData value for the first asset in the pair. (optional) -asset_data_b = 0x0257179264389b814a946f3e92105513705ca6b990 # str | The assetData value for the second asset in the pair. (optional) -network_id = 42 # float | The id of the Ethereum network (optional) (default to 1) -page = 3 # float | The number of the page to request in the collection. (optional) (default to 1) -per_page = 10 # float | The number of records to return per page. (optional) (default to 100) - -try: - api_response = api_instance.get_asset_pairs(asset_data_a=asset_data_a, asset_data_b=asset_data_b, network_id=network_id, page=page, per_page=per_page) - pprint(api_response) -except ApiException as e: - print("Exception when calling DefaultApi->get_asset_pairs: %s\n" % e) -``` - -## Contributing - -We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. - -Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. - -### Install Code and Dependencies - -Ensure that you have installed Python >=3.6, Docker, and docker-compose. Then: - -```bash -pip install -e .[dev] -``` - -### Test - -Tests depend on a running instance of 0x-launch-kit-backend, backed by a Ganache node with the 0x contracts deployed in it. For convenience, a docker-compose file is provided that creates this environment. And a shortcut is provided to interface with that file: `./setup.py start_test_relayer` will start those services. With them running, the tests can be run with `./setup.py test`. When you're done with testing, you can `./setup.py stop_test_relayer`. - -### Clean - -`./setup.py clean --all` - -### Lint - -`./setup.py lint` - -### Build Documentation - -`./setup.py build_sphinx` - -### More - -See `./setup.py --help-commands` for more info. - -## Documentation for API Endpoints - -All URIs are relative to _http://localhost_ - -| Class | Method | HTTP request | Description | -| ------------ | --------------------------------------------------------------- | ----------------------------- | ----------- | -| _DefaultApi_ | [**get_asset_pairs**](docs/DefaultApi.md#get_asset_pairs) | **GET** /v2/asset_pairs | -| _DefaultApi_ | [**get_fee_recipients**](docs/DefaultApi.md#get_fee_recipients) | **GET** /v2/fee_recipients | -| _DefaultApi_ | [**get_order**](docs/DefaultApi.md#get_order) | **GET** /v2/order/{orderHash} | -| _DefaultApi_ | [**get_order_config**](docs/DefaultApi.md#get_order_config) | **POST** /v2/order_config | -| _DefaultApi_ | [**get_orderbook**](docs/DefaultApi.md#get_orderbook) | **GET** /v2/orderbook | -| _DefaultApi_ | [**get_orders**](docs/DefaultApi.md#get_orders) | **GET** /v2/orders | -| _DefaultApi_ | [**post_order**](docs/DefaultApi.md#post_order) | **POST** /v2/order | - -## Documentation For Models - -- [OrderSchema](docs/OrderSchema.md) -- [PaginatedCollectionSchema](docs/PaginatedCollectionSchema.md) -- [RelayerApiAssetDataPairsResponseSchema](docs/RelayerApiAssetDataPairsResponseSchema.md) -- [RelayerApiAssetDataTradeInfoSchema](docs/RelayerApiAssetDataTradeInfoSchema.md) -- [RelayerApiErrorResponseSchema](docs/RelayerApiErrorResponseSchema.md) -- [RelayerApiErrorResponseSchemaValidationErrors](docs/RelayerApiErrorResponseSchemaValidationErrors.md) -- [RelayerApiFeeRecipientsResponseSchema](docs/RelayerApiFeeRecipientsResponseSchema.md) -- [RelayerApiOrderConfigPayloadSchema](docs/RelayerApiOrderConfigPayloadSchema.md) -- [RelayerApiOrderConfigResponseSchema](docs/RelayerApiOrderConfigResponseSchema.md) -- [RelayerApiOrderSchema](docs/RelayerApiOrderSchema.md) -- [RelayerApiOrderbookResponseSchema](docs/RelayerApiOrderbookResponseSchema.md) -- [RelayerApiOrdersChannelSubscribePayloadSchema](docs/RelayerApiOrdersChannelSubscribePayloadSchema.md) -- [RelayerApiOrdersChannelSubscribeSchema](docs/RelayerApiOrdersChannelSubscribeSchema.md) -- [RelayerApiOrdersChannelUpdateSchema](docs/RelayerApiOrdersChannelUpdateSchema.md) -- [RelayerApiOrdersResponseSchema](docs/RelayerApiOrdersResponseSchema.md) -- [SignedOrderSchema](docs/SignedOrderSchema.md) - -## Documentation For Authorization - -All endpoints do not require authorization. diff --git a/python-packages/sra_client/doc_template/.gitkeep b/python-packages/sra_client/doc_template/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/sra_client/docs/DefaultApi.md b/python-packages/sra_client/docs/DefaultApi.md deleted file mode 100644 index 6b41414a79..0000000000 --- a/python-packages/sra_client/docs/DefaultApi.md +++ /dev/null @@ -1,397 +0,0 @@ -# sra_client.DefaultApi - -All URIs are relative to _http://localhost_ - -| Method | HTTP request | Description | -| ---------------------------------------------------------- | ----------------------------- | ----------- | -| [**get_asset_pairs**](DefaultApi.md#get_asset_pairs) | **GET** /v2/asset_pairs | -| [**get_fee_recipients**](DefaultApi.md#get_fee_recipients) | **GET** /v2/fee_recipients | -| [**get_order**](DefaultApi.md#get_order) | **GET** /v2/order/{orderHash} | -| [**get_order_config**](DefaultApi.md#get_order_config) | **POST** /v2/order_config | -| [**get_orderbook**](DefaultApi.md#get_orderbook) | **GET** /v2/orderbook | -| [**get_orders**](DefaultApi.md#get_orders) | **GET** /v2/orders | -| [**post_order**](DefaultApi.md#post_order) | **POST** /v2/order | - -# **get_asset_pairs** - -> RelayerApiAssetDataPairsResponseSchema get_asset_pairs(asset_data_a=asset_data_a, asset_data_b=asset_data_b, network_id=network_id, page=page, per_page=per_page) - -Retrieves a list of available asset pairs and the information required to trade them (in any order). Setting only `assetDataA` or `assetDataB` returns pairs filtered by that asset only. - -### Example - -```python -from __future__ import print_function -import time -import sra_client -from sra_client.rest import ApiException -from pprint import pprint - -# create an instance of the API class -api_instance = sra_client.DefaultApi() -asset_data_a = 0xf47261b04c32345ced77393b3530b1eed0f346429d # str | The assetData value for the first asset in the pair. (optional) -asset_data_b = 0x0257179264389b814a946f3e92105513705ca6b990 # str | The assetData value for the second asset in the pair. (optional) -network_id = 42 # float | The id of the Ethereum network (optional) (default to 1) -page = 3 # float | The number of the page to request in the collection. (optional) (default to 1) -per_page = 10 # float | The number of records to return per page. (optional) (default to 100) - -try: - api_response = api_instance.get_asset_pairs(asset_data_a=asset_data_a, asset_data_b=asset_data_b, network_id=network_id, page=page, per_page=per_page) - pprint(api_response) -except ApiException as e: - print("Exception when calling DefaultApi->get_asset_pairs: %s\n" % e) -``` - -### Parameters - -| Name | Type | Description | Notes | -| ---------------- | --------- | ----------------------------------------------------- | -------------------------- | -| **asset_data_a** | **str** | The assetData value for the first asset in the pair. | [optional] | -| **asset_data_b** | **str** | The assetData value for the second asset in the pair. | [optional] | -| **network_id** | **float** | The id of the Ethereum network | [optional][default to 1] | -| **page** | **float** | The number of the page to request in the collection. | [optional][default to 1] | -| **per_page** | **float** | The number of records to return per page. | [optional][default to 100] | - -### Return type - -[**RelayerApiAssetDataPairsResponseSchema**](RelayerApiAssetDataPairsResponseSchema.md) - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_fee_recipients** - -> RelayerApiFeeRecipientsResponseSchema get_fee_recipients(network_id=network_id, page=page, per_page=per_page) - -Retrieves a collection of all fee recipient addresses for a relayer. This endpoint should be [paginated](#section/Pagination). - -### Example - -```python -from __future__ import print_function -import time -import sra_client -from sra_client.rest import ApiException -from pprint import pprint - -# create an instance of the API class -api_instance = sra_client.DefaultApi() -network_id = 42 # float | The id of the Ethereum network (optional) (default to 1) -page = 3 # float | The number of the page to request in the collection. (optional) (default to 1) -per_page = 10 # float | The number of records to return per page. (optional) (default to 100) - -try: - api_response = api_instance.get_fee_recipients(network_id=network_id, page=page, per_page=per_page) - pprint(api_response) -except ApiException as e: - print("Exception when calling DefaultApi->get_fee_recipients: %s\n" % e) -``` - -### Parameters - -| Name | Type | Description | Notes | -| -------------- | --------- | ---------------------------------------------------- | -------------------------- | -| **network_id** | **float** | The id of the Ethereum network | [optional][default to 1] | -| **page** | **float** | The number of the page to request in the collection. | [optional][default to 1] | -| **per_page** | **float** | The number of records to return per page. | [optional][default to 100] | - -### Return type - -[**RelayerApiFeeRecipientsResponseSchema**](RelayerApiFeeRecipientsResponseSchema.md) - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_order** - -> RelayerApiOrderSchema get_order(order_hash, network_id=network_id) - -Retrieves the 0x order with meta info that is associated with the hash. - -### Example - -```python -from __future__ import print_function -import time -import sra_client -from sra_client.rest import ApiException -from pprint import pprint - -# create an instance of the API class -api_instance = sra_client.DefaultApi() -order_hash = 0xd4b103c42d2512eef3fee775e097f044291615d25f5d71e0ac70dbd49d223591 # str | The hash of the desired 0x order. -network_id = 42 # float | The id of the Ethereum network (optional) (default to 1) - -try: - api_response = api_instance.get_order(order_hash, network_id=network_id) - pprint(api_response) -except ApiException as e: - print("Exception when calling DefaultApi->get_order: %s\n" % e) -``` - -### Parameters - -| Name | Type | Description | Notes | -| -------------- | --------- | --------------------------------- | ------------------------ | -| **order_hash** | **str** | The hash of the desired 0x order. | -| **network_id** | **float** | The id of the Ethereum network | [optional][default to 1] | - -### Return type - -[**RelayerApiOrderSchema**](RelayerApiOrderSchema.md) - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_order_config** - -> RelayerApiOrderConfigResponseSchema get_order_config(network_id=network_id, relayer_api_order_config_payload_schema=relayer_api_order_config_payload_schema) - -Relayers have full discretion over the orders that they are willing to host on their orderbooks (e.g what fees they charge, etc...). In order for traders to discover their requirements programmatically, they can send an incomplete order to this endpoint and receive the missing fields, specifc to that order. This gives relayers a large amount of flexibility to tailor fees to unique traders, trading pairs and volume amounts. Submit a partial order and receive information required to complete the order: `senderAddress`, `feeRecipientAddress`, `makerFee`, `takerFee`. - -### Example - -```python -from __future__ import print_function -import time -import sra_client -from sra_client.rest import ApiException -from pprint import pprint - -# create an instance of the API class -api_instance = sra_client.DefaultApi() -network_id = 42 # float | The id of the Ethereum network (optional) (default to 1) -relayer_api_order_config_payload_schema = {"makerAddress":"0x9e56625509c2f60af937f23b7b532600390e8c8b","takerAddress":"0xa2b31dacf30a9c50ca473337c01d8a201ae33e32","makerAssetAmount":"10000000000000000","takerAssetAmount":"1","makerAssetData":"0xf47261b0000000000000000000000000e41d2489571d322189246dafa5ebde1f4699f498","takerAssetData":"0x02571792000000000000000000000000371b13d97f4bf77d724e78c16b7dc74099f40e840000000000000000000000000000000000000000000000000000000000000063","exchangeAddress":"0x12459c951127e0c374ff9105dda097662a027093","expirationTimeSeconds":"1532560590"} # RelayerApiOrderConfigPayloadSchema | The fields of a 0x order the relayer may want to decide what configuration to send back. (optional) - -try: - api_response = api_instance.get_order_config(network_id=network_id, relayer_api_order_config_payload_schema=relayer_api_order_config_payload_schema) - pprint(api_response) -except ApiException as e: - print("Exception when calling DefaultApi->get_order_config: %s\n" % e) -``` - -### Parameters - -| Name | Type | Description | Notes | -| ------------------------------------------- | ------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ------------------------ | -| **network_id** | **float** | The id of the Ethereum network | [optional][default to 1] | -| **relayer_api_order_config_payload_schema** | [**RelayerApiOrderConfigPayloadSchema**](RelayerApiOrderConfigPayloadSchema.md) | The fields of a 0x order the relayer may want to decide what configuration to send back. | [optional] | - -### Return type - -[**RelayerApiOrderConfigResponseSchema**](RelayerApiOrderConfigResponseSchema.md) - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_orderbook** - -> RelayerApiOrderbookResponseSchema get_orderbook(base_asset_data, quote_asset_data, network_id=network_id, page=page, per_page=per_page) - -Retrieves the orderbook for a given asset pair. This endpoint should be [paginated](#section/Pagination). Bids will be sorted in descending order by price, and asks will be sorted in ascending order by price. Within the price sorted orders, the orders are further sorted by _taker fee price_ which is defined as the **takerFee** divided by **takerTokenAmount**. After _taker fee price_, orders are to be sorted by expiration in ascending order. The way pagination works for this endpoint is that the **page** and **perPage** query params apply to both `bids` and `asks` collections, and if `page` \* `perPage` > `total` for a certain collection, the `records` for that collection should just be empty. - -### Example - -```python -from __future__ import print_function -import time -import sra_client -from sra_client.rest import ApiException -from pprint import pprint - -# create an instance of the API class -api_instance = sra_client.DefaultApi() -base_asset_data = 0xf47261b04c32345ced77393b3530b1eed0f346429d # str | assetData (makerAssetData or takerAssetData) designated as the base currency in the [currency pair calculation](https://en.wikipedia.org/wiki/Currency_pair) of price. -quote_asset_data = 0xf47261b04c32345ced77393b3530b1eed0f346429d # str | assetData (makerAssetData or takerAssetData) designated as the quote currency in the currency pair calculation of price (required). -network_id = 42 # float | The id of the Ethereum network (optional) (default to 1) -page = 3 # float | The number of the page to request in the collection. (optional) (default to 1) -per_page = 10 # float | The number of records to return per page. (optional) (default to 100) - -try: - api_response = api_instance.get_orderbook(base_asset_data, quote_asset_data, network_id=network_id, page=page, per_page=per_page) - pprint(api_response) -except ApiException as e: - print("Exception when calling DefaultApi->get_orderbook: %s\n" % e) -``` - -### Parameters - -| Name | Type | Description | Notes | -| -------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | -| **base_asset_data** | **str** | assetData (makerAssetData or takerAssetData) designated as the base currency in the [currency pair calculation](https://en.wikipedia.org/wiki/Currency_pair) of price. | -| **quote_asset_data** | **str** | assetData (makerAssetData or takerAssetData) designated as the quote currency in the currency pair calculation of price (required). | -| **network_id** | **float** | The id of the Ethereum network | [optional][default to 1] | -| **page** | **float** | The number of the page to request in the collection. | [optional][default to 1] | -| **per_page** | **float** | The number of records to return per page. | [optional][default to 100] | - -### Return type - -[**RelayerApiOrderbookResponseSchema**](RelayerApiOrderbookResponseSchema.md) - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_orders** - -> RelayerApiOrdersResponseSchema get_orders(maker_asset_proxy_id=maker_asset_proxy_id, taker_asset_proxy_id=taker_asset_proxy_id, maker_asset_address=maker_asset_address, taker_asset_address=taker_asset_address, exchange_address=exchange_address, sender_address=sender_address, maker_asset_data=maker_asset_data, taker_asset_data=taker_asset_data, trader_asset_data=trader_asset_data, maker_address=maker_address, taker_address=taker_address, trader_address=trader_address, fee_recipient_address=fee_recipient_address, network_id=network_id, page=page, per_page=per_page) - -Retrieves a list of orders given query parameters. This endpoint should be [paginated](#section/Pagination). For querying an entire orderbook snapshot, the [orderbook endpoint](#operation/getOrderbook) is recommended. If both makerAssetData and takerAssetData are specified, returned orders will be sorted by price determined by (takerTokenAmount/makerTokenAmount) in ascending order. By default, orders returned by this endpoint are unsorted. - -### Example - -```python -from __future__ import print_function -import time -import sra_client -from sra_client.rest import ApiException -from pprint import pprint - -# create an instance of the API class -api_instance = sra_client.DefaultApi() -maker_asset_proxy_id = 0xf47261b0 # str | The maker [asset proxy id](https://0x.org/docs/tools/0x.js#types-AssetProxyId) (example: \"0xf47261b0\" for ERC20, \"0x02571792\" for ERC721). (optional) -taker_asset_proxy_id = 0x02571792 # str | The taker asset [asset proxy id](https://0x.org/docs/tools/0x.js#types-AssetProxyId) (example: \"0xf47261b0\" for ERC20, \"0x02571792\" for ERC721). (optional) -maker_asset_address = 0xe41d2489571d322189246dafa5ebde1f4699f498 # str | The contract address for the maker asset. (optional) -taker_asset_address = 0xe41d2489571d322189246dafa5ebde1f4699f498 # str | The contract address for the taker asset. (optional) -exchange_address = 0xe41d2489571d322189246dafa5ebde1f4699f498 # str | Same as exchangeAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) (optional) -sender_address = 0xe41d2489571d322189246dafa5ebde1f4699f498 # str | Same as senderAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) (optional) -maker_asset_data = 0xe41d2489571d322189246dafa5ebde1f4699f498 # str | Same as makerAssetData in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) (optional) -taker_asset_data = 0xe41d2489571d322189246dafa5ebde1f4699f498 # str | Same as takerAssetData in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) (optional) -trader_asset_data = 0xe41d2489571d322189246dafa5ebde1f4699f498 # str | Same as traderAssetData in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) (optional) -maker_address = 0xe41d2489571d322189246dafa5ebde1f4699f498 # str | Same as makerAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) (optional) -taker_address = 0xe41d2489571d322189246dafa5ebde1f4699f498 # str | Same as takerAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) (optional) -trader_address = 0xe41d2489571d322189246dafa5ebde1f4699f498 # str | Same as traderAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) (optional) -fee_recipient_address = 0xe41d2489571d322189246dafa5ebde1f4699f498 # str | Same as feeRecipientAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) (optional) -network_id = 42 # float | The id of the Ethereum network (optional) (default to 1) -page = 3 # float | The number of the page to request in the collection. (optional) (default to 1) -per_page = 10 # float | The number of records to return per page. (optional) (default to 100) - -try: - api_response = api_instance.get_orders(maker_asset_proxy_id=maker_asset_proxy_id, taker_asset_proxy_id=taker_asset_proxy_id, maker_asset_address=maker_asset_address, taker_asset_address=taker_asset_address, exchange_address=exchange_address, sender_address=sender_address, maker_asset_data=maker_asset_data, taker_asset_data=taker_asset_data, trader_asset_data=trader_asset_data, maker_address=maker_address, taker_address=taker_address, trader_address=trader_address, fee_recipient_address=fee_recipient_address, network_id=network_id, page=page, per_page=per_page) - pprint(api_response) -except ApiException as e: - print("Exception when calling DefaultApi->get_orders: %s\n" % e) -``` - -### Parameters - -| Name | Type | Description | Notes | -| ------------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | -| **maker_asset_proxy_id** | **str** | The maker [asset proxy id](https://0x.org/docs/tools/0x.js#types-AssetProxyId) (example: \"0xf47261b0\" for ERC20, \"0x02571792\" for ERC721). | [optional] | -| **taker_asset_proxy_id** | **str** | The taker asset [asset proxy id](https://0x.org/docs/tools/0x.js#types-AssetProxyId) (example: \"0xf47261b0\" for ERC20, \"0x02571792\" for ERC721). | [optional] | -| **maker_asset_address** | **str** | The contract address for the maker asset. | [optional] | -| **taker_asset_address** | **str** | The contract address for the taker asset. | [optional] | -| **exchange_address** | **str** | Same as exchangeAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) | [optional] | -| **sender_address** | **str** | Same as senderAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) | [optional] | -| **maker_asset_data** | **str** | Same as makerAssetData in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) | [optional] | -| **taker_asset_data** | **str** | Same as takerAssetData in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) | [optional] | -| **trader_asset_data** | **str** | Same as traderAssetData in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) | [optional] | -| **maker_address** | **str** | Same as makerAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) | [optional] | -| **taker_address** | **str** | Same as takerAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) | [optional] | -| **trader_address** | **str** | Same as traderAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) | [optional] | -| **fee_recipient_address** | **str** | Same as feeRecipientAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) | [optional] | -| **network_id** | **float** | The id of the Ethereum network | [optional][default to 1] | -| **page** | **float** | The number of the page to request in the collection. | [optional][default to 1] | -| **per_page** | **float** | The number of records to return per page. | [optional][default to 100] | - -### Return type - -[**RelayerApiOrdersResponseSchema**](RelayerApiOrdersResponseSchema.md) - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **post_order** - -> post_order(network_id=network_id, signed_order_schema=signed_order_schema) - -Submit a signed order to the relayer. - -### Example - -```python -from __future__ import print_function -import time -import sra_client -from sra_client.rest import ApiException -from pprint import pprint - -# create an instance of the API class -api_instance = sra_client.DefaultApi() -network_id = 42 # float | The id of the Ethereum network (optional) (default to 1) -signed_order_schema = {"makerAddress":"0x9e56625509c2f60af937f23b7b532600390e8c8b","takerAddress":"0xa2b31dacf30a9c50ca473337c01d8a201ae33e32","feeRecipientAddress":"0xb046140686d052fff581f63f8136cce132e857da","senderAddress":"0xa2b31dacf30a9c50ca473337c01d8a201ae33e32","makerAssetAmount":"10000000000000000","takerAssetAmount":"20000000000000000","makerFee":"100000000000000","takerFee":"200000000000000","expirationTimeSeconds":"1532560590","salt":"1532559225","makerAssetData":"0xf47261b0000000000000000000000000e41d2489571d322189246dafa5ebde1f4699f498","takerAssetData":"0x02571792000000000000000000000000371b13d97f4bf77d724e78c16b7dc74099f40e840000000000000000000000000000000000000000000000000000000000000063","exchangeAddress":"0x12459c951127e0c374ff9105dda097662a027093","signature":"0x012761a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351bc33"} # SignedOrderSchema | A valid signed 0x order based on the schema. (optional) - -try: - api_instance.post_order(network_id=network_id, signed_order_schema=signed_order_schema) -except ApiException as e: - print("Exception when calling DefaultApi->post_order: %s\n" % e) -``` - -### Parameters - -| Name | Type | Description | Notes | -| ----------------------- | --------------------------------------------- | -------------------------------------------- | ------------------------ | -| **network_id** | **float** | The id of the Ethereum network | [optional][default to 1] | -| **signed_order_schema** | [**SignedOrderSchema**](SignedOrderSchema.md) | A valid signed 0x order based on the schema. | [optional] | - -### Return type - -void (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/OrderSchema.md b/python-packages/sra_client/docs/OrderSchema.md deleted file mode 100644 index 5378c95f44..0000000000 --- a/python-packages/sra_client/docs/OrderSchema.md +++ /dev/null @@ -1,21 +0,0 @@ -# OrderSchema - -## Properties - -| Name | Type | Description | Notes | -| --------------------------- | ------- | ----------- | ----- | -| **maker_address** | **str** | | -| **taker_address** | **str** | | -| **maker_fee** | **str** | | -| **taker_fee** | **str** | | -| **sender_address** | **str** | | -| **maker_asset_amount** | **str** | | -| **taker_asset_amount** | **str** | | -| **maker_asset_data** | **str** | | -| **taker_asset_data** | **str** | | -| **salt** | **str** | | -| **exchange_address** | **str** | | -| **fee_recipient_address** | **str** | | -| **expiration_time_seconds** | **str** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/PaginatedCollectionSchema.md b/python-packages/sra_client/docs/PaginatedCollectionSchema.md deleted file mode 100644 index 969cbf7b59..0000000000 --- a/python-packages/sra_client/docs/PaginatedCollectionSchema.md +++ /dev/null @@ -1,11 +0,0 @@ -# PaginatedCollectionSchema - -## Properties - -| Name | Type | Description | Notes | -| ------------ | --------- | ----------- | ----- | -| **total** | **float** | | -| **per_page** | **float** | | -| **page** | **float** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/RelayerApiAssetDataPairsResponseSchema.md b/python-packages/sra_client/docs/RelayerApiAssetDataPairsResponseSchema.md deleted file mode 100644 index 0e87e8dc0f..0000000000 --- a/python-packages/sra_client/docs/RelayerApiAssetDataPairsResponseSchema.md +++ /dev/null @@ -1,9 +0,0 @@ -# RelayerApiAssetDataPairsResponseSchema - -## Properties - -| Name | Type | Description | Notes | -| ----------- | ---------------- | ----------- | ----- | -| **records** | **list[object]** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/RelayerApiAssetDataTradeInfoSchema.md b/python-packages/sra_client/docs/RelayerApiAssetDataTradeInfoSchema.md deleted file mode 100644 index 15de4e4ad8..0000000000 --- a/python-packages/sra_client/docs/RelayerApiAssetDataTradeInfoSchema.md +++ /dev/null @@ -1,12 +0,0 @@ -# RelayerApiAssetDataTradeInfoSchema - -## Properties - -| Name | Type | Description | Notes | -| -------------- | --------- | ----------- | ---------- | -| **asset_data** | **str** | | -| **min_amount** | **str** | | [optional] | -| **max_amount** | **str** | | [optional] | -| **precision** | **float** | | [optional] | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/RelayerApiErrorResponseSchema.md b/python-packages/sra_client/docs/RelayerApiErrorResponseSchema.md deleted file mode 100644 index 11e3b32a93..0000000000 --- a/python-packages/sra_client/docs/RelayerApiErrorResponseSchema.md +++ /dev/null @@ -1,11 +0,0 @@ -# RelayerApiErrorResponseSchema - -## Properties - -| Name | Type | Description | Notes | -| --------------------- | ----------------------------------------------------------------------------------------------------------- | ----------- | ---------- | -| **code** | **int** | | -| **reason** | **str** | | -| **validation_errors** | [**list[RelayerApiErrorResponseSchemaValidationErrors]**](RelayerApiErrorResponseSchemaValidationErrors.md) | | [optional] | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/RelayerApiErrorResponseSchemaValidationErrors.md b/python-packages/sra_client/docs/RelayerApiErrorResponseSchemaValidationErrors.md deleted file mode 100644 index 2147b3822a..0000000000 --- a/python-packages/sra_client/docs/RelayerApiErrorResponseSchemaValidationErrors.md +++ /dev/null @@ -1,11 +0,0 @@ -# RelayerApiErrorResponseSchemaValidationErrors - -## Properties - -| Name | Type | Description | Notes | -| ---------- | ------- | ----------- | ----- | -| **field** | **str** | | -| **code** | **int** | | -| **reason** | **str** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/RelayerApiFeeRecipientsResponseSchema.md b/python-packages/sra_client/docs/RelayerApiFeeRecipientsResponseSchema.md deleted file mode 100644 index f12582a812..0000000000 --- a/python-packages/sra_client/docs/RelayerApiFeeRecipientsResponseSchema.md +++ /dev/null @@ -1,9 +0,0 @@ -# RelayerApiFeeRecipientsResponseSchema - -## Properties - -| Name | Type | Description | Notes | -| ----------- | ------------- | ----------- | ----- | -| **records** | **list[str]** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/RelayerApiOrderConfigPayloadSchema.md b/python-packages/sra_client/docs/RelayerApiOrderConfigPayloadSchema.md deleted file mode 100644 index ee0800066d..0000000000 --- a/python-packages/sra_client/docs/RelayerApiOrderConfigPayloadSchema.md +++ /dev/null @@ -1,16 +0,0 @@ -# RelayerApiOrderConfigPayloadSchema - -## Properties - -| Name | Type | Description | Notes | -| --------------------------- | ------- | ----------- | ----- | -| **maker_address** | **str** | | -| **taker_address** | **str** | | -| **maker_asset_amount** | **str** | | -| **taker_asset_amount** | **str** | | -| **maker_asset_data** | **str** | | -| **taker_asset_data** | **str** | | -| **exchange_address** | **str** | | -| **expiration_time_seconds** | **str** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/RelayerApiOrderConfigResponseSchema.md b/python-packages/sra_client/docs/RelayerApiOrderConfigResponseSchema.md deleted file mode 100644 index 2ebafdf472..0000000000 --- a/python-packages/sra_client/docs/RelayerApiOrderConfigResponseSchema.md +++ /dev/null @@ -1,12 +0,0 @@ -# RelayerApiOrderConfigResponseSchema - -## Properties - -| Name | Type | Description | Notes | -| ------------------------- | ------- | ----------- | ----- | -| **maker_fee** | **str** | | -| **taker_fee** | **str** | | -| **fee_recipient_address** | **str** | | -| **sender_address** | **str** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/RelayerApiOrderSchema.md b/python-packages/sra_client/docs/RelayerApiOrderSchema.md deleted file mode 100644 index bbdffe2f45..0000000000 --- a/python-packages/sra_client/docs/RelayerApiOrderSchema.md +++ /dev/null @@ -1,10 +0,0 @@ -# RelayerApiOrderSchema - -## Properties - -| Name | Type | Description | Notes | -| ------------- | --------------------------------- | ----------- | ----- | -| **order** | [**OrderSchema**](OrderSchema.md) | | -| **meta_data** | [**object**](.md) | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/RelayerApiOrderbookResponseSchema.md b/python-packages/sra_client/docs/RelayerApiOrderbookResponseSchema.md deleted file mode 100644 index 6fb7c88ff2..0000000000 --- a/python-packages/sra_client/docs/RelayerApiOrderbookResponseSchema.md +++ /dev/null @@ -1,10 +0,0 @@ -# RelayerApiOrderbookResponseSchema - -## Properties - -| Name | Type | Description | Notes | -| -------- | ----------------------------------------------------------------------- | ----------- | ----- | -| **bids** | [**RelayerApiOrdersResponseSchema**](RelayerApiOrdersResponseSchema.md) | | -| **asks** | [**RelayerApiOrdersResponseSchema**](RelayerApiOrdersResponseSchema.md) | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/RelayerApiOrdersChannelSubscribePayloadSchema.md b/python-packages/sra_client/docs/RelayerApiOrdersChannelSubscribePayloadSchema.md deleted file mode 100644 index 97c2cbc21f..0000000000 --- a/python-packages/sra_client/docs/RelayerApiOrdersChannelSubscribePayloadSchema.md +++ /dev/null @@ -1,16 +0,0 @@ -# RelayerApiOrdersChannelSubscribePayloadSchema - -## Properties - -| Name | Type | Description | Notes | -| ------------------------ | --------- | ----------- | ---------- | -| **maker_asset_proxy_id** | **str** | | [optional] | -| **taker_asset_proxy_id** | **str** | | [optional] | -| **network_id** | **float** | | [optional] | -| **maker_asset_address** | **str** | | [optional] | -| **taker_asset_address** | **str** | | [optional] | -| **maker_asset_data** | **str** | | [optional] | -| **taker_asset_data** | **str** | | [optional] | -| **trader_asset_data** | **str** | | [optional] | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/RelayerApiOrdersChannelSubscribeSchema.md b/python-packages/sra_client/docs/RelayerApiOrdersChannelSubscribeSchema.md deleted file mode 100644 index 5e1c96c24b..0000000000 --- a/python-packages/sra_client/docs/RelayerApiOrdersChannelSubscribeSchema.md +++ /dev/null @@ -1,12 +0,0 @@ -# RelayerApiOrdersChannelSubscribeSchema - -## Properties - -| Name | Type | Description | Notes | -| -------------- | ----------------------------------------------------------------------------------------------------- | ----------- | ---------- | -| **type** | **str** | | -| **channel** | **str** | | -| **request_id** | **str** | | -| **payload** | [**RelayerApiOrdersChannelSubscribePayloadSchema**](RelayerApiOrdersChannelSubscribePayloadSchema.md) | | [optional] | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/RelayerApiOrdersChannelUpdateSchema.md b/python-packages/sra_client/docs/RelayerApiOrdersChannelUpdateSchema.md deleted file mode 100644 index 8d763367a0..0000000000 --- a/python-packages/sra_client/docs/RelayerApiOrdersChannelUpdateSchema.md +++ /dev/null @@ -1,12 +0,0 @@ -# RelayerApiOrdersChannelUpdateSchema - -## Properties - -| Name | Type | Description | Notes | -| -------------- | ----------------------------------------------------------- | ----------- | ---------- | -| **type** | **str** | | -| **channel** | **str** | | -| **request_id** | **str** | | -| **payload** | [**list[RelayerApiOrderSchema]**](RelayerApiOrderSchema.md) | | [optional] | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/RelayerApiOrdersResponseSchema.md b/python-packages/sra_client/docs/RelayerApiOrdersResponseSchema.md deleted file mode 100644 index 8989d346be..0000000000 --- a/python-packages/sra_client/docs/RelayerApiOrdersResponseSchema.md +++ /dev/null @@ -1,9 +0,0 @@ -# RelayerApiOrdersResponseSchema - -## Properties - -| Name | Type | Description | Notes | -| ----------- | ----------------------------------------------------------- | ----------- | ----- | -| **records** | [**list[RelayerApiOrderSchema]**](RelayerApiOrderSchema.md) | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/SignedOrderSchema.md b/python-packages/sra_client/docs/SignedOrderSchema.md deleted file mode 100644 index 4c753e6cc7..0000000000 --- a/python-packages/sra_client/docs/SignedOrderSchema.md +++ /dev/null @@ -1,9 +0,0 @@ -# SignedOrderSchema - -## Properties - -| Name | Type | Description | Notes | -| ------------- | ------- | ----------- | ----- | -| **signature** | **str** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/generate.sh b/python-packages/sra_client/generate.sh deleted file mode 100755 index 91967dee38..0000000000 --- a/python-packages/sra_client/generate.sh +++ /dev/null @@ -1,26 +0,0 @@ -# This file provided not so much to be run but rather more for posterity, as a -# record of how this generated code was produced. - -GENERATOR_JAR=http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/3.3.4/openapi-generator-cli-3.3.4.jar -GENERATOR_JAR_BASENAME=$(basename $GENERATOR_JAR) - -if [ -f $GENERATOR_JAR_BASENAME ]; then - if [ "$(openssl dgst -sha256 $GENERATOR_JAR_BASENAME)" \ - != "SHA256($GENERATOR_JAR_BASENAME)= 24cb04939110cffcdd7062d2f50c6f61159dc3e0ca3b8aecbae6ade53ad3dc8c" \ - ]; then - rm $GENERATOR_JAR_BASENAME - fi -fi - -if [ ! -f $GENERATOR_JAR_BASENAME ]; then - wget $GENERATOR_JAR -fi - -PYTHON_POST_PROCESS_FILE="black --line-length 79" \ - java -jar openapi-generator-cli-3.3.4.jar \ - generate \ - --input-spec http://unpkg.com/@0x/sra-spec@1.0.11/lib/api.json \ - --output . \ - --generator-name python \ - --config openapi-generator-cli-config.json \ - --enable-post-process-file diff --git a/python-packages/sra_client/openapi-generator-cli-config.json b/python-packages/sra_client/openapi-generator-cli-config.json deleted file mode 100644 index cc619e4653..0000000000 --- a/python-packages/sra_client/openapi-generator-cli-config.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "packageName": "sra_client", - "projectName": "0x-sra-client" -} diff --git a/python-packages/sra_client/requirements.txt b/python-packages/sra_client/requirements.txt deleted file mode 100644 index bafdc07532..0000000000 --- a/python-packages/sra_client/requirements.txt +++ /dev/null @@ -1,5 +0,0 @@ -certifi >= 14.05.14 -six >= 1.10 -python_dateutil >= 2.5.3 -setuptools >= 21.0.0 -urllib3 >= 1.15.1 diff --git a/python-packages/sra_client/setup.py b/python-packages/sra_client/setup.py deleted file mode 100755 index 36b63eb074..0000000000 --- a/python-packages/sra_client/setup.py +++ /dev/null @@ -1,239 +0,0 @@ -#!/usr/bin/env python -# coding: utf-8 - -"""setuptools module for sra_client package.""" - -# pylint: disable=import-outside-toplevel -# we import things outside of top-level because 3rd party libs may not yet be -# installed when you invoke this script - -import subprocess # nosec -import distutils.command.build_py -from distutils.command.clean import clean -from shutil import rmtree -from sys import exit # pylint: disable=redefined-builtin -from urllib.request import urlopen -from urllib.error import URLError - -from setuptools import setup, find_packages # noqa: H301 -from setuptools.command.test import test as TestCommand - -NAME = "0x-sra-client" -VERSION = "4.0.0" -# To install the library, run the following -# -# python setup.py install -# -# prerequisite: setuptools -# http://pypi.python.org/pypi/setuptools - -with open("README.md", "r") as file_handle: - README_MD = file_handle.read() - -REQUIRES = ["urllib3 >= 1.15", "six >= 1.10", "certifi", "python-dateutil"] - - -class CleanCommandExtension(clean): - """Custom command to do custom cleanup.""" - - def run(self): - """Run the regular clean, followed by our custom commands.""" - super().run() - rmtree("__pycache__", ignore_errors=True) - rmtree(".mypy_cache", ignore_errors=True) - rmtree(".tox", ignore_errors=True) - rmtree(".pytest_cache", ignore_errors=True) - rmtree("src/0x_sra_client.egg-info", ignore_errors=True) - rmtree("build", ignore_errors=True) - rmtree("dist", ignore_errors=True) - subprocess.check_call( # nosec - ("docker-compose -f test/relayer/docker-compose.yml down").split() - ) - subprocess.check_call( # nosec - ("docker-compose -f test/relayer/docker-compose.yml rm").split() - ) - - -class TestCommandExtension(TestCommand): - """Run pytest tests.""" - - def run_tests(self): - """Invoke pytest.""" - import pytest - - exit(pytest.main(["--doctest-modules", "-rapP"])) - # show short test summary at end ^ - # above call commented out due to a problem with launch kit, - # documented at - # https://github.com/0xProject/0x-launch-kit-backend/issues/73 - - -class TestPublishCommand(distutils.command.build_py.build_py): - """Custom command to publish to test.pypi.org.""" - - description = ( - "Publish dist/* to test.pypi.org. Run sdist & bdist_wheel first." - ) - - def run(self): - """Run twine to upload to test.pypi.org.""" - subprocess.check_call( # nosec - ( - "twine upload --repository-url https://test.pypi.org/legacy/" - + " --verbose dist/*" - ).split() - ) - - -class StartTestRelayerCommand(distutils.command.build_py.build_py): - """Custom command to boot up a local 0x-launch-kit-backend in docker.""" - - description = "Run launch-kit daemon to support tests." - - def run(self): - """Run `docker-compose up`.""" - subprocess.call( # nosec - ("docker-compose -f test/relayer/docker-compose.yml pull").split() - ) - subprocess.call( # nosec - ("docker-compose -f test/relayer/docker-compose.yml up -d").split() - ) - launch_kit_ready = False - print( - "Waiting for Launch Kit Backend to start accepting connections...", - flush=True, - ) - while not launch_kit_ready: - try: - launch_kit_ready = ( - urlopen( # nosec - "http://localhost:3000/v3/asset_pairs" - ).getcode() - == 200 - ) - except URLError: - continue - print("done") - - -class StopTestRelayerCommand(distutils.command.build_py.build_py): - """Custom command to tear down the 0x-launch-kit-backend test relayer.""" - - description = "Tear down launch-kit daemon." - - def run(self): - """Run `docker-compose down`.""" - subprocess.call( # nosec - ("docker-compose -f test/relayer/docker-compose.yml down").split() - ) - - -class LintCommand(distutils.command.build_py.build_py): - """Custom setuptools command class for running linters.""" - - description = "Run linters" - - def run(self): - """Run linter shell commands.""" - lint_targets = "test src/zero_ex/sra_client/__init__.py setup.py" - lint_commands = [ - # formatter: - ( - f"black --line-length 79 --check --diff test {lint_targets}" - ).split(), - # style guide checker (formerly pep8): - f"pycodestyle {lint_targets}".split(), - # docstring style checker: - f"pydocstyle {lint_targets}".split(), - # static type checker: - f"bandit -r {lint_targets}".split(), - # general linter: - f"pylint {lint_targets}".split(), - # pylint takes relatively long to run, so it runs last, to enable - # fast failures. - ] - - for lint_command in lint_commands: - print( - "Running lint command `", " ".join(lint_command).strip(), "`" - ) - subprocess.check_call(lint_command) # nosec - - -class PublishCommand(distutils.command.build_py.build_py): - """Custom command to publish to pypi.org.""" - - description = "Publish dist/* to pypi.org. Run sdist & bdist_wheel first." - - def run(self): - """Run twine to upload to pypi.org.""" - subprocess.check_call("twine upload dist/*".split()) # nosec - - -class PublishDocsCommand(distutils.command.build_py.build_py): - """Custom command to publish docs to S3.""" - - description = ( - "Publish docs to " - + "http://0x-sra-client-py.s3-website-us-east-1.amazonaws.com/" - ) - - def run(self): - """Run npm package `discharge` to build & upload docs.""" - subprocess.check_call("discharge deploy".split()) # nosec - - -setup( - name=NAME, - version=VERSION, - description="Standard Relayer REST API Client", - author="F. Eugene Aumson", - author_email="feuGeneA@users.noreply.github.com", - url=( - "https://github.com/0xproject/0x-monorepo/tree/development" - "/python-packages/sra_client" - ), - keywords=["OpenAPI", "OpenAPI-Generator", "Standard Relayer REST API"], - install_requires=REQUIRES, - namespace_packages=["zero_ex"], - packages=find_packages("src"), - package_dir={"": "src"}, - include_package_data=True, - long_description=README_MD, - long_description_content_type="text/markdown", - cmdclass={ - "clean": CleanCommandExtension, - "test_publish": TestPublishCommand, - "publish": PublishCommand, - "start_test_relayer": StartTestRelayerCommand, - "stop_test_relayer": StopTestRelayerCommand, - "lint": LintCommand, - "publish_docs": PublishDocsCommand, - "test": TestCommandExtension, - }, - extras_require={ - "dev": [ - "0x-contract-artifacts", - "0x-contract-addresses", - "0x-contract-wrappers", - "0x-order-utils", - "web3", - "bandit", - "black", - "coverage", - "coveralls", - "pycodestyle", - "pydocstyle", - "pylint", - "pytest", - "sphinx", - ] - }, - command_options={ - "build_sphinx": { - "source_dir": ("setup.py", "src"), - "build_dir": ("setup.py", "build/docs"), - "warning_is_error": ("setup.py", "true"), - } - }, -) diff --git a/python-packages/sra_client/src/conf.py b/python-packages/sra_client/src/conf.py deleted file mode 100644 index deedfcf996..0000000000 --- a/python-packages/sra_client/src/conf.py +++ /dev/null @@ -1,54 +0,0 @@ -"""Configuration file for the Sphinx documentation builder.""" - -# Reference: http://www.sphinx-doc.org/en/master/config - -from typing import List -import pkg_resources - - -# pylint: disable=invalid-name -# because these variables are not named in upper case, as globals should be. - -project = "0x-sra-client" -# pylint: disable=redefined-builtin -copyright = "2018, ZeroEx, Intl." -author = "F. Eugene Aumson" -version = pkg_resources.get_distribution("0x-sra-client").version -release = "" # The full version, including alpha/beta/rc tags - -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.doctest", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.viewcode", -] - -templates_path = ["doc_templates"] - -source_suffix = ".rst" -# eg: source_suffix = [".rst", ".md"] - -master_doc = "index" # The master toctree document. - -language = None - -exclude_patterns: List[str] = [] - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = None - -html_theme = "alabaster" - -html_static_path = ["doc_static"] -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". - -# Output file base name for HTML help builder. -htmlhelp_basename = "sraclientpydoc" - -# -- Extension configuration: - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = {"https://docs.python.org/": None} diff --git a/python-packages/sra_client/src/doc_static/.gitkeep b/python-packages/sra_client/src/doc_static/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python-packages/sra_client/src/index.rst b/python-packages/sra_client/src/index.rst deleted file mode 100644 index d05a4a98f2..0000000000 --- a/python-packages/sra_client/src/index.rst +++ /dev/null @@ -1,68 +0,0 @@ -.. source for the sphinx-generated build/docs/web/index.html - -Python zero_ex.sra_client -========================= - -.. toctree:: - :maxdepth: 2 - :caption: Contents: - -.. automodule:: zero_ex.sra_client - -zero_ex.sra_client.RelayerApi -============================= - -.. autoclass:: zero_ex.sra_client.RelayerApi - :members: - -zero_ex.sra_client.models -========================= - -.. autoclass:: zero_ex.sra_client.models.relayer_api_asset_data_pairs_response_schema.RelayerApiAssetDataPairsResponseSchema - :members: - -.. autoclass:: zero_ex.sra_client.models.relayer_api_asset_data_trade_info_schema.RelayerApiAssetDataTradeInfoSchema - :members: - -.. autoclass:: zero_ex.sra_client.models.relayer_api_error_response_schema.RelayerApiErrorResponseSchema - :members: - -.. autoclass:: zero_ex.sra_client.models.relayer_api_error_response_schema_validation_errors.RelayerApiErrorResponseSchemaValidationErrors - :members: - -.. autoclass:: zero_ex.sra_client.models.relayer_api_fee_recipients_response_schema.RelayerApiFeeRecipientsResponseSchema - :members: - -.. autoclass:: zero_ex.sra_client.models.relayer_api_orderbook_response_schema.RelayerApiOrderbookResponseSchema - :members: - -.. autoclass:: zero_ex.sra_client.models.relayer_api_order_config_payload_schema.RelayerApiOrderConfigPayloadSchema - :members: - -.. autoclass:: zero_ex.sra_client.models.relayer_api_order_config_response_schema.RelayerApiOrderConfigResponseSchema - :members: - -.. autoclass:: zero_ex.sra_client.models.relayer_api_orders_channel_subscribe_payload_schema.RelayerApiOrdersChannelSubscribePayloadSchema - :members: - -.. autoclass:: zero_ex.sra_client.models.relayer_api_orders_channel_subscribe_schema.RelayerApiOrdersChannelSubscribeSchema - :members: - -.. autoclass:: zero_ex.sra_client.models.relayer_api_orders_channel_update_schema.RelayerApiOrdersChannelUpdateSchema - :members: - -.. autoclass:: zero_ex.sra_client.models.relayer_api_order_schema.RelayerApiOrderSchema - :members: - -.. autoclass:: zero_ex.sra_client.models.relayer_api_orders_response_schema.RelayerApiOrdersResponseSchema - :members: - -.. autoclass:: zero_ex.sra_client.models.signed_order_schema.SignedOrderSchema - :members: - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` diff --git a/python-packages/sra_client/src/zero_ex/__init__.py b/python-packages/sra_client/src/zero_ex/__init__.py deleted file mode 100644 index 3fe1300cfb..0000000000 --- a/python-packages/sra_client/src/zero_ex/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -"""0x Python API.""" -__import__("pkg_resources").declare_namespace(__name__) # type: ignore diff --git a/python-packages/sra_client/src/zero_ex/sra_client/__init__.py b/python-packages/sra_client/src/zero_ex/sra_client/__init__.py deleted file mode 100644 index d65f723dec..0000000000 --- a/python-packages/sra_client/src/zero_ex/sra_client/__init__.py +++ /dev/null @@ -1,479 +0,0 @@ -# coding: utf-8 - -# flake8: noqa - -r"""A Python client for interacting with SRA-compatible Relayers. - -0x Protocol is an open standard. Many Relayers opt to implementing a set of -`Standard Relayer API (SRA) -`_ endpoints, to make it -easier for anyone to source liquidity that conforms to the 0x order format. -Here, we will show you how you can use the `0x-sra-client`:code: module to -interact with 0x relayers that implement the SRA specification. - -Setup ------ - -Install the package with pip:: - - pip install 0x-sra-client - -To interact with a 0x Relayer, you need the HTTP endpoint of the Relayer you'd -like to connect to (eg https://api.radarrelay.com/0x/v3). - -For testing one can use the `0x-launch-kit-backend -`_ to host -orders locally. The examples below assume that this server is running locally -and listening on port 3000, so the Relayer URL they use is -`http://localhost:3000`:code:. - -By default, Launch Kit will connect to Kovan via Infura. However, it can be -configured to connect to any JSON-RPC endpoint, on any network. The examples -below assume that Launch Kit is connected to a Ganache development network -accessible at `http://localhost:8545`:code:. - -These examples are automatically verified by spinning up docker images -`0xorg/ganache-cli`, `0xorg/mesh`, and `0xorg/launch-kit-backend`. You can -replicate this environment yourself by using `this docker-compose.yml file -`_. -(Note: This will only work on Linux, because it uses `network_mode: -"host"`:code:, which only works on Linux.) - -Configure and create an API client instance -------------------------------------------- - ->>> from zero_ex.sra_client import RelayerApi ->>> relayer = RelayerApi("http://localhost:3000") - -Preparing to trade ------------------- - -Making and taking orders induces the SRA endpoint to deal with the Ethereum -network. Before we can start trading, we need to do a few things with the -network directly. - -To start, connect to the Ethereum network: - ->>> from web3 import HTTPProvider, Web3 ->>> eth_node = HTTPProvider("http://localhost:8545") - -For our Maker role, we'll just use the first address available in the node: - ->>> maker_address = Web3(eth_node).eth.accounts[0] - -The 0x Ganache snapshot loaded into our eth_node has a pre-loaded ZRX balance -for this account, so the example orders below have the maker trading away ZRX. -Before such an order can be valid, though, the maker must give the 0x contracts -permission to trade their ZRX tokens: - ->>> from zero_ex.contract_addresses import chain_to_addresses, ChainId ->>> contract_addresses = chain_to_addresses(ChainId(Web3(eth_node).eth.chainId)) ->>> ->>> from zero_ex.contract_artifacts import abi_by_name ->>> zrx_token_contract = Web3(eth_node).eth.contract( -... address=Web3.toChecksumAddress(contract_addresses.zrx_token), -... abi=abi_by_name("ZRXToken") -... ) ->>> ->>> zrx_token_contract.functions.approve( -... Web3.toChecksumAddress(contract_addresses.erc20_proxy), -... 1000000000000000000 -... ).transact( -... {"from": Web3.toChecksumAddress(maker_address)} -... ) -HexBytes('0x...') - -Post Order ------------ - -Post an order for our Maker to trade ZRX for WETH: - ->>> from zero_ex.contract_wrappers.exchange.types import Order ->>> from zero_ex.contract_wrappers.order_conversions import order_to_jsdict ->>> from zero_ex.order_utils import ( -... asset_data_utils, -... sign_hash) ->>> import random ->>> from datetime import datetime, timedelta ->>> order = Order( -... makerAddress=maker_address, -... takerAddress="0x0000000000000000000000000000000000000000", -... senderAddress="0x0000000000000000000000000000000000000000", -... exchangeAddress=contract_addresses.exchange, -... feeRecipientAddress="0x0000000000000000000000000000000000000000", -... makerAssetData=asset_data_utils.encode_erc20( -... contract_addresses.zrx_token -... ), -... makerFeeAssetData=asset_data_utils.encode_erc20('0x'+'00'*20), -... takerAssetData=asset_data_utils.encode_erc20( -... contract_addresses.ether_token -... ), -... takerFeeAssetData=asset_data_utils.encode_erc20('0x'+'00'*20), -... salt=random.randint(1, 100000000000000000), -... makerFee=0, -... takerFee=0, -... makerAssetAmount=2, -... takerAssetAmount=2, -... expirationTimeSeconds=round( -... (datetime.utcnow() + timedelta(days=1)).timestamp() -... ) -... ) - -Before hashing and submitting our order, it's a good idea to ask the relayer -how to configure the order, so that the submission won't be rejected: - ->>> order_config = relayer.get_order_config( -... relayer_api_order_config_payload_schema={ -... "makerAddress": order["makerAddress"], -... "takerAddress": order["takerAddress"], -... "makerAssetAmount": order["makerAssetAmount"], -... "takerAssetAmount": order["takerAssetAmount"], -... "expirationTimeSeconds": order["expirationTimeSeconds"], -... "makerAssetData": '0x' + order["makerAssetData"].hex(), -... "takerAssetData": '0x' + order["takerAssetData"].hex(), -... "exchangeAddress": contract_addresses.exchange, -... } -... ) ->>> order_config -{'fee_recipient_address': '0x0000000000000000000000000000000000000001', - 'maker_fee': '0', - 'sender_address': '0x0000000000000000000000000000000000000000', - 'taker_fee': '0'} - -Now we'll apply that configuration to our order before proceeding: - ->>> order["feeRecipientAddress"] = order_config.fee_recipient_address ->>> order["makerFee"] = int(order_config.maker_fee) ->>> order["takerFee"] = int(order_config.taker_fee) ->>> order["senderAddress"] = order_config.sender_address - ->>> from zero_ex.order_utils import generate_order_hash_hex ->>> order_hash_hex = generate_order_hash_hex( -... order, contract_addresses.exchange, Web3(eth_node).eth.chainId -... ) - ->>> relayer.post_order_with_http_info( -... signed_order_schema=order_to_jsdict( -... order=order, -... exchange_address=contract_addresses.exchange, -... signature=sign_hash( -... eth_node, Web3.toChecksumAddress(maker_address), order_hash_hex -... ), -... chain_id=Web3(eth_node).eth.chainId, -... ) -... )[1] -200 - -Get Order ---------- - -(But first sleep for a moment, to give the test relayer a chance to start up. - ->>> from time import sleep ->>> sleep(0.2) - -This is necessary for automated verification of these examples.) - -Retrieve the order we just posted: - ->>> relayer.get_order("0x" + order_hash_hex) -{'meta_data': {'orderHash': '0x...', - 'remainingFillableTakerAssetAmount': '2'}, - 'order': {'chainId': 1337, - 'exchangeAddress': '0x...', - 'expirationTimeSeconds': '...', - 'feeRecipientAddress': '0x0000000000000000000000000000000000000001', - 'makerAddress': '0x...', - 'makerAssetAmount': '2', - 'makerAssetData': '0xf47261b0000000000000000000000000...', - 'makerFee': '0', - 'makerFeeAssetData': '0xf47261b0000000000000000000000000...', - 'salt': '...', - 'senderAddress': '0x0000000000000000000000000000000000000000', - 'signature': '0x...', - 'takerAddress': '0x0000000000000000000000000000000000000000', - 'takerAssetAmount': '2', - 'takerAssetData': '0xf47261b0000000000000000000000000...', - 'takerFee': '0', - 'takerFeeAssetData': '0xf47261b0000000000000000000000000...'}} - -Get Orders ------------ - -Retrieve all of the Relayer's orders, a set which at this point consists solely -of the one we just posted: - ->>> relayer.get_orders() -{'records': [{'meta_data': {'orderHash': '0x...', - 'remainingFillableTakerAssetAmount': '2'}, - 'order': {'chainId': 1337, - 'exchangeAddress': '0x...', - 'expirationTimeSeconds': '...', - 'feeRecipientAddress': '0x0000000000000000000000000000000000000001', - 'makerAddress': '0x...', - 'makerAssetAmount': '2', - 'makerAssetData': '0xf47261b000000000000000000000000...', - 'makerFee': '0', - 'makerFeeAssetData': '0xf47261b000000000000000000000000...', - 'salt': '...', - 'senderAddress': '0x0000000000000000000000000000000000000000', - 'signature': '0x...', - 'takerAddress': '0x0000000000000000000000000000000000000000', - 'takerAssetAmount': '2', - 'takerAssetData': '0xf47261b0000000000000000000000000...', - 'takerFee': '0', - 'takerFeeAssetData': '0xf47261b0000000000000000000000000...'}}...]} - -Get Asset Pairs ---------------- - -Get all of the Relayer's available asset pairs, which here means just WETH and -ZRX, since that's all there is on this Relayer's order book: - ->>> relayer.get_asset_pairs() -{'records': [{'assetDataA': {'assetData': '0xf47261b0000000000000000000000000...', - 'maxAmount': '115792089237316195423570985008687907853269984665640564039457584007913129639936', - 'minAmount': '0', - 'precision': 18}, - 'assetDataB': {'assetData': '0xf47261b0000000000000000000000000...', - 'maxAmount': '115792089237316195423570985008687907853269984665640564039457584007913129639936', - 'minAmount': '0', - 'precision': 18}}]} ->>> asset_data_utils.decode_erc20_asset_data( -... relayer.get_asset_pairs().records[0]['assetDataA']['assetData'] -... ).token_address == contract_addresses.zrx_token -True ->>> asset_data_utils.decode_erc20_asset_data( -... relayer.get_asset_pairs().records[0]['assetDataB']['assetData'] -... ).token_address == contract_addresses.ether_token -True - -Get Orderbook -------------- - -Get the Relayer's order book for the WETH/ZRX asset pair (which, again, -consists just of our order): - ->>> orderbook = relayer.get_orderbook( -... base_asset_data= "0x" + asset_data_utils.encode_erc20( -... contract_addresses.ether_token -... ).hex(), -... quote_asset_data= "0x" + asset_data_utils.encode_erc20( -... contract_addresses.zrx_token -... ).hex(), -... ) ->>> orderbook -{'asks': {'records': [...]}, - 'bids': {'records': [{'meta_data': {'orderHash': '0x...', - 'remainingFillableTakerAssetAmount': '2'}, - 'order': {'chainId': 1337, - 'exchangeAddress': '0x...', - 'expirationTimeSeconds': '...', - 'feeRecipientAddress': '0x0000000000000000000000000000000000000001', - 'makerAddress': '0x...', - 'makerAssetAmount': '2', - 'makerAssetData': '0xf47261b0000000000000000000000000...', - 'makerFee': '0', - 'makerFeeAssetData': '0xf47261b0000000000000000000000000...', - 'salt': '...', - 'senderAddress': '0x0000000000000000000000000000000000000000', - 'signature': '0x...', - 'takerAddress': '0x0000000000000000000000000000000000000000', - 'takerAssetAmount': '2', - 'takerAssetData': '0xf47261b0000000000000000000000000...', - 'takerFee': '0', - 'takerFeeAssetData': '0xf47261b0000000000000000000000000...'}}...]}} - -Select an order from the orderbook -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -We'll select the order we just submitted, which must be referred to by order -hash. To calculate an order hash, we'll use the Exchange contract: - ->>> from zero_ex.contract_wrappers.exchange import Exchange ->>> exchange = Exchange( -... web3_or_provider=eth_node, -... contract_address=chain_to_addresses(ChainId.GANACHE).exchange -... ) ->>> from zero_ex.contract_wrappers.order_conversions import jsdict_to_order ->>> order = jsdict_to_order( -... relayer.get_order( -... '0x' + exchange.get_order_info.call(order)["orderHash"].hex() -... ).order -... ) ->>> from pprint import pprint ->>> pprint(order) -{'chainId': 1337, - 'expirationTimeSeconds': ..., - 'feeRecipientAddress': '0x0000000000000000000000000000000000000001', - 'makerAddress': '0x...', - 'makerAssetAmount': 2, - 'makerAssetData': b... - 'makerFee': 0, - 'makerFeeAssetData': b... - 'salt': ..., - 'senderAddress': '0x0000000000000000000000000000000000000000', - 'signature': '0x...', - 'takerAddress': '0x0000000000000000000000000000000000000000', - 'takerAssetAmount': 2, - 'takerAssetData': b..., - 'takerFee': 0, - 'takerFeeAssetData': b...} - -Filling or Cancelling an Order ------------------------------- - -Fills and cancels are triggered by dealing directly with the 0x Exchange -contract, not by going through a Relayer. - -See `the 0x-contract-wrappers documentation -`_ for more -examples. - -Filling -^^^^^^^ - ->>> taker_address = Web3(eth_node).eth.accounts[1] - -Our taker will take a ZRX/WETH order, but it doesn't have any WETH yet. By -depositing some ether into the WETH contract, it will be given some WETH to -trade with: - ->>> weth_instance = Web3(eth_node).eth.contract( -... address=Web3.toChecksumAddress(contract_addresses.ether_token), -... abi=abi_by_name("WETH9") -... ) ->>> weth_instance.functions.deposit().transact( -... {"from": Web3.toChecksumAddress(taker_address), -... "value": 1000000000000000000} -... ) -HexBytes('0x...') - -Next the taker needs to give the 0x contracts permission to trade their WETH: - ->>> weth_instance.functions.approve( -... Web3.toChecksumAddress(contract_addresses.erc20_proxy), -... 1000000000000000000 -... ).transact( -... {"from": Web3.toChecksumAddress(taker_address)} -... ) -HexBytes('0x...') - -Now the taker is ready to trade. - -Recall that in a previous example we selected a specific order from the order -book. Now let's have the taker fill it: - ->>> from zero_ex.contract_wrappers import TxParams ->>> from zero_ex.order_utils import Order - -(Due to `an Issue with the Launch Kit Backend -`_, we need to -checksum the address in the order before filling it.) - ->>> order['makerAddress'] = Web3.toChecksumAddress(order['makerAddress']) - -Finally, filling an order requires paying a protocol fee, which can be sent as -value in the transaction. The calculation of the amount to send is a function -of the gas price, so we need some help from Web3.py for that: - ->>> from web3.gas_strategies.rpc import rpc_gas_price_strategy ->>> web3 = Web3(eth_node) ->>> web3.eth.setGasPriceStrategy(rpc_gas_price_strategy) - -Before actually executing the fill, it's a good idea to run it as read-only -(non-transactional) so that we can get intelligible errors in case there's -something wrong: - ->>> pprint(exchange.fill_order.call( -... order=order, -... taker_asset_fill_amount=order['takerAssetAmount']/2, # note the half fill -... signature=bytes.fromhex(order['signature'].replace('0x', '')), -... tx_params=TxParams( -... from_=taker_address, value=web3.eth.generateGasPrice()*150000, -... ), -... )) -{'makerAssetFilledAmount': 1, - 'makerFeePaid': 0, - 'protocolFeePaid': ..., - 'takerAssetFilledAmount': 1, - 'takerFeePaid': 0} - -Now we're finally ready to execute the fill: - ->>> exchange.fill_order.send_transaction( -... order=order, -... taker_asset_fill_amount=order['takerAssetAmount']/2, # note the half fill -... signature=bytes.fromhex(order['signature'].replace('0x', '')), -... tx_params=TxParams( -... from_=taker_address, value=web3.eth.generateGasPrice()*150000, -... ), -... ) -HexBytes('0x...') - -Cancelling -^^^^^^^^^^ - -Note that the above fill was partial: it only filled half of the order. Now -we'll have our maker cancel the remaining order: - ->>> exchange.cancel_order.send_transaction( -... order=order, -... tx_params=TxParams(from_=maker_address) -... ) -HexBytes('0x...') - -""" # noqa: E501 (line too long) - -from __future__ import absolute_import - -__version__ = "1.0.0" - -# import apis into sdk package -from .api.relayer_api import RelayerApi - -# import ApiClient -from .api_client import ApiClient -from .configuration import Configuration - -# import models into sdk package -from .models.order_schema import OrderSchema -from .models.paginated_collection_schema import PaginatedCollectionSchema -from .models.relayer_api_asset_data_pairs_response_schema import ( - RelayerApiAssetDataPairsResponseSchema, -) -from .models.relayer_api_asset_data_trade_info_schema import ( - RelayerApiAssetDataTradeInfoSchema, -) -from .models.relayer_api_error_response_schema import ( - RelayerApiErrorResponseSchema, -) -from .models.relayer_api_error_response_schema_validation_errors import ( - RelayerApiErrorResponseSchemaValidationErrors, -) -from .models.relayer_api_fee_recipients_response_schema import ( - RelayerApiFeeRecipientsResponseSchema, -) -from .models.relayer_api_order_config_payload_schema import ( - RelayerApiOrderConfigPayloadSchema, -) -from .models.relayer_api_order_config_response_schema import ( - RelayerApiOrderConfigResponseSchema, -) -from .models.relayer_api_order_schema import RelayerApiOrderSchema -from .models.relayer_api_orderbook_response_schema import ( - RelayerApiOrderbookResponseSchema, -) -from .models.relayer_api_orders_channel_subscribe_payload_schema import ( - RelayerApiOrdersChannelSubscribePayloadSchema, -) -from .models.relayer_api_orders_channel_subscribe_schema import ( - RelayerApiOrdersChannelSubscribeSchema, -) -from .models.relayer_api_orders_channel_update_schema import ( - RelayerApiOrdersChannelUpdateSchema, -) -from .models.relayer_api_orders_response_schema import ( - RelayerApiOrdersResponseSchema, -) -from .models.signed_order_schema import SignedOrderSchema diff --git a/python-packages/sra_client/src/zero_ex/sra_client/api/__init__.py b/python-packages/sra_client/src/zero_ex/sra_client/api/__init__.py deleted file mode 100644 index a98e99e272..0000000000 --- a/python-packages/sra_client/src/zero_ex/sra_client/api/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -from __future__ import absolute_import - -# flake8: noqa - -# import apis into api package -from zero_ex.sra_client.api.relayer_api import RelayerApi diff --git a/python-packages/sra_client/src/zero_ex/sra_client/api/relayer_api.py b/python-packages/sra_client/src/zero_ex/sra_client/api/relayer_api.py deleted file mode 100644 index ef74aaf24b..0000000000 --- a/python-packages/sra_client/src/zero_ex/sra_client/api/relayer_api.py +++ /dev/null @@ -1,1065 +0,0 @@ -# coding: utf-8 - - -from __future__ import absolute_import - -import re # noqa: F401 - -# python 2 and python 3 compatibility library -import six - -from zero_ex.sra_client.api_client import ApiClient -from zero_ex.sra_client.configuration import Configuration -from zero_ex.sra_client.models.relayer_api_order_config_payload_schema import ( - RelayerApiOrderConfigPayloadSchema, -) - - -class RelayerApi(object): - """API for SRA compliant 0x relayers.""" - - # NOTE: This class is auto generated by OpenAPI Generator - # Ref: https://openapi-generator.tech - - # Do not edit the class manually. - - def __init__(self, url: str): - config = Configuration() - config.host = url - self.api_client = ApiClient(config) - - def get_asset_pairs(self, **kwargs): - """get_asset_pairs - - Retrieves a list of available asset pairs and the information - required to trade them (in any order). Setting only `assetDataA` or - `assetDataB` returns pairs filtered by that asset only. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass `async_req` = **True** - - >>> thread = api.get_asset_pairs(async_req=True) # doctest: +SKIP - >>> result = thread.get() # doctest: +SKIP - - :param bool async_req: Whether request should be asynchronous. - :param str asset_data_a: The assetData value for the first asset in the pair. - :param str asset_data_b: The assetData value for the second asset in the pair. - :param int page: The number of the page to request in the collection. - :param int per_page: The number of records to return per page. - - :return: :class:`RelayerApiAssetDataPairsResponseSchema`. - If the method is called asynchronously returns the request thread. - """ - kwargs["_return_http_data_only"] = True - if kwargs.get("async_req"): - return self.get_asset_pairs_with_http_info(**kwargs) - else: - (data) = self.get_asset_pairs_with_http_info(**kwargs) - return data - - def get_asset_pairs_with_http_info(self, **kwargs): - """get_asset_pairs - - Retrieves a list of available asset pairs and the information - required to trade them (in any order). Setting only `assetDataA` or - `assetDataB` returns pairs filtered by that asset only. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass `async_req` = **True** - - >>> thread = api.get_asset_pairs_with_http_info(async_req=True) # doctest: +SKIP - >>> result = thread.get() # doctest: +SKIP - - :param bool async_req: Whether request should be asynchronous. - :param str asset_data_a: The assetData value for the first asset in the pair. - :param str asset_data_b: The assetData value for the second asset in the pair. - :param int page: The number of the page to request in the collection. - :param int per_page: The number of records to return per page. - - :return: A tuple consisting of a - :class:`RelayerApiAssetDataPairsResponseSchema`, an HTTP status - code integer, and a collection of HTTP headers. If the method is - called asynchronously returns the request thread. - """ - - local_var_params = locals() - - all_params = [ - "asset_data_a", - "asset_data_b", - "page", - "per_page", - ] - all_params.append("async_req") - all_params.append("_return_http_data_only") - all_params.append("_preload_content") - all_params.append("_request_timeout") - - for key, val in six.iteritems(local_var_params["kwargs"]): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method get_asset_pairs" % key - ) - local_var_params[key] = val - del local_var_params["kwargs"] - - collection_formats = {} - - path_params = {} - - query_params = [] - if "asset_data_a" in local_var_params: - query_params.append( - ("assetDataA", local_var_params["asset_data_a"]) - ) - if "asset_data_b" in local_var_params: - query_params.append( - ("assetDataB", local_var_params["asset_data_b"]) - ) - if "page" in local_var_params: - query_params.append(("page", local_var_params["page"])) - if "per_page" in local_var_params: - query_params.append(("perPage", local_var_params["per_page"])) - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params["Accept"] = self.api_client.select_header_accept( - ["application/json"] - ) - - # Authentication setting - auth_settings = [] - - return self.api_client.call_api( - "/v3/asset_pairs", - "GET", - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type="RelayerApiAssetDataPairsResponseSchema", - auth_settings=auth_settings, - async_req=local_var_params.get("async_req"), - _return_http_data_only=local_var_params.get( - "_return_http_data_only" - ), - _preload_content=local_var_params.get("_preload_content", True), - _request_timeout=local_var_params.get("_request_timeout"), - collection_formats=collection_formats, - ) - - def get_fee_recipients(self, **kwargs): - """get_fee_recipients - - Retrieves a collection of all fee recipient addresses for a relayer. - This endpoint should be paginated. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass `async_req` = **True** - - >>> thread = api.get_fee_recipients(async_req=True) # doctest: +SKIP - >>> result = thread.get() # doctest: +SKIP - - :param bool async_req: Whether request should be asynchronous. - :param int page: The number of the page to request in the collection. - :param int per_page: The number of records to return per page. - - :return: :class:`RelayerApiFeeRecipientsResponseSchema`. - If the method is called asynchronously, returns the request thread. - """ - kwargs["_return_http_data_only"] = True - if kwargs.get("async_req"): - return self.get_fee_recipients_with_http_info(**kwargs) - else: - (data) = self.get_fee_recipients_with_http_info(**kwargs) - return data - - def get_fee_recipients_with_http_info(self, **kwargs): - """get_fee_recipients - - Retrieves a collection of all fee recipient addresses for a relayer. - This endpoint should be paginated. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass `async_req` = **True** - - >>> thread = api.get_fee_recipients_with_http_info(async_req=True) # doctest: +SKIP - >>> result = thread.get() # doctest: +SKIP - - :param bool async_req: Whether request should be asynchronous. - :param int page: The number of the page to request in the collection. - :param int per_page: The number of records to return per page. - - :return: A tuple consisting of a - :class:`RelayerApiFeeRecipientsResponseSchema`, an HTTP status - code integer, and a collection of HTTP headers. If the method is - called asynchronously returns the request thread. - """ - - local_var_params = locals() - - all_params = ["page", "per_page"] - all_params.append("async_req") - all_params.append("_return_http_data_only") - all_params.append("_preload_content") - all_params.append("_request_timeout") - - for key, val in six.iteritems(local_var_params["kwargs"]): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method get_fee_recipients" % key - ) - local_var_params[key] = val - del local_var_params["kwargs"] - - collection_formats = {} - - path_params = {} - - query_params = [] - if "page" in local_var_params: - query_params.append(("page", local_var_params["page"])) - if "per_page" in local_var_params: - query_params.append(("perPage", local_var_params["per_page"])) - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params["Accept"] = self.api_client.select_header_accept( - ["application/json"] - ) - - # Authentication setting - auth_settings = [] - - return self.api_client.call_api( - "/v3/fee_recipients", - "GET", - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type="RelayerApiFeeRecipientsResponseSchema", - auth_settings=auth_settings, - async_req=local_var_params.get("async_req"), - _return_http_data_only=local_var_params.get( - "_return_http_data_only" - ), - _preload_content=local_var_params.get("_preload_content", True), - _request_timeout=local_var_params.get("_request_timeout"), - collection_formats=collection_formats, - ) - - def get_order(self, order_hash, **kwargs): - """get_order - - Retrieves the 0x order with meta info that is associated with the hash. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass `async_req` = **True** - - >>> thread = api.get_order(async_req=True) # doctest: +SKIP - >>> result = thread.get() # doctest: +SKIP - - :param bool async_req: Whether request should be asynchronous. - :param str order_hash: The hash of the desired 0x order. (required) - - :return: :class:`RelayerApiOrderSchema`. - If the method is called asynchronously, returns the request thread. - """ - kwargs["_return_http_data_only"] = True - if kwargs.get("async_req"): - return self.get_order_with_http_info(order_hash, **kwargs) - else: - (data) = self.get_order_with_http_info(order_hash, **kwargs) - return data - - def get_order_with_http_info(self, order_hash, **kwargs): - """get_order - - Retrieves the 0x order with meta info that is associated with the hash. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass `async_req` = **True** - - >>> thread = api.get_order_with_http_info(async_req=True) # doctest: +SKIP - >>> result = thread.get() # doctest: +SKIP - - :param bool async_req: Whether request should be asynchronous. - :param str order_hash: The hash of the desired 0x order. (required) - - :return: A tuple consisting of a - :class:`RelayerApiOrderSchema`, an HTTP status code integer, and a - collection of HTTP headers. If the method is called - asynchronously returns the request thread. - """ - - local_var_params = locals() - - all_params = ["order_hash"] - all_params.append("async_req") - all_params.append("_return_http_data_only") - all_params.append("_preload_content") - all_params.append("_request_timeout") - - for key, val in six.iteritems(local_var_params["kwargs"]): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method get_order" % key - ) - local_var_params[key] = val - del local_var_params["kwargs"] - # verify the required parameter 'order_hash' is set - if ( - "order_hash" not in local_var_params - or local_var_params["order_hash"] is None - ): - raise ValueError( - "Missing the required parameter `order_hash` when calling `get_order`" - ) - - collection_formats = {} - - path_params = {} - if "order_hash" in local_var_params: - path_params["orderHash"] = local_var_params["order_hash"] - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params["Accept"] = self.api_client.select_header_accept( - ["application/json"] - ) - - # Authentication setting - auth_settings = [] - - return self.api_client.call_api( - "/v3/order/{orderHash}", - "GET", - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type="RelayerApiOrderSchema", - auth_settings=auth_settings, - async_req=local_var_params.get("async_req"), - _return_http_data_only=local_var_params.get( - "_return_http_data_only" - ), - _preload_content=local_var_params.get("_preload_content", True), - _request_timeout=local_var_params.get("_request_timeout"), - collection_formats=collection_formats, - ) - - def get_order_config(self, **kwargs): - """get_order_config - - Relayers have full discretion over the orders that they are willing - to host on their orderbooks (e.g what fees they charge, etc...). In - order for traders to discover their requirements programmatically, - they can send an incomplete order to this endpoint and receive the - missing fields, specifc to that order. This gives relayers a large - amount of flexibility to tailor fees to unique traders, trading pairs - and volume amounts. Submit a partial order and receive information - required to complete the order: `senderAddress`, - `feeRecipientAddress`, `makerFee`, `takerFee`. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass `async_req` = **True** - - >>> thread = api.get_order_config(async_req=True) # doctest: +SKIP - >>> result = thread.get() # doctest: +SKIP - - :param bool async_req: Whether request should be asynchronous. - :param relayer_api_order_config_payload_schema: instance of - :class:`RelayerApiOrderConfigPayloadSchema`. The fields of a 0x - order the relayer may want to decide what configuration to send - back. - - :return: :class:`RelayerApiOrderConfigResponseSchema`. - If the method is called asynchronously returns the request thread. - """ - kwargs["_return_http_data_only"] = True - if kwargs.get("async_req"): - return self.get_order_config_with_http_info(**kwargs) - else: - (data) = self.get_order_config_with_http_info(**kwargs) - return data - - def get_order_config_with_http_info(self, **kwargs): - """get_order_config - - Relayers have full discretion over the orders that they are willing - to host on their orderbooks (e.g what fees they charge, etc...). In - order for traders to discover their requirements programmatically, - they can send an incomplete order to this endpoint and receive the - missing fields, specifc to that order. This gives relayers a large - amount of flexibility to tailor fees to unique traders, trading pairs - and volume amounts. Submit a partial order and receive information - required to complete the order: `senderAddress`, - `feeRecipientAddress`, `makerFee`, `takerFee`. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass `async_req` = **True** - - >>> thread = api.get_order_config_with_http_info(async_req=True) # doctest: +SKIP - >>> result = thread.get() # doctest: +SKIP - - :param bool async_req: Whether request should be asynchronous. - :param relayer_api_order_config_payload_schema: instance of - :class: `RelayerApiOrderConfigPayloadSchema`. The fields of a 0x - order the relayer may want to decide what configuration to send - back. - - :return: A tuple consisting of a - :class:`RelayerApiOrderConfigResponseSchema`, an HTTP status code - integer, and a collection of HTTP headers. If the method is - called asynchronously returns the request thread. - """ - - local_var_params = locals() - - all_params = ["relayer_api_order_config_payload_schema"] - all_params.append("async_req") - all_params.append("_return_http_data_only") - all_params.append("_preload_content") - all_params.append("_request_timeout") - - for key, val in six.iteritems(local_var_params["kwargs"]): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method get_order_config" % key - ) - local_var_params[key] = val - del local_var_params["kwargs"] - - collection_formats = {} - - path_params = {} - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if "relayer_api_order_config_payload_schema" in local_var_params: - body_params = local_var_params[ - "relayer_api_order_config_payload_schema" - ] - # HTTP header `Accept` - header_params["Accept"] = self.api_client.select_header_accept( - ["application/json"] - ) - - # HTTP header `Content-Type` - header_params[ - "Content-Type" - ] = self.api_client.select_header_content_type(["application/json"]) - - # Authentication setting - auth_settings = [] - - return self.api_client.call_api( - "/v3/order_config", - "POST", - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type="RelayerApiOrderConfigResponseSchema", - auth_settings=auth_settings, - async_req=local_var_params.get("async_req"), - _return_http_data_only=local_var_params.get( - "_return_http_data_only" - ), - _preload_content=local_var_params.get("_preload_content", True), - _request_timeout=local_var_params.get("_request_timeout"), - collection_formats=collection_formats, - ) - - def get_orderbook(self, base_asset_data, quote_asset_data, **kwargs): - """get_orderbook - - Retrieves the orderbook for a given asset pair. This endpoint should - be paginated. Bids will be sorted in - descending order by price, and asks will be sorted in ascending order - by price. Within the price sorted orders, the orders are further - sorted by **taker fee price** which is defined as the **takerFee** - divided by **takerTokenAmount**. After **taker fee price**, orders are - to be sorted by expiration in ascending order. The way pagination - works for this endpoint is that the **page** and **perPage** query - params apply to both `bids` and `asks` collections, and if `page` * - `perPage` = `total` for a certain collection, the `records` for that - collection should just be empty. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass `async_req` = **True** - - >>> thread = api.get_orderbook(async_req=True) # doctest: +SKIP - >>> result = thread.get() # doctest: +SKIP - - :param bool async_req: Whether request should be asynchronous. - :param str base_asset_data: assetData (makerAssetData or - takerAssetData) designated as the base currency in the - `currency pair calculation - `__ - of price. (required) - :param str quote_asset_data: assetData (makerAssetData or - takerAssetData) designated as the quote currency in the currency - pair calculation of price. (required) - :param int page: The number of the page to request in the collection. - :param int per_page: The number of records to return per page. - - :return: :class:`RelayerApiOrderbookResponseSchema`. - If the method is called asynchronously, returns the request thread. - """ - kwargs["_return_http_data_only"] = True - if kwargs.get("async_req"): - return self.get_orderbook_with_http_info( - base_asset_data, quote_asset_data, **kwargs - ) - else: - (data) = self.get_orderbook_with_http_info( - base_asset_data, quote_asset_data, **kwargs - ) - return data - - def get_orderbook_with_http_info( - self, base_asset_data, quote_asset_data, **kwargs - ): - """get_orderbook - - Retrieves the orderbook for a given asset pair. This endpoint should - be paginated. Bids will be sorted in - descending order by price, and asks will be sorted in ascending order - by price. Within the price sorted orders, the orders are further - sorted by **taker fee price** which is defined as the **takerFee** - divided by **takerTokenAmount**. After **taker fee price**, orders are - to be sorted by expiration in ascending order. The way pagination - works for this endpoint is that the **page** and **perPage** query - params apply to both `bids` and `asks` collections, and if `page` * - `perPage` = `total` for a certain collection, the `records` for that - collection should just be empty. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass `async_req` = **True** - - >>> thread = api.get_orderbook_with_http_info(async_req=True) # doctest: +SKIP - >>> result = thread.get() # doctest: +SKIP - - :param bool async_req: Whether request should be asynchronous. - :param str base_asset_data: assetData (makerAssetData or - takerAssetData) designated as the base currency in the - `currency pair calculation - `__ - of price. (required) - :param str quote_asset_data: assetData (makerAssetData or - takerAssetData) designated as the quote currency in the currency - pair calculation of price. (required) - :param int page: The number of the page to request in the collection. - :param int per_page: The number of records to return per page. - - :return: A tuple consisting of a - :class:`RelayerApiOrderbookResponseSchema`, an HTTP status code - integer, and a collection of HTTP headers. If the method is - called asynchronously returns the request thread. - """ - - local_var_params = locals() - - all_params = [ - "base_asset_data", - "quote_asset_data", - "page", - "per_page", - ] - all_params.append("async_req") - all_params.append("_return_http_data_only") - all_params.append("_preload_content") - all_params.append("_request_timeout") - - for key, val in six.iteritems(local_var_params["kwargs"]): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method get_orderbook" % key - ) - local_var_params[key] = val - del local_var_params["kwargs"] - # verify the required parameter 'base_asset_data' is set - if ( - "base_asset_data" not in local_var_params - or local_var_params["base_asset_data"] is None - ): - raise ValueError( - "Missing the required parameter `base_asset_data`" - "when calling `get_orderbook`" - ) - # verify the required parameter 'quote_asset_data' is set - if ( - "quote_asset_data" not in local_var_params - or local_var_params["quote_asset_data"] is None - ): - raise ValueError( - "Missing the required parameter `quote_asset_data`" - " when calling `get_orderbook`" - ) - - collection_formats = {} - - path_params = {} - - query_params = [] - if "base_asset_data" in local_var_params: - query_params.append( - ("baseAssetData", local_var_params["base_asset_data"]) - ) - if "quote_asset_data" in local_var_params: - query_params.append( - ("quoteAssetData", local_var_params["quote_asset_data"]) - ) - if "page" in local_var_params: - query_params.append(("page", local_var_params["page"])) - if "per_page" in local_var_params: - query_params.append(("perPage", local_var_params["per_page"])) - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params["Accept"] = self.api_client.select_header_accept( - ["application/json"] - ) - - # Authentication setting - auth_settings = [] - - return self.api_client.call_api( - "/v3/orderbook", - "GET", - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type="RelayerApiOrderbookResponseSchema", - auth_settings=auth_settings, - async_req=local_var_params.get("async_req"), - _return_http_data_only=local_var_params.get( - "_return_http_data_only" - ), - _preload_content=local_var_params.get("_preload_content", True), - _request_timeout=local_var_params.get("_request_timeout"), - collection_formats=collection_formats, - ) - - def get_orders(self, **kwargs): - """get_orders - - Retrieves a list of orders given query parameters. This endpoint - should be paginated. For querying an entire - orderbook snapshot, the orderbook endpoint - is recommended. If both makerAssetData and takerAssetData are - specified, returned orders will be sorted by price determined by - (takerTokenAmount/makerTokenAmount) in ascending order. By default, - orders returned by this endpoint are unsorted. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass `async_req` = **True** - - >>> thread = api.get_orders(async_req=True) # doctest: +SKIP - >>> result = thread.get() # doctest: +SKIP - - :param bool async_req: Whether request should be asynchronous. - :param str maker_asset_proxy_id: The maker - `asset proxy id - `__ - (example: "0xf47261b0" for ERC20, "0x02571792" for ERC721). - :param str taker_asset_proxy_id: The taker asset - `asset proxy id - `__ - (example: "0xf47261b0" for ERC20, "0x02571792" for ERC721). - :param str maker_asset_address: The contract address for the maker asset. - :param str taker_asset_address: The contract address for the taker asset. - :param str exchange_address: Contract address for the exchange - contract. - :param str sender_address: Same as senderAddress in the - `0x Protocol v3 Specification - `__ - :param str maker_asset_data: Same as makerAssetData in the - `0x Protocol v3 Specification - `__ - :param str taker_asset_data: Same as takerAssetData in the - `0x Protocol v3 Specification - `__ - :param str trader_asset_data: Same as traderAssetData in the [0x - `0x Protocol v3 Specification - `__ - :param str maker_address: Same as makerAddress in the - `0x Protocol v3 Specification - `__ - :param str taker_address: Same as takerAddress in the - `0x Protocol v3 Specification - `__ - :param str trader_address: Same as traderAddress in the - `0x Protocol v3 Specification - `__ - :param str fee_recipient_address: Same as feeRecipientAddress in the - `0x Protocol v3 Specification - `__ - :param int page: The number of the page to request in the collection. - :param int per_page: The number of records to return per page. - - :return: :class:`RelayerApiOrdersResponseSchema`. - If the method is called asynchronously, returns the request thread. - """ - kwargs["_return_http_data_only"] = True - if kwargs.get("async_req"): - return self.get_orders_with_http_info(**kwargs) - else: - (data) = self.get_orders_with_http_info(**kwargs) - return data - - def get_orders_with_http_info(self, **kwargs): - """get_orders - - Retrieves a list of orders given query parameters. This endpoint - should be paginated. For querying an entire - orderbook snapshot, the orderbook endpoint - is recommended. If both makerAssetData and takerAssetData are - specified, returned orders will be sorted by price determined by - (takerTokenAmount/makerTokenAmount) in ascending order. By default, - orders returned by this endpoint are unsorted. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass `async_req` = **True** - - >>> thread = api.get_orders_with_http_info(async_req=True) # doctest: +SKIP - >>> result = thread.get() # doctest: +SKIP - - :param bool async_req: Whether request should be asynchronous. - :param str maker_asset_proxy_id: The maker - `asset proxy id - `__ - (example: "0xf47261b0" for ERC20, "0x02571792" for ERC721). - :param str taker_asset_proxy_id: The taker asset - `asset proxy id - `__ - (example: "0xf47261b0" for ERC20, "0x02571792" for ERC721). - :param str maker_asset_address: The contract address for the maker asset. - :param str taker_asset_address: The contract address for the taker asset. - :param str exchange_address: Same as exchangeAddress in the [0x - `0x Protocol v3 Specification - `__ - :param str sender_address: Same as senderAddress in the - `0x Protocol v3 Specification - `__ - :param str maker_asset_data: Same as makerAssetData in the - `0x Protocol v3 Specification - `__ - :param str taker_asset_data: Same as takerAssetData in the - `0x Protocol v3 Specification - `__ - :param str trader_asset_data: Same as traderAssetData in the - `0x Protocol v3 Specification - `__ - :param str maker_address: Same as makerAddress in the - `0x Protocol v3 Specification - `__ - :param str taker_address: Same as takerAddress in the - `0x Protocol v3 Specification - `__ - :param str trader_address: Same as traderAddress in the - `0x Protocol v3 Specification - `__ - :param str fee_recipient_address: Same as feeRecipientAddress in the - `0x Protocol v3 Specification - `__ - :param int page: The number of the page to request in the collection. - :param int per_page: The number of records to return per page. - - :return: A tuple consisting of a - :class:`RelayerApiOrdersResponseSchema`, an HTTP status code - integer, and a collection of HTTP headers. If the method is - called asynchronously returns the request thread. - """ - - local_var_params = locals() - - all_params = [ - "maker_asset_proxy_id", - "taker_asset_proxy_id", - "maker_asset_address", - "taker_asset_address", - "exchange_address", - "sender_address", - "maker_asset_data", - "taker_asset_data", - "trader_asset_data", - "maker_address", - "taker_address", - "trader_address", - "fee_recipient_address", - "page", - "per_page", - ] - all_params.append("async_req") - all_params.append("_return_http_data_only") - all_params.append("_preload_content") - all_params.append("_request_timeout") - - for key, val in six.iteritems(local_var_params["kwargs"]): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method get_orders" % key - ) - local_var_params[key] = val - del local_var_params["kwargs"] - - collection_formats = {} - - path_params = {} - - query_params = [] - if "maker_asset_proxy_id" in local_var_params: - query_params.append( - ("makerAssetProxyId", local_var_params["maker_asset_proxy_id"]) - ) - if "taker_asset_proxy_id" in local_var_params: - query_params.append( - ("takerAssetProxyId", local_var_params["taker_asset_proxy_id"]) - ) - if "maker_asset_address" in local_var_params: - query_params.append( - ("makerAssetAddress", local_var_params["maker_asset_address"]) - ) - if "taker_asset_address" in local_var_params: - query_params.append( - ("takerAssetAddress", local_var_params["taker_asset_address"]) - ) - if "exchange_address" in local_var_params: - query_params.append( - ("exchangeAddress", local_var_params["exchange_address"]) - ) - if "sender_address" in local_var_params: - query_params.append( - ("senderAddress", local_var_params["sender_address"]) - ) - if "maker_asset_data" in local_var_params: - query_params.append( - ("makerAssetData", local_var_params["maker_asset_data"]) - ) - if "taker_asset_data" in local_var_params: - query_params.append( - ("takerAssetData", local_var_params["taker_asset_data"]) - ) - if "trader_asset_data" in local_var_params: - query_params.append( - ("traderAssetData", local_var_params["trader_asset_data"]) - ) - if "maker_address" in local_var_params: - query_params.append( - ("makerAddress", local_var_params["maker_address"]) - ) - if "taker_address" in local_var_params: - query_params.append( - ("takerAddress", local_var_params["taker_address"]) - ) - if "trader_address" in local_var_params: - query_params.append( - ("traderAddress", local_var_params["trader_address"]) - ) - if "fee_recipient_address" in local_var_params: - query_params.append( - ( - "feeRecipientAddress", - local_var_params["fee_recipient_address"], - ) - ) - if "page" in local_var_params: - query_params.append(("page", local_var_params["page"])) - if "per_page" in local_var_params: - query_params.append(("perPage", local_var_params["per_page"])) - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params["Accept"] = self.api_client.select_header_accept( - ["application/json"] - ) - - # Authentication setting - auth_settings = [] - - return self.api_client.call_api( - "/v3/orders", - "GET", - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type="RelayerApiOrdersResponseSchema", - auth_settings=auth_settings, - async_req=local_var_params.get("async_req"), - _return_http_data_only=local_var_params.get( - "_return_http_data_only" - ), - _preload_content=local_var_params.get("_preload_content", True), - _request_timeout=local_var_params.get("_request_timeout"), - collection_formats=collection_formats, - ) - - def post_order(self, **kwargs): - """post_order - - Submit a signed order to the relayer. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass `async_req` = **True** - - >>> thread = api.post_order(async_req=True) # doctest: +SKIP - >>> result = thread.get() # doctest: +SKIP - - :param bool async_req: Whether request should be asynchronous. - :param signed_order_schema: Instance of :class:`SignedOrderSchema`. - A valid signed 0x order based on the schema. - - :return: None. - If the method is called asynchronously, returns the request thread. - """ - kwargs["_return_http_data_only"] = True - if kwargs.get("async_req"): - return self.post_order_with_http_info(**kwargs) - else: - (data) = self.post_order_with_http_info(**kwargs) - return data - - def post_order_with_http_info(self, **kwargs): - """post_order - - Submit a signed order to the relayer. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass `async_req` = **True** - - >>> thread = api.post_order_with_http_info(async_req=True) # doctest: +SKIP - >>> result = thread.get() # doctest: +SKIP - - :param bool async_req: Whether request should be asynchronous. - :param signed_order_schema: Instance of :class:`SignedOrderSchema` - A valid signed 0x order based on the schema. - - :return: A tuple consisting of the response data (always empty for this - method), an HTTP status code integer, and a collection of HTTP - headers. If the method is called asynchronously returns the - request thread. - """ - - local_var_params = locals() - - all_params = ["signed_order_schema"] - all_params.append("async_req") - all_params.append("_return_http_data_only") - all_params.append("_preload_content") - all_params.append("_request_timeout") - - for key, val in six.iteritems(local_var_params["kwargs"]): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method post_order" % key - ) - local_var_params[key] = val - del local_var_params["kwargs"] - - collection_formats = {} - - path_params = {} - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if "signed_order_schema" in local_var_params: - body_params = local_var_params["signed_order_schema"] - # HTTP header `Accept` - header_params["Accept"] = self.api_client.select_header_accept( - ["application/json"] - ) - - # HTTP header `Content-Type` - header_params[ - "Content-Type" - ] = self.api_client.select_header_content_type(["application/json"]) - - # Authentication setting - auth_settings = [] - - return self.api_client.call_api( - "/v3/order", - "POST", - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - async_req=local_var_params.get("async_req"), - _return_http_data_only=local_var_params.get( - "_return_http_data_only" - ), - _preload_content=local_var_params.get("_preload_content", True), - _request_timeout=local_var_params.get("_request_timeout"), - collection_formats=collection_formats, - ) diff --git a/python-packages/sra_client/src/zero_ex/sra_client/api_client.py b/python-packages/sra_client/src/zero_ex/sra_client/api_client.py deleted file mode 100644 index 829833ec86..0000000000 --- a/python-packages/sra_client/src/zero_ex/sra_client/api_client.py +++ /dev/null @@ -1,729 +0,0 @@ -# coding: utf-8 - -from __future__ import absolute_import - -import datetime -import json -import mimetypes -from multiprocessing.pool import ThreadPool -import os -import re -import tempfile - -# python 2 and python 3 compatibility library -import six -from six.moves.urllib.parse import quote - -from zero_ex.sra_client.configuration import Configuration -import zero_ex.sra_client.models -from zero_ex.sra_client import rest - - -class ApiClient(object): - """Generic API client for OpenAPI client library builds. - - OpenAPI generic API client. This client handles the client- - server communication, and is invariant across implementations. Specifics of - the methods and models for each application are generated from the OpenAPI - templates. - - NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - Do not edit the class manually. - - :param configuration: .Configuration object for this client - :param header_name: a header to pass when making calls to the API. - :param header_value: a header value to pass when making calls to - the API. - :param cookie: a cookie to include in the header when making calls - to the API - :param pool_threads: The number of threads to use for async requests - to the API. More threads means more concurrent API requests. - """ - - PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types - NATIVE_TYPES_MAPPING = { - "int": int, - "long": int if six.PY3 else long, # noqa: F821 - "float": float, - "str": str, - "bool": bool, - "date": datetime.date, - "datetime": datetime.datetime, - "object": object, - } - _pool = None - - def __init__( - self, - configuration=None, - header_name=None, - header_value=None, - cookie=None, - pool_threads=None, - ): - if configuration is None: - configuration = Configuration() - self.configuration = configuration - self.pool_threads = pool_threads - - self.rest_client = rest.RESTClientObject(configuration) - self.default_headers = {} - if header_name is not None: - self.default_headers[header_name] = header_value - self.cookie = cookie - # Set default User-Agent. - self.user_agent = "OpenAPI-Generator/1.0.0/python" - - def __del__(self): - if self._pool: - self._pool.close() - self._pool.join() - self._pool = None - - @property - def pool(self): - """Create thread pool on first request - avoids instantiating unused threadpool for blocking clients. - """ - if self._pool is None: - self._pool = ThreadPool(self.pool_threads) - return self._pool - - @property - def user_agent(self): - """User agent for this API client""" - return self.default_headers["User-Agent"] - - @user_agent.setter - def user_agent(self, value): - self.default_headers["User-Agent"] = value - - def set_default_header(self, header_name, header_value): - self.default_headers[header_name] = header_value - - def __call_api( - self, - resource_path, - method, - path_params=None, - query_params=None, - header_params=None, - body=None, - post_params=None, - files=None, - response_type=None, - auth_settings=None, - _return_http_data_only=None, - collection_formats=None, - _preload_content=True, - _request_timeout=None, - ): - - config = self.configuration - - # header parameters - header_params = header_params or {} - header_params.update(self.default_headers) - if self.cookie: - header_params["Cookie"] = self.cookie - if header_params: - header_params = self.sanitize_for_serialization(header_params) - header_params = dict( - self.parameters_to_tuples(header_params, collection_formats) - ) - - # path parameters - if path_params: - path_params = self.sanitize_for_serialization(path_params) - path_params = self.parameters_to_tuples( - path_params, collection_formats - ) - for k, v in path_params: - # specified safe chars, encode everything - resource_path = resource_path.replace( - "{%s}" % k, - quote(str(v), safe=config.safe_chars_for_path_param), - ) - - # query parameters - if query_params: - query_params = self.sanitize_for_serialization(query_params) - query_params = self.parameters_to_tuples( - query_params, collection_formats - ) - - # post parameters - if post_params or files: - post_params = self.prepare_post_parameters(post_params, files) - post_params = self.sanitize_for_serialization(post_params) - post_params = self.parameters_to_tuples( - post_params, collection_formats - ) - - # auth setting - self.update_params_for_auth(header_params, query_params, auth_settings) - - # body - if body: - body = self.sanitize_for_serialization(body) - - # request url - url = self.configuration.host + resource_path - - # perform request and return response - response_data = self.request( - method, - url, - query_params=query_params, - headers=header_params, - post_params=post_params, - body=body, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - ) - - self.last_response = response_data - - return_data = response_data - if _preload_content: - # deserialize response data - if response_type: - return_data = self.deserialize(response_data, response_type) - else: - return_data = None - - if _return_http_data_only: - return return_data - else: - return ( - return_data, - response_data.status, - response_data.getheaders(), - ) - - def sanitize_for_serialization(self, obj): - """Builds a JSON POST object. - - If obj is None, return None. - If obj is str, int, long, float, bool, return directly. - If obj is datetime.datetime, datetime.date convert to string in iso8601 format. - If obj is list, sanitize each element in the list. - If obj is dict, return the dict. - If obj is OpenAPI model, return the properties dict. - - :param obj: The data to serialize. - :return: The serialized form of data. - """ - if obj is None: - return None - elif isinstance(obj, self.PRIMITIVE_TYPES): - return obj - elif isinstance(obj, list): - return [ - self.sanitize_for_serialization(sub_obj) for sub_obj in obj - ] - elif isinstance(obj, tuple): - return tuple( - self.sanitize_for_serialization(sub_obj) for sub_obj in obj - ) - elif isinstance(obj, (datetime.datetime, datetime.date)): - return obj.isoformat() - - if isinstance(obj, dict): - obj_dict = obj - else: - # Convert model obj to dict except - # attributes `openapi_types`, `attribute_map` - # and attributes which value is not None. - # Convert attribute name to json key in - # model definition for request. - obj_dict = { - obj.attribute_map[attr]: getattr(obj, attr) - for attr, _ in six.iteritems(obj.openapi_types) - if getattr(obj, attr) is not None - } - - return { - key: self.sanitize_for_serialization(val) - for key, val in six.iteritems(obj_dict) - } - - def deserialize(self, response, response_type): - """Deserializes response into an object. - - :param response: RESTResponse object to be deserialized. - :param response_type: class literal for - deserialized object, or string of class name. - - :return: deserialized object. - """ - # handle file downloading - # save response body into a tmp file and return the instance - if response_type == "file": - return self.__deserialize_file(response) - - # fetch data from response object - try: - data = json.loads(response.data) - except ValueError: - data = response.data - - return self.__deserialize(data, response_type) - - def __deserialize(self, data, klass): - """Deserializes dict, list, str into an object. - - :param data: dict, list or str. - :param klass: class literal, or string of class name. - - :return: object. - """ - if data is None: - return None - - if type(klass) == str: - if klass.startswith("list["): - sub_kls = re.match(r"list\[(.*)\]", klass).group(1) - return [ - self.__deserialize(sub_data, sub_kls) for sub_data in data - ] - - if klass.startswith("dict("): - sub_kls = re.match(r"dict\(([^,]*), (.*)\)", klass).group(2) - return { - k: self.__deserialize(v, sub_kls) - for k, v in six.iteritems(data) - } - - # convert str to class - if klass in self.NATIVE_TYPES_MAPPING: - klass = self.NATIVE_TYPES_MAPPING[klass] - else: - klass = getattr(zero_ex.sra_client.models, klass) - - if klass in self.PRIMITIVE_TYPES: - return self.__deserialize_primitive(data, klass) - elif klass == object: - return self.__deserialize_object(data) - elif klass == datetime.date: - return self.__deserialize_date(data) - elif klass == datetime.datetime: - return self.__deserialize_datatime(data) - else: - return self.__deserialize_model(data, klass) - - def call_api( - self, - resource_path, - method, - path_params=None, - query_params=None, - header_params=None, - body=None, - post_params=None, - files=None, - response_type=None, - auth_settings=None, - async_req=None, - _return_http_data_only=None, - collection_formats=None, - _preload_content=True, - _request_timeout=None, - ): - """Makes the HTTP request (synchronous) and returns deserialized data. - - To make an async_req request, set the async_req parameter. - - :param resource_path: Path to method endpoint. - :param method: Method to call. - :param path_params: Path parameters in the url. - :param query_params: Query parameters in the url. - :param header_params: Header parameters to be - placed in the request header. - :param body: Request body. - :param post_params dict: Request post form parameters, - for `application/x-www-form-urlencoded`, `multipart/form-data`. - :param auth_settings list: Auth Settings names for the request. - :param response: Response data type. - :param files dict: key -> filename, value -> filepath, - for `multipart/form-data`. - :param async_req bool: execute request asynchronously - :param _return_http_data_only: response data without head status code - and headers - :param collection_formats: dict of collection formats for path, query, - header, and post parameters. - :param _preload_content: if False, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is True. - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: - If async_req parameter is True, - the request will be called asynchronously. - The method will return the request thread. - If parameter async_req is False or missing, - then the method will return the response directly. - """ - if not async_req: - return self.__call_api( - resource_path, - method, - path_params, - query_params, - header_params, - body, - post_params, - files, - response_type, - auth_settings, - _return_http_data_only, - collection_formats, - _preload_content, - _request_timeout, - ) - else: - thread = self.pool.apply_async( - self.__call_api, - ( - resource_path, - method, - path_params, - query_params, - header_params, - body, - post_params, - files, - response_type, - auth_settings, - _return_http_data_only, - collection_formats, - _preload_content, - _request_timeout, - ), - ) - return thread - - def request( - self, - method, - url, - query_params=None, - headers=None, - post_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - """Makes the HTTP request using RESTClient.""" - if method == "GET": - return self.rest_client.GET( - url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers, - ) - elif method == "HEAD": - return self.rest_client.HEAD( - url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers, - ) - elif method == "OPTIONS": - return self.rest_client.OPTIONS( - url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - elif method == "POST": - return self.rest_client.POST( - url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - elif method == "PUT": - return self.rest_client.PUT( - url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - elif method == "PATCH": - return self.rest_client.PATCH( - url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - elif method == "DELETE": - return self.rest_client.DELETE( - url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - else: - raise ValueError( - "http method must be `GET`, `HEAD`, `OPTIONS`," - " `POST`, `PATCH`, `PUT` or `DELETE`." - ) - - def parameters_to_tuples(self, params, collection_formats): - """Get parameters as list of tuples, formatting collections. - - :param params: Parameters as dict or list of two-tuples - :param dict collection_formats: Parameter collection formats - :return: Parameters as list of tuples, collections formatted - """ - new_params = [] - if collection_formats is None: - collection_formats = {} - for k, v in ( - six.iteritems(params) if isinstance(params, dict) else params - ): # noqa: E501 - if k in collection_formats: - collection_format = collection_formats[k] - if collection_format == "multi": - new_params.extend((k, value) for value in v) - else: - if collection_format == "ssv": - delimiter = " " - elif collection_format == "tsv": - delimiter = "\t" - elif collection_format == "pipes": - delimiter = "|" - else: # csv is the default - delimiter = "," - new_params.append( - (k, delimiter.join(str(value) for value in v)) - ) - else: - new_params.append((k, v)) - return new_params - - def prepare_post_parameters(self, post_params=None, files=None): - """Builds form parameters. - - :param post_params: Normal form parameters. - :param files: File parameters. - :return: Form parameters with files. - """ - params = [] - - if post_params: - params = post_params - - if files: - for k, v in six.iteritems(files): - if not v: - continue - file_names = v if type(v) is list else [v] - for n in file_names: - with open(n, "rb") as f: - filename = os.path.basename(f.name) - filedata = f.read() - mimetype = ( - mimetypes.guess_type(filename)[0] - or "application/octet-stream" - ) - params.append( - tuple([k, tuple([filename, filedata, mimetype])]) - ) - - return params - - def select_header_accept(self, accepts): - """Returns `Accept` based on an array of accepts provided. - - :param accepts: List of headers. - :return: Accept (e.g. application/json). - """ - if not accepts: - return - - accepts = [x.lower() for x in accepts] - - if "application/json" in accepts: - return "application/json" - else: - return ", ".join(accepts) - - def select_header_content_type(self, content_types): - """Returns `Content-Type` based on an array of content_types provided. - - :param content_types: List of content-types. - :return: Content-Type (e.g. application/json). - """ - if not content_types: - return "application/json" - - content_types = [x.lower() for x in content_types] - - if "application/json" in content_types or "*/*" in content_types: - return "application/json" - else: - return content_types[0] - - def update_params_for_auth(self, headers, querys, auth_settings): - """Updates header and query params based on authentication setting. - - :param headers: Header parameters dict to be updated. - :param querys: Query parameters tuple list to be updated. - :param auth_settings: Authentication setting identifiers list. - """ - if not auth_settings: - return - - for auth in auth_settings: - auth_setting = self.configuration.auth_settings().get(auth) - if auth_setting: - if not auth_setting["value"]: - continue - elif auth_setting["in"] == "header": - headers[auth_setting["key"]] = auth_setting["value"] - elif auth_setting["in"] == "query": - querys.append((auth_setting["key"], auth_setting["value"])) - else: - raise ValueError( - "Authentication token must be in `query` or `header`" - ) - - def __deserialize_file(self, response): - """Deserializes body to file - - Saves response body into a file in a temporary folder, - using the filename from the `Content-Disposition` header if provided. - - :param response: RESTResponse. - :return: file path. - """ - fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) - os.close(fd) - os.remove(path) - - content_disposition = response.getheader("Content-Disposition") - if content_disposition: - filename = re.search( - r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition - ).group(1) - path = os.path.join(os.path.dirname(path), filename) - - with open(path, "wb") as f: - f.write(response.data) - - return path - - def __deserialize_primitive(self, data, klass): - """Deserializes string to primitive type. - - :param data: str. - :param klass: class literal. - - :return: int, long, float, str, bool. - """ - try: - return klass(data) - except UnicodeEncodeError: - return six.text_type(data) - except TypeError: - return data - - def __deserialize_object(self, value): - """Return an original value. - - :return: object. - """ - return value - - def __deserialize_date(self, string): - """Deserializes string to date. - - :param string: str. - :return: date. - """ - try: - from dateutil.parser import parse - - return parse(string).date() - except ImportError: - return string - except ValueError: - raise rest.ApiException( - status=0, - reason="Failed to parse `{0}` as date object".format(string), - ) - - def __deserialize_datatime(self, string): - """Deserializes string to datetime. - - The string should be in iso8601 datetime format. - - :param string: str. - :return: datetime. - """ - try: - from dateutil.parser import parse - - return parse(string) - except ImportError: - return string - except ValueError: - raise rest.ApiException( - status=0, - reason=( - "Failed to parse `{0}` as datetime object".format(string) - ), - ) - - def __deserialize_model(self, data, klass): - """Deserializes list or dict to model. - - :param data: dict, list. - :param klass: class literal. - :return: model object. - """ - - if not klass.openapi_types and not hasattr( - klass, "get_real_child_model" - ): - return data - - kwargs = {} - if klass.openapi_types is not None: - for attr, attr_type in six.iteritems(klass.openapi_types): - if ( - data is not None - and klass.attribute_map[attr] in data - and isinstance(data, (list, dict)) - ): - value = data[klass.attribute_map[attr]] - kwargs[attr] = self.__deserialize(value, attr_type) - - instance = klass(**kwargs) - - if hasattr(instance, "get_real_child_model"): - klass_name = instance.get_real_child_model(data) - if klass_name: - instance = self.__deserialize(data, klass_name) - return instance diff --git a/python-packages/sra_client/src/zero_ex/sra_client/configuration.py b/python-packages/sra_client/src/zero_ex/sra_client/configuration.py deleted file mode 100644 index 9b0cc05bbf..0000000000 --- a/python-packages/sra_client/src/zero_ex/sra_client/configuration.py +++ /dev/null @@ -1,225 +0,0 @@ -# coding: utf-8 - - -from __future__ import absolute_import - -import copy -import logging -import multiprocessing -import sys -import urllib3 - -import six -from six.moves import http_client as httplib - - -class TypeWithDefault(type): - def __init__(cls, name, bases, dct): - super(TypeWithDefault, cls).__init__(name, bases, dct) - cls._default = None - - def __call__(cls): - if cls._default is None: - cls._default = type.__call__(cls) - return copy.copy(cls._default) - - def set_default(cls, default): - cls._default = copy.copy(default) - - -class Configuration(six.with_metaclass(TypeWithDefault, object)): - """NOTE: This class is auto generated by OpenAPI Generator - - Ref: https://openapi-generator.tech - Do not edit the class manually. - """ - - def __init__(self): - """Constructor""" - # Default Base url - self.host = "http://localhost:3000" - # Temp file folder for downloading files - self.temp_folder_path = None - - # Authentication Settings - # dict to store API key(s) - self.api_key = {} - # dict to store API prefix (e.g. Bearer) - self.api_key_prefix = {} - # Username for HTTP basic authentication - self.username = "" - # Password for HTTP basic authentication - self.password = "" - - # Logging Settings - self.logger = {} - self.logger["package_logger"] = logging.getLogger("sra_client") - self.logger["urllib3_logger"] = logging.getLogger("urllib3") - # Log format - self.logger_format = "%(asctime)s %(levelname)s %(message)s" - # Log stream handler - self.logger_stream_handler = None - # Log file handler - self.logger_file_handler = None - # Debug file location - self.logger_file = None - # Debug switch - self.debug = False - - # SSL/TLS verification - # Set this to false to skip verifying SSL certificate when calling API - # from https server. - self.verify_ssl = True - # Set this to customize the certificate file to verify the peer. - self.ssl_ca_cert = None - # client certificate file - self.cert_file = None - # client key file - self.key_file = None - # Set this to True/False to enable/disable SSL hostname verification. - self.assert_hostname = None - - # urllib3 connection pool's maximum number of connections saved - # per pool. urllib3 uses 1 connection as default value, but this is - # not the best value when you are making a lot of possibly parallel - # requests to the same host, which is often the case here. - # cpu_count * 5 is used as default value to increase performance. - self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 - - # Proxy URL - self.proxy = None - # Safe chars for path_param - self.safe_chars_for_path_param = "" - - @property - def logger_file(self): - """The logger file. - - If the logger_file is None, then add stream handler and remove file - handler. Otherwise, add file handler and remove stream handler. - - :param value: The logger_file path. - :type: str - """ - return self.__logger_file - - @logger_file.setter - def logger_file(self, value): - """The logger file. - - If the logger_file is None, then add stream handler and remove file - handler. Otherwise, add file handler and remove stream handler. - - :param value: The logger_file path. - :type: str - """ - self.__logger_file = value - if self.__logger_file: - # If set logging file, - # then add file handler and remove stream handler. - self.logger_file_handler = logging.FileHandler(self.__logger_file) - self.logger_file_handler.setFormatter(self.logger_formatter) - for _, logger in six.iteritems(self.logger): - logger.addHandler(self.logger_file_handler) - - @property - def debug(self): - """Debug status - - :param value: The debug status, True or False. - :type: bool - """ - return self.__debug - - @debug.setter - def debug(self, value): - """Debug status - - :param value: The debug status, True or False. - :type: bool - """ - self.__debug = value - if self.__debug: - # if debug status is True, turn on debug logging - for _, logger in six.iteritems(self.logger): - logger.setLevel(logging.DEBUG) - # turn on httplib debug - httplib.HTTPConnection.debuglevel = 1 - else: - # if debug status is False, turn off debug logging, - # setting log level to default `logging.WARNING` - for _, logger in six.iteritems(self.logger): - logger.setLevel(logging.WARNING) - # turn off httplib debug - httplib.HTTPConnection.debuglevel = 0 - - @property - def logger_format(self): - """The logger format. - - The logger_formatter will be updated when sets logger_format. - - :param value: The format string. - :type: str - """ - return self.__logger_format - - @logger_format.setter - def logger_format(self, value): - """The logger format. - - The logger_formatter will be updated when sets logger_format. - - :param value: The format string. - :type: str - """ - self.__logger_format = value - self.logger_formatter = logging.Formatter(self.__logger_format) - - def get_api_key_with_prefix(self, identifier): - """Gets API key (with prefix if set). - - :param identifier: The identifier of apiKey. - :return: The token for api key authentication. - """ - if self.api_key.get(identifier) and self.api_key_prefix.get( - identifier - ): - return ( - self.api_key_prefix[identifier] - + " " - + self.api_key[identifier] - ) # noqa: E501 - elif self.api_key.get(identifier): - return self.api_key[identifier] - - def get_basic_auth_token(self): - """Gets HTTP basic authentication header (string). - - :return: The token for basic HTTP authentication. - """ - return urllib3.util.make_headers( - basic_auth=self.username + ":" + self.password - ).get("authorization") - - def auth_settings(self): - """Gets Auth Settings dict for api client. - - :return: The Auth Settings information dict. - """ - return {} - - def to_debug_report(self): - """Gets the essential information for debugging. - - :return: The report for debugging. - """ - return ( - "Python SDK Debug Report:\n" - "OS: {env}\n" - "Python Version: {pyversion}\n" - "Version of the API: 2.0.0\n" - "SDK Package Version: 1.0.0".format( - env=sys.platform, pyversion=sys.version - ) - ) diff --git a/python-packages/sra_client/src/zero_ex/sra_client/models/__init__.py b/python-packages/sra_client/src/zero_ex/sra_client/models/__init__.py deleted file mode 100644 index 5b078f533b..0000000000 --- a/python-packages/sra_client/src/zero_ex/sra_client/models/__init__.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding: utf-8 - -# flake8: noqa - -from __future__ import absolute_import - -# import models into model package -from zero_ex.sra_client.models.order_schema import OrderSchema -from zero_ex.sra_client.models.paginated_collection_schema import ( - PaginatedCollectionSchema, -) -from zero_ex.sra_client.models.relayer_api_asset_data_pairs_response_schema import ( - RelayerApiAssetDataPairsResponseSchema, -) -from zero_ex.sra_client.models.relayer_api_asset_data_trade_info_schema import ( - RelayerApiAssetDataTradeInfoSchema, -) -from zero_ex.sra_client.models.relayer_api_error_response_schema import ( - RelayerApiErrorResponseSchema, -) -from zero_ex.sra_client.models.relayer_api_error_response_schema_validation_errors import ( - RelayerApiErrorResponseSchemaValidationErrors, -) -from zero_ex.sra_client.models.relayer_api_fee_recipients_response_schema import ( - RelayerApiFeeRecipientsResponseSchema, -) -from zero_ex.sra_client.models.relayer_api_order_config_payload_schema import ( - RelayerApiOrderConfigPayloadSchema, -) -from zero_ex.sra_client.models.relayer_api_order_config_response_schema import ( - RelayerApiOrderConfigResponseSchema, -) -from zero_ex.sra_client.models.relayer_api_order_schema import RelayerApiOrderSchema -from zero_ex.sra_client.models.relayer_api_orderbook_response_schema import ( - RelayerApiOrderbookResponseSchema, -) -from zero_ex.sra_client.models.relayer_api_orders_channel_subscribe_payload_schema import ( - RelayerApiOrdersChannelSubscribePayloadSchema, -) -from zero_ex.sra_client.models.relayer_api_orders_channel_subscribe_schema import ( - RelayerApiOrdersChannelSubscribeSchema, -) -from zero_ex.sra_client.models.relayer_api_orders_channel_update_schema import ( - RelayerApiOrdersChannelUpdateSchema, -) -from zero_ex.sra_client.models.relayer_api_orders_response_schema import ( - RelayerApiOrdersResponseSchema, -) -from zero_ex.sra_client.models.signed_order_schema import SignedOrderSchema diff --git a/python-packages/sra_client/src/zero_ex/sra_client/models/order_schema.py b/python-packages/sra_client/src/zero_ex/sra_client/models/order_schema.py deleted file mode 100644 index 568cc7ec26..0000000000 --- a/python-packages/sra_client/src/zero_ex/sra_client/models/order_schema.py +++ /dev/null @@ -1,530 +0,0 @@ -# coding: utf-8 - - -import pprint -import re # noqa: F401 - -import six - - -class OrderSchema(object): - """ - Attributes: - openapi_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - openapi_types = {} - - attribute_map = { - "maker_address": "makerAddress", - "taker_address": "takerAddress", - "maker_fee": "makerFee", - "taker_fee": "takerFee", - "sender_address": "senderAddress", - "maker_asset_amount": "makerAssetAmount", - "taker_asset_amount": "takerAssetAmount", - "maker_asset_data": "makerAssetData", - "taker_asset_data": "takerAssetData", - "salt": "salt", - "exchange_address": "exchangeAddress", - "fee_recipient_address": "feeRecipientAddress", - "expiration_time_seconds": "expirationTimeSeconds", - } - - def __init__( - self, - maker_address=None, - taker_address=None, - maker_fee=None, - taker_fee=None, - sender_address=None, - maker_asset_amount=None, - taker_asset_amount=None, - maker_asset_data=None, - taker_asset_data=None, - salt=None, - exchange_address=None, - fee_recipient_address=None, - expiration_time_seconds=None, - ): # noqa: E501 - """OrderSchema - a model defined in OpenAPI""" # noqa: E501 - - self._maker_address = None - self._taker_address = None - self._maker_fee = None - self._taker_fee = None - self._sender_address = None - self._maker_asset_amount = None - self._taker_asset_amount = None - self._maker_asset_data = None - self._taker_asset_data = None - self._salt = None - self._exchange_address = None - self._fee_recipient_address = None - self._expiration_time_seconds = None - self.discriminator = None - - self.maker_address = maker_address - self.taker_address = taker_address - self.maker_fee = maker_fee - self.taker_fee = taker_fee - self.sender_address = sender_address - self.maker_asset_amount = maker_asset_amount - self.taker_asset_amount = taker_asset_amount - self.maker_asset_data = maker_asset_data - self.taker_asset_data = taker_asset_data - self.salt = salt - self.exchange_address = exchange_address - self.fee_recipient_address = fee_recipient_address - self.expiration_time_seconds = expiration_time_seconds - - @property - def maker_address(self): - """Gets the maker_address of this OrderSchema. # noqa: E501 - - - :return: The maker_address of this OrderSchema. # noqa: E501 - :rtype: str - """ - return self._maker_address - - @maker_address.setter - def maker_address(self, maker_address): - """Sets the maker_address of this OrderSchema. - - - :param maker_address: The maker_address of this OrderSchema. # noqa: E501 - :type: str - """ - if maker_address is None: - raise ValueError( - "Invalid value for `maker_address`, must not be `None`" - ) # noqa: E501 - if maker_address is not None and not re.search( - r"^0x[0-9a-f]{40}$", maker_address - ): # noqa: E501 - raise ValueError( - r"Invalid value for `maker_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`" - ) # noqa: E501 - - self._maker_address = maker_address - - @property - def taker_address(self): - """Gets the taker_address of this OrderSchema. # noqa: E501 - - - :return: The taker_address of this OrderSchema. # noqa: E501 - :rtype: str - """ - return self._taker_address - - @taker_address.setter - def taker_address(self, taker_address): - """Sets the taker_address of this OrderSchema. - - - :param taker_address: The taker_address of this OrderSchema. # noqa: E501 - :type: str - """ - if taker_address is None: - raise ValueError( - "Invalid value for `taker_address`, must not be `None`" - ) # noqa: E501 - if taker_address is not None and not re.search( - r"^0x[0-9a-f]{40}$", taker_address - ): # noqa: E501 - raise ValueError( - r"Invalid value for `taker_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`" - ) # noqa: E501 - - self._taker_address = taker_address - - @property - def maker_fee(self): - """Gets the maker_fee of this OrderSchema. # noqa: E501 - - - :return: The maker_fee of this OrderSchema. # noqa: E501 - :rtype: str - """ - return self._maker_fee - - @maker_fee.setter - def maker_fee(self, maker_fee): - """Sets the maker_fee of this OrderSchema. - - - :param maker_fee: The maker_fee of this OrderSchema. # noqa: E501 - :type: str - """ - if maker_fee is None: - raise ValueError( - "Invalid value for `maker_fee`, must not be `None`" - ) # noqa: E501 - if maker_fee is not None and not re.search( - r"^\d+$", maker_fee - ): # noqa: E501 - raise ValueError( - r"Invalid value for `maker_fee`, must be a follow pattern or equal to `/^\d+$/`" - ) # noqa: E501 - - self._maker_fee = maker_fee - - @property - def taker_fee(self): - """Gets the taker_fee of this OrderSchema. # noqa: E501 - - - :return: The taker_fee of this OrderSchema. # noqa: E501 - :rtype: str - """ - return self._taker_fee - - @taker_fee.setter - def taker_fee(self, taker_fee): - """Sets the taker_fee of this OrderSchema. - - - :param taker_fee: The taker_fee of this OrderSchema. # noqa: E501 - :type: str - """ - if taker_fee is None: - raise ValueError( - "Invalid value for `taker_fee`, must not be `None`" - ) # noqa: E501 - if taker_fee is not None and not re.search( - r"^\d+$", taker_fee - ): # noqa: E501 - raise ValueError( - r"Invalid value for `taker_fee`, must be a follow pattern or equal to `/^\d+$/`" - ) # noqa: E501 - - self._taker_fee = taker_fee - - @property - def sender_address(self): - """Gets the sender_address of this OrderSchema. # noqa: E501 - - - :return: The sender_address of this OrderSchema. # noqa: E501 - :rtype: str - """ - return self._sender_address - - @sender_address.setter - def sender_address(self, sender_address): - """Sets the sender_address of this OrderSchema. - - - :param sender_address: The sender_address of this OrderSchema. # noqa: E501 - :type: str - """ - if sender_address is None: - raise ValueError( - "Invalid value for `sender_address`, must not be `None`" - ) # noqa: E501 - if sender_address is not None and not re.search( - r"^0x[0-9a-f]{40}$", sender_address - ): # noqa: E501 - raise ValueError( - r"Invalid value for `sender_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`" - ) # noqa: E501 - - self._sender_address = sender_address - - @property - def maker_asset_amount(self): - """Gets the maker_asset_amount of this OrderSchema. # noqa: E501 - - - :return: The maker_asset_amount of this OrderSchema. # noqa: E501 - :rtype: str - """ - return self._maker_asset_amount - - @maker_asset_amount.setter - def maker_asset_amount(self, maker_asset_amount): - """Sets the maker_asset_amount of this OrderSchema. - - - :param maker_asset_amount: The maker_asset_amount of this OrderSchema. # noqa: E501 - :type: str - """ - if maker_asset_amount is None: - raise ValueError( - "Invalid value for `maker_asset_amount`, must not be `None`" - ) # noqa: E501 - if maker_asset_amount is not None and not re.search( - r"^\d+$", maker_asset_amount - ): # noqa: E501 - raise ValueError( - r"Invalid value for `maker_asset_amount`, must be a follow pattern or equal to `/^\d+$/`" - ) # noqa: E501 - - self._maker_asset_amount = maker_asset_amount - - @property - def taker_asset_amount(self): - """Gets the taker_asset_amount of this OrderSchema. # noqa: E501 - - - :return: The taker_asset_amount of this OrderSchema. # noqa: E501 - :rtype: str - """ - return self._taker_asset_amount - - @taker_asset_amount.setter - def taker_asset_amount(self, taker_asset_amount): - """Sets the taker_asset_amount of this OrderSchema. - - - :param taker_asset_amount: The taker_asset_amount of this OrderSchema. # noqa: E501 - :type: str - """ - if taker_asset_amount is None: - raise ValueError( - "Invalid value for `taker_asset_amount`, must not be `None`" - ) # noqa: E501 - if taker_asset_amount is not None and not re.search( - r"^\d+$", taker_asset_amount - ): # noqa: E501 - raise ValueError( - r"Invalid value for `taker_asset_amount`, must be a follow pattern or equal to `/^\d+$/`" - ) # noqa: E501 - - self._taker_asset_amount = taker_asset_amount - - @property - def maker_asset_data(self): - """Gets the maker_asset_data of this OrderSchema. # noqa: E501 - - - :return: The maker_asset_data of this OrderSchema. # noqa: E501 - :rtype: str - """ - return self._maker_asset_data - - @maker_asset_data.setter - def maker_asset_data(self, maker_asset_data): - """Sets the maker_asset_data of this OrderSchema. - - - :param maker_asset_data: The maker_asset_data of this OrderSchema. # noqa: E501 - :type: str - """ - if maker_asset_data is None: - raise ValueError( - "Invalid value for `maker_asset_data`, must not be `None`" - ) # noqa: E501 - if maker_asset_data is not None and not re.search( - r"^0x(([0-9a-f][0-9a-f])+)?$", maker_asset_data - ): # noqa: E501 - raise ValueError( - r"Invalid value for `maker_asset_data`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`" - ) # noqa: E501 - - self._maker_asset_data = maker_asset_data - - @property - def taker_asset_data(self): - """Gets the taker_asset_data of this OrderSchema. # noqa: E501 - - - :return: The taker_asset_data of this OrderSchema. # noqa: E501 - :rtype: str - """ - return self._taker_asset_data - - @taker_asset_data.setter - def taker_asset_data(self, taker_asset_data): - """Sets the taker_asset_data of this OrderSchema. - - - :param taker_asset_data: The taker_asset_data of this OrderSchema. # noqa: E501 - :type: str - """ - if taker_asset_data is None: - raise ValueError( - "Invalid value for `taker_asset_data`, must not be `None`" - ) # noqa: E501 - if taker_asset_data is not None and not re.search( - r"^0x(([0-9a-f][0-9a-f])+)?$", taker_asset_data - ): # noqa: E501 - raise ValueError( - r"Invalid value for `taker_asset_data`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`" - ) # noqa: E501 - - self._taker_asset_data = taker_asset_data - - @property - def salt(self): - """Gets the salt of this OrderSchema. # noqa: E501 - - - :return: The salt of this OrderSchema. # noqa: E501 - :rtype: str - """ - return self._salt - - @salt.setter - def salt(self, salt): - """Sets the salt of this OrderSchema. - - - :param salt: The salt of this OrderSchema. # noqa: E501 - :type: str - """ - if salt is None: - raise ValueError( - "Invalid value for `salt`, must not be `None`" - ) # noqa: E501 - if salt is not None and not re.search(r"^\d+$", salt): # noqa: E501 - raise ValueError( - r"Invalid value for `salt`, must be a follow pattern or equal to `/^\d+$/`" - ) # noqa: E501 - - self._salt = salt - - @property - def exchange_address(self): - """Gets the exchange_address of this OrderSchema. # noqa: E501 - - - :return: The exchange_address of this OrderSchema. # noqa: E501 - :rtype: str - """ - return self._exchange_address - - @exchange_address.setter - def exchange_address(self, exchange_address): - """Sets the exchange_address of this OrderSchema. - - - :param exchange_address: The exchange_address of this OrderSchema. # noqa: E501 - :type: str - """ - if exchange_address is None: - raise ValueError( - "Invalid value for `exchange_address`, must not be `None`" - ) # noqa: E501 - if exchange_address is not None and not re.search( - r"^0x[0-9a-f]{40}$", exchange_address - ): # noqa: E501 - raise ValueError( - r"Invalid value for `exchange_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`" - ) # noqa: E501 - - self._exchange_address = exchange_address - - @property - def fee_recipient_address(self): - """Gets the fee_recipient_address of this OrderSchema. # noqa: E501 - - - :return: The fee_recipient_address of this OrderSchema. # noqa: E501 - :rtype: str - """ - return self._fee_recipient_address - - @fee_recipient_address.setter - def fee_recipient_address(self, fee_recipient_address): - """Sets the fee_recipient_address of this OrderSchema. - - - :param fee_recipient_address: The fee_recipient_address of this OrderSchema. # noqa: E501 - :type: str - """ - if fee_recipient_address is None: - raise ValueError( - "Invalid value for `fee_recipient_address`, must not be `None`" - ) # noqa: E501 - if fee_recipient_address is not None and not re.search( - r"^0x[0-9a-f]{40}$", fee_recipient_address - ): # noqa: E501 - raise ValueError( - r"Invalid value for `fee_recipient_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`" - ) # noqa: E501 - - self._fee_recipient_address = fee_recipient_address - - @property - def expiration_time_seconds(self): - """Gets the expiration_time_seconds of this OrderSchema. # noqa: E501 - - - :return: The expiration_time_seconds of this OrderSchema. # noqa: E501 - :rtype: str - """ - return self._expiration_time_seconds - - @expiration_time_seconds.setter - def expiration_time_seconds(self, expiration_time_seconds): - """Sets the expiration_time_seconds of this OrderSchema. - - - :param expiration_time_seconds: The expiration_time_seconds of this OrderSchema. # noqa: E501 - :type: str - """ - if expiration_time_seconds is None: - raise ValueError( - "Invalid value for `expiration_time_seconds`, must not be `None`" - ) # noqa: E501 - if expiration_time_seconds is not None and not re.search( - r"^\d+$", expiration_time_seconds - ): # noqa: E501 - raise ValueError( - r"Invalid value for `expiration_time_seconds`, must be a follow pattern or equal to `/^\d+$/`" - ) # noqa: E501 - - self._expiration_time_seconds = expiration_time_seconds - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list( - map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value, - ) - ) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict( - map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") - else item, - value.items(), - ) - ) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, OrderSchema): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python-packages/sra_client/src/zero_ex/sra_client/models/paginated_collection_schema.py b/python-packages/sra_client/src/zero_ex/sra_client/models/paginated_collection_schema.py deleted file mode 100644 index 4a327b0040..0000000000 --- a/python-packages/sra_client/src/zero_ex/sra_client/models/paginated_collection_schema.py +++ /dev/null @@ -1,155 +0,0 @@ -# coding: utf-8 - - -import pprint -import re # noqa: F401 - -import six - - -class PaginatedCollectionSchema(object): - """ - Attributes: - openapi_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - openapi_types = {"total": "float", "per_page": "float", "page": "float"} - - attribute_map = {"total": "total", "per_page": "perPage", "page": "page"} - - def __init__(self, total=None, per_page=None, page=None): # noqa: E501 - """PaginatedCollectionSchema - a model defined in OpenAPI""" # noqa: E501 - - self._total = None - self._per_page = None - self._page = None - self.discriminator = None - - self.total = total - self.per_page = per_page - self.page = page - - @property - def total(self): - """Gets the total of this PaginatedCollectionSchema. # noqa: E501 - - - :return: The total of this PaginatedCollectionSchema. # noqa: E501 - :rtype: float - """ - return self._total - - @total.setter - def total(self, total): - """Sets the total of this PaginatedCollectionSchema. - - - :param total: The total of this PaginatedCollectionSchema. # noqa: E501 - :type: float - """ - if total is None: - raise ValueError( - "Invalid value for `total`, must not be `None`" - ) # noqa: E501 - - self._total = total - - @property - def per_page(self): - """Gets the per_page of this PaginatedCollectionSchema. # noqa: E501 - - - :return: The per_page of this PaginatedCollectionSchema. # noqa: E501 - :rtype: float - """ - return self._per_page - - @per_page.setter - def per_page(self, per_page): - """Sets the per_page of this PaginatedCollectionSchema. - - - :param per_page: The per_page of this PaginatedCollectionSchema. # noqa: E501 - :type: float - """ - if per_page is None: - raise ValueError( - "Invalid value for `per_page`, must not be `None`" - ) # noqa: E501 - - self._per_page = per_page - - @property - def page(self): - """Gets the page of this PaginatedCollectionSchema. # noqa: E501 - - - :return: The page of this PaginatedCollectionSchema. # noqa: E501 - :rtype: float - """ - return self._page - - @page.setter - def page(self, page): - """Sets the page of this PaginatedCollectionSchema. - - - :param page: The page of this PaginatedCollectionSchema. # noqa: E501 - :type: float - """ - if page is None: - raise ValueError( - "Invalid value for `page`, must not be `None`" - ) # noqa: E501 - - self._page = page - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list( - map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value, - ) - ) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict( - map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") - else item, - value.items(), - ) - ) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, PaginatedCollectionSchema): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_asset_data_pairs_response_schema.py b/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_asset_data_pairs_response_schema.py deleted file mode 100644 index cc5cea4751..0000000000 --- a/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_asset_data_pairs_response_schema.py +++ /dev/null @@ -1,99 +0,0 @@ -# coding: utf-8 - - -import pprint -import re # noqa: F401 - -import six - - -class RelayerApiAssetDataPairsResponseSchema(object): - """ - Attributes: - openapi_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - openapi_types = {"records": "list[object]"} - - attribute_map = {"records": "records"} - - def __init__(self, records=None): # noqa: E501 - """RelayerApiAssetDataPairsResponseSchema - a model defined in OpenAPI""" # noqa: E501 - - self._records = None - self.discriminator = None - - self.records = records - - @property - def records(self): - """Gets the records of this RelayerApiAssetDataPairsResponseSchema. - - :return: The records of this RelayerApiAssetDataPairsResponseSchema. - :rtype: list[object] - """ - return self._records - - @records.setter - def records(self, records): - """Sets the records of this RelayerApiAssetDataPairsResponseSchema. - - :param records: The records of this RelayerApiAssetDataPairsResponseSchema. - :type: list[object] - """ - if records is None: - raise ValueError( - "Invalid value for `records`, must not be `None`" - ) # noqa: E501 - - self._records = records - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list( - map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value, - ) - ) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict( - map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") - else item, - value.items(), - ) - ) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, RelayerApiAssetDataPairsResponseSchema): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_asset_data_trade_info_schema.py b/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_asset_data_trade_info_schema.py deleted file mode 100644 index 387642678c..0000000000 --- a/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_asset_data_trade_info_schema.py +++ /dev/null @@ -1,203 +0,0 @@ -# coding: utf-8 - - -import pprint -import re # noqa: F401 - -import six - - -class RelayerApiAssetDataTradeInfoSchema(object): - """ - Attributes: - openapi_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - openapi_types = { - "asset_data": "str", - "min_amount": "str", - "max_amount": "str", - "precision": "float", - } - - attribute_map = { - "asset_data": "assetData", - "min_amount": "minAmount", - "max_amount": "maxAmount", - "precision": "precision", - } - - def __init__( - self, asset_data=None, min_amount=None, max_amount=None, precision=None - ): # noqa: E501 - """RelayerApiAssetDataTradeInfoSchema - a model defined in OpenAPI""" # noqa: E501 - - self._asset_data = None - self._min_amount = None - self._max_amount = None - self._precision = None - self.discriminator = None - - self.asset_data = asset_data - if min_amount is not None: - self.min_amount = min_amount - if max_amount is not None: - self.max_amount = max_amount - if precision is not None: - self.precision = precision - - @property - def asset_data(self): - """Gets the asset_data of this RelayerApiAssetDataTradeInfoSchema. - - - :return: The asset_data of this RelayerApiAssetDataTradeInfoSchema. - :rtype: str - """ - return self._asset_data - - @asset_data.setter - def asset_data(self, asset_data): - """Sets the asset_data of this RelayerApiAssetDataTradeInfoSchema. - - - :param asset_data: The asset_data of this RelayerApiAssetDataTradeInfoSchema. - :type: str - """ - if asset_data is None: - raise ValueError( - "Invalid value for `asset_data`, must not be `None`" - ) # noqa: E501 - if asset_data is not None and not re.search( - r"^0x(([0-9a-f][0-9a-f])+)?$", asset_data - ): # noqa: E501 - raise ValueError( - r"Invalid value for `asset_data`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`" - ) # noqa: E501 - - self._asset_data = asset_data - - @property - def min_amount(self): - """Gets the min_amount of this RelayerApiAssetDataTradeInfoSchema. - - - :return: The min_amount of this RelayerApiAssetDataTradeInfoSchema. - :rtype: str - """ - return self._min_amount - - @min_amount.setter - def min_amount(self, min_amount): - """Sets the min_amount of this RelayerApiAssetDataTradeInfoSchema. - - - :param min_amount: The min_amount of this RelayerApiAssetDataTradeInfoSchema. - :type: str - """ - if min_amount is not None and not re.search( - r"^\d+$", min_amount - ): # noqa: E501 - raise ValueError( - r"Invalid value for `min_amount`, must be a follow pattern or equal to `/^\d+$/`" - ) # noqa: E501 - - self._min_amount = min_amount - - @property - def max_amount(self): - """Gets the max_amount of this RelayerApiAssetDataTradeInfoSchema. - - - :return: The max_amount of this RelayerApiAssetDataTradeInfoSchema. - :rtype: str - """ - return self._max_amount - - @max_amount.setter - def max_amount(self, max_amount): - """Sets the max_amount of this RelayerApiAssetDataTradeInfoSchema. - - - :param max_amount: The max_amount of this RelayerApiAssetDataTradeInfoSchema. - :type: str - """ - if max_amount is not None and not re.search( - r"^\d+$", max_amount - ): # noqa: E501 - raise ValueError( - r"Invalid value for `max_amount`, must be a follow pattern or equal to `/^\d+$/`" - ) # noqa: E501 - - self._max_amount = max_amount - - @property - def precision(self): - """Gets the precision of this RelayerApiAssetDataTradeInfoSchema. - - - :return: The precision of this RelayerApiAssetDataTradeInfoSchema. - :rtype: float - """ - return self._precision - - @precision.setter - def precision(self, precision): - """Sets the precision of this RelayerApiAssetDataTradeInfoSchema. - - - :param precision: The precision of this RelayerApiAssetDataTradeInfoSchema. - :type: float - """ - - self._precision = precision - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list( - map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value, - ) - ) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict( - map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") - else item, - value.items(), - ) - ) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, RelayerApiAssetDataTradeInfoSchema): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_error_response_schema.py b/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_error_response_schema.py deleted file mode 100644 index db21a30514..0000000000 --- a/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_error_response_schema.py +++ /dev/null @@ -1,170 +0,0 @@ -# coding: utf-8 - - -import pprint -import re # noqa: F401 - -import six - - -class RelayerApiErrorResponseSchema(object): - """ - Attributes: - openapi_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - openapi_types = { - "code": "int", - "reason": "str", - "validation_errors": "list[RelayerApiErrorResponseSchemaValidationErrors]", - } - - attribute_map = { - "code": "code", - "reason": "reason", - "validation_errors": "validationErrors", - } - - def __init__( - self, code=None, reason=None, validation_errors=None - ): # noqa: E501 - """RelayerApiErrorResponseSchema - a model defined in OpenAPI""" # noqa: E501 - - self._code = None - self._reason = None - self._validation_errors = None - self.discriminator = None - - self.code = code - self.reason = reason - if validation_errors is not None: - self.validation_errors = validation_errors - - @property - def code(self): - """Gets the code of this RelayerApiErrorResponseSchema. - - - :return: The code of this RelayerApiErrorResponseSchema. - :rtype: int - """ - return self._code - - @code.setter - def code(self, code): - """Sets the code of this RelayerApiErrorResponseSchema. - - - :param code: The code of this RelayerApiErrorResponseSchema. - :type: int - """ - if code is None: - raise ValueError( - "Invalid value for `code`, must not be `None`" - ) # noqa: E501 - if code is not None and code > 103: # noqa: E501 - raise ValueError( - "Invalid value for `code`, must be a value less than or equal to `103`" - ) # noqa: E501 - if code is not None and code < 100: # noqa: E501 - raise ValueError( - "Invalid value for `code`, must be a value greater than or equal to `100`" - ) # noqa: E501 - - self._code = code - - @property - def reason(self): - """Gets the reason of this RelayerApiErrorResponseSchema. - - - :return: The reason of this RelayerApiErrorResponseSchema. - :rtype: str - """ - return self._reason - - @reason.setter - def reason(self, reason): - """Sets the reason of this RelayerApiErrorResponseSchema. - - - :param reason: The reason of this RelayerApiErrorResponseSchema. - :type: str - """ - if reason is None: - raise ValueError( - "Invalid value for `reason`, must not be `None`" - ) # noqa: E501 - - self._reason = reason - - @property - def validation_errors(self): - """Gets the validation_errors of this RelayerApiErrorResponseSchema. - - - :return: The validation_errors of this RelayerApiErrorResponseSchema. - :rtype: list[RelayerApiErrorResponseSchemaValidationErrors] - """ - return self._validation_errors - - @validation_errors.setter - def validation_errors(self, validation_errors): - """Sets the validation_errors of this RelayerApiErrorResponseSchema. - - - :param validation_errors: The validation_errors of this RelayerApiErrorResponseSchema. - :type: list[RelayerApiErrorResponseSchemaValidationErrors] - """ - - self._validation_errors = validation_errors - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list( - map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value, - ) - ) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict( - map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") - else item, - value.items(), - ) - ) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, RelayerApiErrorResponseSchema): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_error_response_schema_validation_errors.py b/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_error_response_schema_validation_errors.py deleted file mode 100644 index df7cb705f5..0000000000 --- a/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_error_response_schema_validation_errors.py +++ /dev/null @@ -1,165 +0,0 @@ -# coding: utf-8 - - -import pprint -import re # noqa: F401 - -import six - - -class RelayerApiErrorResponseSchemaValidationErrors(object): - """ - Attributes: - openapi_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - openapi_types = {"field": "str", "code": "int", "reason": "str"} - - attribute_map = {"field": "field", "code": "code", "reason": "reason"} - - def __init__(self, field=None, code=None, reason=None): # noqa: E501 - """RelayerApiErrorResponseSchemaValidationErrors - a model defined in OpenAPI""" # noqa: E501 - - self._field = None - self._code = None - self._reason = None - self.discriminator = None - - self.field = field - self.code = code - self.reason = reason - - @property - def field(self): - """Gets the field of this RelayerApiErrorResponseSchemaValidationErrors. - - - :return: The field of this RelayerApiErrorResponseSchemaValidationErrors. - :rtype: str - """ - return self._field - - @field.setter - def field(self, field): - """Sets the field of this RelayerApiErrorResponseSchemaValidationErrors. - - - :param field: The field of this RelayerApiErrorResponseSchemaValidationErrors. - :type: str - """ - if field is None: - raise ValueError( - "Invalid value for `field`, must not be `None`" - ) # noqa: E501 - - self._field = field - - @property - def code(self): - """Gets the code of this RelayerApiErrorResponseSchemaValidationErrors. - - - :return: The code of this RelayerApiErrorResponseSchemaValidationErrors. - :rtype: int - """ - return self._code - - @code.setter - def code(self, code): - """Sets the code of this RelayerApiErrorResponseSchemaValidationErrors. - - - :param code: The code of this RelayerApiErrorResponseSchemaValidationErrors. - :type: int - """ - if code is None: - raise ValueError( - "Invalid value for `code`, must not be `None`" - ) # noqa: E501 - if code is not None and code > 1006: # noqa: E501 - raise ValueError( - "Invalid value for `code`, must be a value less than or equal to `1006`" - ) # noqa: E501 - if code is not None and code < 1000: # noqa: E501 - raise ValueError( - "Invalid value for `code`, must be a value greater than or equal to `1000`" - ) # noqa: E501 - - self._code = code - - @property - def reason(self): - """Gets the reason of this RelayerApiErrorResponseSchemaValidationErrors. - - - :return: The reason of this RelayerApiErrorResponseSchemaValidationErrors. - :rtype: str - """ - return self._reason - - @reason.setter - def reason(self, reason): - """Sets the reason of this RelayerApiErrorResponseSchemaValidationErrors. - - - :param reason: The reason of this RelayerApiErrorResponseSchemaValidationErrors. - :type: str - """ - if reason is None: - raise ValueError( - "Invalid value for `reason`, must not be `None`" - ) # noqa: E501 - - self._reason = reason - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list( - map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value, - ) - ) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict( - map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") - else item, - value.items(), - ) - ) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance( - other, RelayerApiErrorResponseSchemaValidationErrors - ): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_fee_recipients_response_schema.py b/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_fee_recipients_response_schema.py deleted file mode 100644 index c7e3444617..0000000000 --- a/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_fee_recipients_response_schema.py +++ /dev/null @@ -1,101 +0,0 @@ -# coding: utf-8 - - -import pprint -import re # noqa: F401 - -import six - - -class RelayerApiFeeRecipientsResponseSchema(object): - """ - Attributes: - openapi_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - openapi_types = {"records": "list[str]"} - - attribute_map = {"records": "records"} - - def __init__(self, records=None): # noqa: E501 - """RelayerApiFeeRecipientsResponseSchema - a model defined in OpenAPI""" # noqa: E501 - - self._records = None - self.discriminator = None - - self.records = records - - @property - def records(self): - """Gets the records of this RelayerApiFeeRecipientsResponseSchema. - - - :return: The records of this RelayerApiFeeRecipientsResponseSchema. - :rtype: list[str] - """ - return self._records - - @records.setter - def records(self, records): - """Sets the records of this RelayerApiFeeRecipientsResponseSchema. - - - :param records: The records of this RelayerApiFeeRecipientsResponseSchema. - :type: list[str] - """ - if records is None: - raise ValueError( - "Invalid value for `records`, must not be `None`" - ) # noqa: E501 - - self._records = records - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list( - map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value, - ) - ) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict( - map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") - else item, - value.items(), - ) - ) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, RelayerApiFeeRecipientsResponseSchema): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_order_config_payload_schema.py b/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_order_config_payload_schema.py deleted file mode 100644 index acebf6a7a6..0000000000 --- a/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_order_config_payload_schema.py +++ /dev/null @@ -1,366 +0,0 @@ -# coding: utf-8 - - -import pprint -import re # noqa: F401 - -import six - - -class RelayerApiOrderConfigPayloadSchema(object): - """ - Attributes: - openapi_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - openapi_types = { - "maker_address": "str", - "taker_address": "str", - "maker_asset_amount": "str", - "taker_asset_amount": "str", - "maker_asset_data": "str", - "taker_asset_data": "str", - "exchange_address": "str", - "expiration_time_seconds": "str", - } - - attribute_map = { - "maker_address": "makerAddress", - "taker_address": "takerAddress", - "maker_asset_amount": "makerAssetAmount", - "taker_asset_amount": "takerAssetAmount", - "maker_asset_data": "makerAssetData", - "taker_asset_data": "takerAssetData", - "exchange_address": "exchangeAddress", - "expiration_time_seconds": "expirationTimeSeconds", - } - - def __init__( - self, - maker_address=None, - taker_address=None, - maker_asset_amount=None, - taker_asset_amount=None, - maker_asset_data=None, - taker_asset_data=None, - exchange_address=None, - expiration_time_seconds=None, - ): # noqa: E501 - """RelayerApiOrderConfigPayloadSchema - a model defined in OpenAPI""" # noqa: E501 - - self._maker_address = None - self._taker_address = None - self._maker_asset_amount = None - self._taker_asset_amount = None - self._maker_asset_data = None - self._taker_asset_data = None - self._exchange_address = None - self._expiration_time_seconds = None - self.discriminator = None - - self.maker_address = maker_address - self.taker_address = taker_address - self.maker_asset_amount = maker_asset_amount - self.taker_asset_amount = taker_asset_amount - self.maker_asset_data = maker_asset_data - self.taker_asset_data = taker_asset_data - self.exchange_address = exchange_address - self.expiration_time_seconds = expiration_time_seconds - - @property - def maker_address(self): - """Gets the maker_address of this RelayerApiOrderConfigPayloadSchema. - - - :return: The maker_address of this RelayerApiOrderConfigPayloadSchema. - :rtype: str - """ - return self._maker_address - - @maker_address.setter - def maker_address(self, maker_address): - """Sets the maker_address of this RelayerApiOrderConfigPayloadSchema. - - - :param maker_address: The maker_address of this RelayerApiOrderConfigPayloadSchema. - :type: str - """ - if maker_address is None: - raise ValueError( - "Invalid value for `maker_address`, must not be `None`" - ) # noqa: E501 - if maker_address is not None and not re.search( - r"^0x[0-9a-f]{40}$", maker_address - ): # noqa: E501 - raise ValueError( - r"Invalid value for `maker_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`" - ) # noqa: E501 - - self._maker_address = maker_address - - @property - def taker_address(self): - """Gets the taker_address of this RelayerApiOrderConfigPayloadSchema. - - - :return: The taker_address of this RelayerApiOrderConfigPayloadSchema. - :rtype: str - """ - return self._taker_address - - @taker_address.setter - def taker_address(self, taker_address): - """Sets the taker_address of this RelayerApiOrderConfigPayloadSchema. - - - :param taker_address: The taker_address of this RelayerApiOrderConfigPayloadSchema. - :type: str - """ - if taker_address is None: - raise ValueError( - "Invalid value for `taker_address`, must not be `None`" - ) # noqa: E501 - if taker_address is not None and not re.search( - r"^0x[0-9a-f]{40}$", taker_address - ): # noqa: E501 - raise ValueError( - r"Invalid value for `taker_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`" - ) # noqa: E501 - - self._taker_address = taker_address - - @property - def maker_asset_amount(self): - """Gets the maker_asset_amount of this RelayerApiOrderConfigPayloadSchema. - - - :return: The maker_asset_amount of this RelayerApiOrderConfigPayloadSchema. - :rtype: str - """ - return self._maker_asset_amount - - @maker_asset_amount.setter - def maker_asset_amount(self, maker_asset_amount): - """Sets the maker_asset_amount of this RelayerApiOrderConfigPayloadSchema. - - - :param maker_asset_amount: The maker_asset_amount of this RelayerApiOrderConfigPayloadSchema. - :type: str - """ - if maker_asset_amount is None: - raise ValueError( - "Invalid value for `maker_asset_amount`, must not be `None`" - ) # noqa: E501 - if maker_asset_amount is not None and not re.search( - r"^\d+$", maker_asset_amount - ): # noqa: E501 - raise ValueError( - r"Invalid value for `maker_asset_amount`, must be a follow pattern or equal to `/^\d+$/`" - ) # noqa: E501 - - self._maker_asset_amount = maker_asset_amount - - @property - def taker_asset_amount(self): - """Gets the taker_asset_amount of this RelayerApiOrderConfigPayloadSchema. - - - :return: The taker_asset_amount of this RelayerApiOrderConfigPayloadSchema. - :rtype: str - """ - return self._taker_asset_amount - - @taker_asset_amount.setter - def taker_asset_amount(self, taker_asset_amount): - """Sets the taker_asset_amount of this RelayerApiOrderConfigPayloadSchema. - - - :param taker_asset_amount: The taker_asset_amount of this RelayerApiOrderConfigPayloadSchema. - :type: str - """ - if taker_asset_amount is None: - raise ValueError( - "Invalid value for `taker_asset_amount`, must not be `None`" - ) # noqa: E501 - if taker_asset_amount is not None and not re.search( - r"^\d+$", taker_asset_amount - ): # noqa: E501 - raise ValueError( - r"Invalid value for `taker_asset_amount`, must be a follow pattern or equal to `/^\d+$/`" - ) # noqa: E501 - - self._taker_asset_amount = taker_asset_amount - - @property - def maker_asset_data(self): - """Gets the maker_asset_data of this RelayerApiOrderConfigPayloadSchema. - - - :return: The maker_asset_data of this RelayerApiOrderConfigPayloadSchema. - :rtype: str - """ - return self._maker_asset_data - - @maker_asset_data.setter - def maker_asset_data(self, maker_asset_data): - """Sets the maker_asset_data of this RelayerApiOrderConfigPayloadSchema. - - - :param maker_asset_data: The maker_asset_data of this RelayerApiOrderConfigPayloadSchema. - :type: str - """ - if maker_asset_data is None: - raise ValueError( - "Invalid value for `maker_asset_data`, must not be `None`" - ) # noqa: E501 - if maker_asset_data is not None and not re.search( - r"^0x(([0-9a-f][0-9a-f])+)?$", maker_asset_data - ): # noqa: E501 - raise ValueError( - r"Invalid value for `maker_asset_data`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`" - ) # noqa: E501 - - self._maker_asset_data = maker_asset_data - - @property - def taker_asset_data(self): - """Gets the taker_asset_data of this RelayerApiOrderConfigPayloadSchema. - - - :return: The taker_asset_data of this RelayerApiOrderConfigPayloadSchema. - :rtype: str - """ - return self._taker_asset_data - - @taker_asset_data.setter - def taker_asset_data(self, taker_asset_data): - """Sets the taker_asset_data of this RelayerApiOrderConfigPayloadSchema. - - - :param taker_asset_data: The taker_asset_data of this RelayerApiOrderConfigPayloadSchema. - :type: str - """ - if taker_asset_data is None: - raise ValueError( - "Invalid value for `taker_asset_data`, must not be `None`" - ) # noqa: E501 - if taker_asset_data is not None and not re.search( - r"^0x(([0-9a-f][0-9a-f])+)?$", taker_asset_data - ): # noqa: E501 - raise ValueError( - r"Invalid value for `taker_asset_data`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`" - ) # noqa: E501 - - self._taker_asset_data = taker_asset_data - - @property - def exchange_address(self): - """Gets the exchange_address of this RelayerApiOrderConfigPayloadSchema. - - - :return: The exchange_address of this RelayerApiOrderConfigPayloadSchema. - :rtype: str - """ - return self._exchange_address - - @exchange_address.setter - def exchange_address(self, exchange_address): - """Sets the exchange_address of this RelayerApiOrderConfigPayloadSchema. - - - :param exchange_address: The exchange_address of this RelayerApiOrderConfigPayloadSchema. - :type: str - """ - if exchange_address is None: - raise ValueError( - "Invalid value for `exchange_address`, must not be `None`" - ) # noqa: E501 - if exchange_address is not None and not re.search( - r"^0x[0-9a-f]{40}$", exchange_address - ): # noqa: E501 - raise ValueError( - r"Invalid value for `exchange_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`" - ) # noqa: E501 - - self._exchange_address = exchange_address - - @property - def expiration_time_seconds(self): - """Gets the expiration_time_seconds of this RelayerApiOrderConfigPayloadSchema. - - - :return: The expiration_time_seconds of this RelayerApiOrderConfigPayloadSchema. - :rtype: str - """ - return self._expiration_time_seconds - - @expiration_time_seconds.setter - def expiration_time_seconds(self, expiration_time_seconds): - """Sets the expiration_time_seconds of this RelayerApiOrderConfigPayloadSchema. - - - :param expiration_time_seconds: The expiration_time_seconds of this RelayerApiOrderConfigPayloadSchema. - :type: str - """ - if expiration_time_seconds is None: - raise ValueError( - "Invalid value for `expiration_time_seconds`, must not be `None`" - ) # noqa: E501 - if expiration_time_seconds is not None and not re.search( - r"^\d+$", expiration_time_seconds - ): # noqa: E501 - raise ValueError( - r"Invalid value for `expiration_time_seconds`, must be a follow pattern or equal to `/^\d+$/`" - ) # noqa: E501 - - self._expiration_time_seconds = expiration_time_seconds - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list( - map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value, - ) - ) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict( - map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") - else item, - value.items(), - ) - ) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, RelayerApiOrderConfigPayloadSchema): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_order_config_response_schema.py b/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_order_config_response_schema.py deleted file mode 100644 index 4e39699be4..0000000000 --- a/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_order_config_response_schema.py +++ /dev/null @@ -1,222 +0,0 @@ -# coding: utf-8 - - -import pprint -import re # noqa: F401 - -import six - - -class RelayerApiOrderConfigResponseSchema(object): - """ - Attributes: - openapi_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - openapi_types = { - "maker_fee": "str", - "taker_fee": "str", - "fee_recipient_address": "str", - "sender_address": "str", - } - - attribute_map = { - "maker_fee": "makerFee", - "taker_fee": "takerFee", - "fee_recipient_address": "feeRecipientAddress", - "sender_address": "senderAddress", - } - - def __init__( - self, - maker_fee=None, - taker_fee=None, - fee_recipient_address=None, - sender_address=None, - ): # noqa: E501 - """RelayerApiOrderConfigResponseSchema - a model defined in OpenAPI""" # noqa: E501 - - self._maker_fee = None - self._taker_fee = None - self._fee_recipient_address = None - self._sender_address = None - self.discriminator = None - - self.maker_fee = maker_fee - self.taker_fee = taker_fee - self.fee_recipient_address = fee_recipient_address - self.sender_address = sender_address - - @property - def maker_fee(self): - """Gets the maker_fee of this RelayerApiOrderConfigResponseSchema. - - - :return: The maker_fee of this RelayerApiOrderConfigResponseSchema. - :rtype: str - """ - return self._maker_fee - - @maker_fee.setter - def maker_fee(self, maker_fee): - """Sets the maker_fee of this RelayerApiOrderConfigResponseSchema. - - - :param maker_fee: The maker_fee of this RelayerApiOrderConfigResponseSchema. - :type: str - """ - if maker_fee is None: - raise ValueError( - "Invalid value for `maker_fee`, must not be `None`" - ) # noqa: E501 - if maker_fee is not None and not re.search( - r"^\d+$", maker_fee - ): # noqa: E501 - raise ValueError( - r"Invalid value for `maker_fee`, must be a follow pattern or equal to `/^\d+$/`" - ) # noqa: E501 - - self._maker_fee = maker_fee - - @property - def taker_fee(self): - """Gets the taker_fee of this RelayerApiOrderConfigResponseSchema. - - - :return: The taker_fee of this RelayerApiOrderConfigResponseSchema. - :rtype: str - """ - return self._taker_fee - - @taker_fee.setter - def taker_fee(self, taker_fee): - """Sets the taker_fee of this RelayerApiOrderConfigResponseSchema. - - - :param taker_fee: The taker_fee of this RelayerApiOrderConfigResponseSchema. - :type: str - """ - if taker_fee is None: - raise ValueError( - "Invalid value for `taker_fee`, must not be `None`" - ) # noqa: E501 - if taker_fee is not None and not re.search( - r"^\d+$", taker_fee - ): # noqa: E501 - raise ValueError( - r"Invalid value for `taker_fee`, must be a follow pattern or equal to `/^\d+$/`" - ) # noqa: E501 - - self._taker_fee = taker_fee - - @property - def fee_recipient_address(self): - """Gets the fee_recipient_address of this RelayerApiOrderConfigResponseSchema. - - - :return: The fee_recipient_address of this RelayerApiOrderConfigResponseSchema. - :rtype: str - """ - return self._fee_recipient_address - - @fee_recipient_address.setter - def fee_recipient_address(self, fee_recipient_address): - """Sets the fee_recipient_address of this RelayerApiOrderConfigResponseSchema. - - - :param fee_recipient_address: The fee_recipient_address of this RelayerApiOrderConfigResponseSchema. - :type: str - """ - if fee_recipient_address is None: - raise ValueError( - "Invalid value for `fee_recipient_address`, must not be `None`" - ) # noqa: E501 - if fee_recipient_address is not None and not re.search( - r"^0x[0-9a-f]{40}$", fee_recipient_address - ): # noqa: E501 - raise ValueError( - r"Invalid value for `fee_recipient_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`" - ) # noqa: E501 - - self._fee_recipient_address = fee_recipient_address - - @property - def sender_address(self): - """Gets the sender_address of this RelayerApiOrderConfigResponseSchema. - - - :return: The sender_address of this RelayerApiOrderConfigResponseSchema. - :rtype: str - """ - return self._sender_address - - @sender_address.setter - def sender_address(self, sender_address): - """Sets the sender_address of this RelayerApiOrderConfigResponseSchema. - - - :param sender_address: The sender_address of this RelayerApiOrderConfigResponseSchema. - :type: str - """ - if sender_address is None: - raise ValueError( - "Invalid value for `sender_address`, must not be `None`" - ) # noqa: E501 - if sender_address is not None and not re.search( - r"^0x[0-9a-f]{40}$", sender_address - ): # noqa: E501 - raise ValueError( - r"Invalid value for `sender_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`" - ) # noqa: E501 - - self._sender_address = sender_address - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list( - map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value, - ) - ) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict( - map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") - else item, - value.items(), - ) - ) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, RelayerApiOrderConfigResponseSchema): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_order_schema.py b/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_order_schema.py deleted file mode 100644 index 1053480527..0000000000 --- a/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_order_schema.py +++ /dev/null @@ -1,128 +0,0 @@ -# coding: utf-8 - - -import pprint -import re # noqa: F401 - -import six - - -class RelayerApiOrderSchema(object): - """ - Attributes: - openapi_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - openapi_types = {"order": "OrderSchema", "meta_data": "object"} - - attribute_map = {"order": "order", "meta_data": "metaData"} - - def __init__(self, order=None, meta_data=None): # noqa: E501 - """RelayerApiOrderSchema - a model defined in OpenAPI""" # noqa: E501 - - self._order = None - self._meta_data = None - self.discriminator = None - - self.order = order - self.meta_data = meta_data - - @property - def order(self): - """Gets the order of this RelayerApiOrderSchema. - - - :return: The order of this RelayerApiOrderSchema. - :rtype: OrderSchema - """ - return self._order - - @order.setter - def order(self, order): - """Sets the order of this RelayerApiOrderSchema. - - - :param order: The order of this RelayerApiOrderSchema. - :type: OrderSchema - """ - if order is None: - raise ValueError( - "Invalid value for `order`, must not be `None`" - ) # noqa: E501 - - self._order = order - - @property - def meta_data(self): - """Gets the meta_data of this RelayerApiOrderSchema. - - - :return: The meta_data of this RelayerApiOrderSchema. - :rtype: object - """ - return self._meta_data - - @meta_data.setter - def meta_data(self, meta_data): - """Sets the meta_data of this RelayerApiOrderSchema. - - - :param meta_data: The meta_data of this RelayerApiOrderSchema. - :type: object - """ - if meta_data is None: - raise ValueError( - "Invalid value for `meta_data`, must not be `None`" - ) # noqa: E501 - - self._meta_data = meta_data - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list( - map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value, - ) - ) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict( - map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") - else item, - value.items(), - ) - ) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, RelayerApiOrderSchema): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_orderbook_response_schema.py b/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_orderbook_response_schema.py deleted file mode 100644 index e70bc3368c..0000000000 --- a/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_orderbook_response_schema.py +++ /dev/null @@ -1,131 +0,0 @@ -# coding: utf-8 - - -import pprint -import re # noqa: F401 - -import six - - -class RelayerApiOrderbookResponseSchema(object): - """ - Attributes: - openapi_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - openapi_types = { - "bids": "RelayerApiOrdersResponseSchema", - "asks": "RelayerApiOrdersResponseSchema", - } - - attribute_map = {"bids": "bids", "asks": "asks"} - - def __init__(self, bids=None, asks=None): # noqa: E501 - """RelayerApiOrderbookResponseSchema - a model defined in OpenAPI""" # noqa: E501 - - self._bids = None - self._asks = None - self.discriminator = None - - self.bids = bids - self.asks = asks - - @property - def bids(self): - """Gets the bids of this RelayerApiOrderbookResponseSchema. - - - :return: The bids of this RelayerApiOrderbookResponseSchema. - :rtype: RelayerApiOrdersResponseSchema - """ - return self._bids - - @bids.setter - def bids(self, bids): - """Sets the bids of this RelayerApiOrderbookResponseSchema. - - - :param bids: The bids of this RelayerApiOrderbookResponseSchema. - :type: RelayerApiOrdersResponseSchema - """ - if bids is None: - raise ValueError( - "Invalid value for `bids`, must not be `None`" - ) # noqa: E501 - - self._bids = bids - - @property - def asks(self): - """Gets the asks of this RelayerApiOrderbookResponseSchema. - - - :return: The asks of this RelayerApiOrderbookResponseSchema. - :rtype: RelayerApiOrdersResponseSchema - """ - return self._asks - - @asks.setter - def asks(self, asks): - """Sets the asks of this RelayerApiOrderbookResponseSchema. - - - :param asks: The asks of this RelayerApiOrderbookResponseSchema. - :type: RelayerApiOrdersResponseSchema - """ - if asks is None: - raise ValueError( - "Invalid value for `asks`, must not be `None`" - ) # noqa: E501 - - self._asks = asks - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list( - map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value, - ) - ) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict( - map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") - else item, - value.items(), - ) - ) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, RelayerApiOrderbookResponseSchema): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_orders_channel_subscribe_payload_schema.py b/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_orders_channel_subscribe_payload_schema.py deleted file mode 100644 index 4ecfea0b68..0000000000 --- a/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_orders_channel_subscribe_payload_schema.py +++ /dev/null @@ -1,311 +0,0 @@ -# coding: utf-8 - - -import pprint -import re # noqa: F401 - -import six - - -class RelayerApiOrdersChannelSubscribePayloadSchema(object): - """ - Attributes: - openapi_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - openapi_types = { - "maker_asset_proxy_id": "str", - "taker_asset_proxy_id": "str", - "maker_asset_address": "str", - "taker_asset_address": "str", - "maker_asset_data": "str", - "taker_asset_data": "str", - "trader_asset_data": "str", - } - - attribute_map = { - "maker_asset_proxy_id": "makerAssetProxyId", - "taker_asset_proxy_id": "takerAssetProxyId", - "maker_asset_address": "makerAssetAddress", - "taker_asset_address": "takerAssetAddress", - "maker_asset_data": "makerAssetData", - "taker_asset_data": "takerAssetData", - "trader_asset_data": "traderAssetData", - } - - def __init__( - self, - maker_asset_proxy_id=None, - taker_asset_proxy_id=None, - maker_asset_address=None, - taker_asset_address=None, - maker_asset_data=None, - taker_asset_data=None, - trader_asset_data=None, - ): # noqa: E501 - """RelayerApiOrdersChannelSubscribePayloadSchema - a model defined in OpenAPI""" # noqa: E501 - - self._maker_asset_proxy_id = None - self._taker_asset_proxy_id = None - self._maker_asset_address = None - self._taker_asset_address = None - self._maker_asset_data = None - self._taker_asset_data = None - self._trader_asset_data = None - self.discriminator = None - - if maker_asset_proxy_id is not None: - self.maker_asset_proxy_id = maker_asset_proxy_id - if taker_asset_proxy_id is not None: - self.taker_asset_proxy_id = taker_asset_proxy_id - if maker_asset_address is not None: - self.maker_asset_address = maker_asset_address - if taker_asset_address is not None: - self.taker_asset_address = taker_asset_address - if maker_asset_data is not None: - self.maker_asset_data = maker_asset_data - if taker_asset_data is not None: - self.taker_asset_data = taker_asset_data - if trader_asset_data is not None: - self.trader_asset_data = trader_asset_data - - @property - def maker_asset_proxy_id(self): - """Gets the maker_asset_proxy_id of this RelayerApiOrdersChannelSubscribePayloadSchema. - - - :return: The maker_asset_proxy_id of this RelayerApiOrdersChannelSubscribePayloadSchema. - :rtype: str - """ - return self._maker_asset_proxy_id - - @maker_asset_proxy_id.setter - def maker_asset_proxy_id(self, maker_asset_proxy_id): - """Sets the maker_asset_proxy_id of this RelayerApiOrdersChannelSubscribePayloadSchema. - - - :param maker_asset_proxy_id: The maker_asset_proxy_id of this RelayerApiOrdersChannelSubscribePayloadSchema. - :type: str - """ - if maker_asset_proxy_id is not None and not re.search( - r"^0x(([0-9a-f][0-9a-f])+)?$", maker_asset_proxy_id - ): # noqa: E501 - raise ValueError( - r"Invalid value for `maker_asset_proxy_id`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`" - ) # noqa: E501 - - self._maker_asset_proxy_id = maker_asset_proxy_id - - @property - def taker_asset_proxy_id(self): - """Gets the taker_asset_proxy_id of this RelayerApiOrdersChannelSubscribePayloadSchema. - - - :return: The taker_asset_proxy_id of this RelayerApiOrdersChannelSubscribePayloadSchema. - :rtype: str - """ - return self._taker_asset_proxy_id - - @taker_asset_proxy_id.setter - def taker_asset_proxy_id(self, taker_asset_proxy_id): - """Sets the taker_asset_proxy_id of this RelayerApiOrdersChannelSubscribePayloadSchema. - - - :param taker_asset_proxy_id: The taker_asset_proxy_id of this RelayerApiOrdersChannelSubscribePayloadSchema. - :type: str - """ - if taker_asset_proxy_id is not None and not re.search( - r"^0x(([0-9a-f][0-9a-f])+)?$", taker_asset_proxy_id - ): # noqa: E501 - raise ValueError( - r"Invalid value for `taker_asset_proxy_id`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`" - ) # noqa: E501 - - self._taker_asset_proxy_id = taker_asset_proxy_id - - @property - def maker_asset_address(self): - """Gets the maker_asset_address of this RelayerApiOrdersChannelSubscribePayloadSchema. - - - :return: The maker_asset_address of this RelayerApiOrdersChannelSubscribePayloadSchema. - :rtype: str - """ - return self._maker_asset_address - - @maker_asset_address.setter - def maker_asset_address(self, maker_asset_address): - """Sets the maker_asset_address of this RelayerApiOrdersChannelSubscribePayloadSchema. - - - :param maker_asset_address: The maker_asset_address of this RelayerApiOrdersChannelSubscribePayloadSchema. - :type: str - """ - if maker_asset_address is not None and not re.search( - r"^0x[0-9a-f]{40}$", maker_asset_address - ): # noqa: E501 - raise ValueError( - r"Invalid value for `maker_asset_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`" - ) # noqa: E501 - - self._maker_asset_address = maker_asset_address - - @property - def taker_asset_address(self): - """Gets the taker_asset_address of this RelayerApiOrdersChannelSubscribePayloadSchema. - - - :return: The taker_asset_address of this RelayerApiOrdersChannelSubscribePayloadSchema. - :rtype: str - """ - return self._taker_asset_address - - @taker_asset_address.setter - def taker_asset_address(self, taker_asset_address): - """Sets the taker_asset_address of this RelayerApiOrdersChannelSubscribePayloadSchema. - - - :param taker_asset_address: The taker_asset_address of this RelayerApiOrdersChannelSubscribePayloadSchema. - :type: str - """ - if taker_asset_address is not None and not re.search( - r"^0x[0-9a-f]{40}$", taker_asset_address - ): # noqa: E501 - raise ValueError( - r"Invalid value for `taker_asset_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`" - ) # noqa: E501 - - self._taker_asset_address = taker_asset_address - - @property - def maker_asset_data(self): - """Gets the maker_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. - - - :return: The maker_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. - :rtype: str - """ - return self._maker_asset_data - - @maker_asset_data.setter - def maker_asset_data(self, maker_asset_data): - """Sets the maker_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. - - - :param maker_asset_data: The maker_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. - :type: str - """ - if maker_asset_data is not None and not re.search( - r"^0x(([0-9a-f][0-9a-f])+)?$", maker_asset_data - ): # noqa: E501 - raise ValueError( - r"Invalid value for `maker_asset_data`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`" - ) # noqa: E501 - - self._maker_asset_data = maker_asset_data - - @property - def taker_asset_data(self): - """Gets the taker_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. - - - :return: The taker_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. - :rtype: str - """ - return self._taker_asset_data - - @taker_asset_data.setter - def taker_asset_data(self, taker_asset_data): - """Sets the taker_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. - - - :param taker_asset_data: The taker_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. - :type: str - """ - if taker_asset_data is not None and not re.search( - r"^0x(([0-9a-f][0-9a-f])+)?$", taker_asset_data - ): # noqa: E501 - raise ValueError( - r"Invalid value for `taker_asset_data`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`" - ) # noqa: E501 - - self._taker_asset_data = taker_asset_data - - @property - def trader_asset_data(self): - """Gets the trader_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. - - - :return: The trader_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. - :rtype: str - """ - return self._trader_asset_data - - @trader_asset_data.setter - def trader_asset_data(self, trader_asset_data): - """Sets the trader_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. - - - :param trader_asset_data: The trader_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. - :type: str - """ - if trader_asset_data is not None and not re.search( - r"^0x(([0-9a-f][0-9a-f])+)?$", trader_asset_data - ): # noqa: E501 - raise ValueError( - r"Invalid value for `trader_asset_data`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`" - ) # noqa: E501 - - self._trader_asset_data = trader_asset_data - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list( - map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value, - ) - ) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict( - map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") - else item, - value.items(), - ) - ) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance( - other, RelayerApiOrdersChannelSubscribePayloadSchema - ): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_orders_channel_subscribe_schema.py b/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_orders_channel_subscribe_schema.py deleted file mode 100644 index f3a527879f..0000000000 --- a/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_orders_channel_subscribe_schema.py +++ /dev/null @@ -1,205 +0,0 @@ -# coding: utf-8 - - -import pprint -import re # noqa: F401 - -import six - - -class RelayerApiOrdersChannelSubscribeSchema(object): - """ - Attributes: - openapi_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - openapi_types = { - "type": "str", - "channel": "str", - "request_id": "str", - "payload": "RelayerApiOrdersChannelSubscribePayloadSchema", - } - - attribute_map = { - "type": "type", - "channel": "channel", - "request_id": "requestId", - "payload": "payload", - } - - def __init__( - self, type=None, channel=None, request_id=None, payload=None - ): # noqa: E501 - """RelayerApiOrdersChannelSubscribeSchema - a model defined in OpenAPI""" # noqa: E501 - - self._type = None - self._channel = None - self._request_id = None - self._payload = None - self.discriminator = None - - self.type = type - self.channel = channel - self.request_id = request_id - if payload is not None: - self.payload = payload - - @property - def type(self): - """Gets the type of this RelayerApiOrdersChannelSubscribeSchema. - - - :return: The type of this RelayerApiOrdersChannelSubscribeSchema. - :rtype: str - """ - return self._type - - @type.setter - def type(self, type): - """Sets the type of this RelayerApiOrdersChannelSubscribeSchema. - - - :param type: The type of this RelayerApiOrdersChannelSubscribeSchema. - :type: str - """ - if type is None: - raise ValueError( - "Invalid value for `type`, must not be `None`" - ) # noqa: E501 - allowed_values = ["subscribe"] # noqa: E501 - if type not in allowed_values: - raise ValueError( - "Invalid value for `type` ({0}), must be one of {1}".format( # noqa: E501 - type, allowed_values - ) - ) - - self._type = type - - @property - def channel(self): - """Gets the channel of this RelayerApiOrdersChannelSubscribeSchema. - - - :return: The channel of this RelayerApiOrdersChannelSubscribeSchema. - :rtype: str - """ - return self._channel - - @channel.setter - def channel(self, channel): - """Sets the channel of this RelayerApiOrdersChannelSubscribeSchema. - - - :param channel: The channel of this RelayerApiOrdersChannelSubscribeSchema. - :type: str - """ - if channel is None: - raise ValueError( - "Invalid value for `channel`, must not be `None`" - ) # noqa: E501 - allowed_values = ["orders"] # noqa: E501 - if channel not in allowed_values: - raise ValueError( - "Invalid value for `channel` ({0}), must be one of {1}".format( # noqa: E501 - channel, allowed_values - ) - ) - - self._channel = channel - - @property - def request_id(self): - """Gets the request_id of this RelayerApiOrdersChannelSubscribeSchema. - - - :return: The request_id of this RelayerApiOrdersChannelSubscribeSchema. - :rtype: str - """ - return self._request_id - - @request_id.setter - def request_id(self, request_id): - """Sets the request_id of this RelayerApiOrdersChannelSubscribeSchema. - - - :param request_id: The request_id of this RelayerApiOrdersChannelSubscribeSchema. - :type: str - """ - if request_id is None: - raise ValueError( - "Invalid value for `request_id`, must not be `None`" - ) # noqa: E501 - - self._request_id = request_id - - @property - def payload(self): - """Gets the payload of this RelayerApiOrdersChannelSubscribeSchema. - - - :return: The payload of this RelayerApiOrdersChannelSubscribeSchema. - :rtype: RelayerApiOrdersChannelSubscribePayloadSchema - """ - return self._payload - - @payload.setter - def payload(self, payload): - """Sets the payload of this RelayerApiOrdersChannelSubscribeSchema. - - - :param payload: The payload of this RelayerApiOrdersChannelSubscribeSchema. - :type: RelayerApiOrdersChannelSubscribePayloadSchema - """ - - self._payload = payload - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list( - map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value, - ) - ) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict( - map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") - else item, - value.items(), - ) - ) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, RelayerApiOrdersChannelSubscribeSchema): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_orders_channel_update_schema.py b/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_orders_channel_update_schema.py deleted file mode 100644 index 9c3ec10191..0000000000 --- a/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_orders_channel_update_schema.py +++ /dev/null @@ -1,205 +0,0 @@ -# coding: utf-8 - - -import pprint -import re # noqa: F401 - -import six - - -class RelayerApiOrdersChannelUpdateSchema(object): - """ - Attributes: - openapi_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - openapi_types = { - "type": "str", - "channel": "str", - "request_id": "str", - "payload": "list[RelayerApiOrderSchema]", - } - - attribute_map = { - "type": "type", - "channel": "channel", - "request_id": "requestId", - "payload": "payload", - } - - def __init__( - self, type=None, channel=None, request_id=None, payload=None - ): # noqa: E501 - """RelayerApiOrdersChannelUpdateSchema - a model defined in OpenAPI""" # noqa: E501 - - self._type = None - self._channel = None - self._request_id = None - self._payload = None - self.discriminator = None - - self.type = type - self.channel = channel - self.request_id = request_id - if payload is not None: - self.payload = payload - - @property - def type(self): - """Gets the type of this RelayerApiOrdersChannelUpdateSchema. - - - :return: The type of this RelayerApiOrdersChannelUpdateSchema. - :rtype: str - """ - return self._type - - @type.setter - def type(self, type): - """Sets the type of this RelayerApiOrdersChannelUpdateSchema. - - - :param type: The type of this RelayerApiOrdersChannelUpdateSchema. - :type: str - """ - if type is None: - raise ValueError( - "Invalid value for `type`, must not be `None`" - ) # noqa: E501 - allowed_values = ["update"] # noqa: E501 - if type not in allowed_values: - raise ValueError( - "Invalid value for `type` ({0}), must be one of {1}".format( # noqa: E501 - type, allowed_values - ) - ) - - self._type = type - - @property - def channel(self): - """Gets the channel of this RelayerApiOrdersChannelUpdateSchema. - - - :return: The channel of this RelayerApiOrdersChannelUpdateSchema. - :rtype: str - """ - return self._channel - - @channel.setter - def channel(self, channel): - """Sets the channel of this RelayerApiOrdersChannelUpdateSchema. - - - :param channel: The channel of this RelayerApiOrdersChannelUpdateSchema. - :type: str - """ - if channel is None: - raise ValueError( - "Invalid value for `channel`, must not be `None`" - ) # noqa: E501 - allowed_values = ["orders"] # noqa: E501 - if channel not in allowed_values: - raise ValueError( - "Invalid value for `channel` ({0}), must be one of {1}".format( # noqa: E501 - channel, allowed_values - ) - ) - - self._channel = channel - - @property - def request_id(self): - """Gets the request_id of this RelayerApiOrdersChannelUpdateSchema. - - - :return: The request_id of this RelayerApiOrdersChannelUpdateSchema. - :rtype: str - """ - return self._request_id - - @request_id.setter - def request_id(self, request_id): - """Sets the request_id of this RelayerApiOrdersChannelUpdateSchema. - - - :param request_id: The request_id of this RelayerApiOrdersChannelUpdateSchema. - :type: str - """ - if request_id is None: - raise ValueError( - "Invalid value for `request_id`, must not be `None`" - ) # noqa: E501 - - self._request_id = request_id - - @property - def payload(self): - """Gets the payload of this RelayerApiOrdersChannelUpdateSchema. - - - :return: The payload of this RelayerApiOrdersChannelUpdateSchema. - :rtype: list[RelayerApiOrderSchema] - """ - return self._payload - - @payload.setter - def payload(self, payload): - """Sets the payload of this RelayerApiOrdersChannelUpdateSchema. - - - :param payload: The payload of this RelayerApiOrdersChannelUpdateSchema. - :type: list[RelayerApiOrderSchema] - """ - - self._payload = payload - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list( - map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value, - ) - ) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict( - map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") - else item, - value.items(), - ) - ) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, RelayerApiOrdersChannelUpdateSchema): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_orders_response_schema.py b/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_orders_response_schema.py deleted file mode 100644 index 7cccc61e14..0000000000 --- a/python-packages/sra_client/src/zero_ex/sra_client/models/relayer_api_orders_response_schema.py +++ /dev/null @@ -1,101 +0,0 @@ -# coding: utf-8 - - -import pprint -import re # noqa: F401 - -import six - - -class RelayerApiOrdersResponseSchema(object): - """ - Attributes: - openapi_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - openapi_types = {"records": "list[RelayerApiOrderSchema]"} - - attribute_map = {"records": "records"} - - def __init__(self, records=None): # noqa: E501 - """RelayerApiOrdersResponseSchema - a model defined in OpenAPI""" # noqa: E501 - - self._records = None - self.discriminator = None - - self.records = records - - @property - def records(self): - """Gets the records of this RelayerApiOrdersResponseSchema. - - - :return: The records of this RelayerApiOrdersResponseSchema. - :rtype: list[RelayerApiOrderSchema] - """ - return self._records - - @records.setter - def records(self, records): - """Sets the records of this RelayerApiOrdersResponseSchema. - - - :param records: The records of this RelayerApiOrdersResponseSchema. - :type: list[RelayerApiOrderSchema] - """ - if records is None: - raise ValueError( - "Invalid value for `records`, must not be `None`" - ) # noqa: E501 - - self._records = records - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list( - map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value, - ) - ) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict( - map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") - else item, - value.items(), - ) - ) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, RelayerApiOrdersResponseSchema): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python-packages/sra_client/src/zero_ex/sra_client/models/signed_order_schema.py b/python-packages/sra_client/src/zero_ex/sra_client/models/signed_order_schema.py deleted file mode 100644 index 3f19f178d7..0000000000 --- a/python-packages/sra_client/src/zero_ex/sra_client/models/signed_order_schema.py +++ /dev/null @@ -1,107 +0,0 @@ -# coding: utf-8 - - -import pprint -import re # noqa: F401 - -import six - - -class SignedOrderSchema(object): - """ - Attributes: - openapi_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - openapi_types = {"signature": "str"} - - attribute_map = {"signature": "signature"} - - def __init__(self, signature=None): # noqa: E501 - """SignedOrderSchema - a model defined in OpenAPI""" # noqa: E501 - - self._signature = None - self.discriminator = None - - self.signature = signature - - @property - def signature(self): - """Gets the signature of this SignedOrderSchema. - - - :return: The signature of this SignedOrderSchema. - :rtype: str - """ - return self._signature - - @signature.setter - def signature(self, signature): - """Sets the signature of this SignedOrderSchema. - - - :param signature: The signature of this SignedOrderSchema. - :type: str - """ - if signature is None: - raise ValueError( - "Invalid value for `signature`, must not be `None`" - ) # noqa: E501 - if signature is not None and not re.search( - r"^0x(([0-9a-f][0-9a-f])+)?$", signature - ): # noqa: E501 - raise ValueError( - r"Invalid value for `signature`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`" - ) # noqa: E501 - - self._signature = signature - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list( - map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value, - ) - ) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict( - map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") - else item, - value.items(), - ) - ) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, SignedOrderSchema): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python-packages/sra_client/src/zero_ex/sra_client/rest.py b/python-packages/sra_client/src/zero_ex/sra_client/rest.py deleted file mode 100644 index b38cabd703..0000000000 --- a/python-packages/sra_client/src/zero_ex/sra_client/rest.py +++ /dev/null @@ -1,421 +0,0 @@ -# coding: utf-8 - - -from __future__ import absolute_import - -import io -import json -import logging -import re -import ssl - -import certifi - -# python 2 and python 3 compatibility library -import six -from six.moves.urllib.parse import urlencode - -try: - import urllib3 -except ImportError: - raise ImportError("OpenAPI Python client requires urllib3.") - - -logger = logging.getLogger(__name__) - - -class RESTResponse(io.IOBase): - def __init__(self, resp): - self.urllib3_response = resp - self.status = resp.status - self.reason = resp.reason - self.data = resp.data - - def getheaders(self): - """Returns a dictionary of the response headers.""" - return self.urllib3_response.getheaders() - - def getheader(self, name, default=None): - """Returns a given response header.""" - return self.urllib3_response.getheader(name, default) - - -class RESTClientObject(object): - def __init__(self, configuration, pools_size=4, maxsize=None): - # urllib3.PoolManager will pass all kw parameters to connectionpool - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 - # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 - # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 - - # cert_reqs - if configuration.verify_ssl: - cert_reqs = ssl.CERT_REQUIRED - else: - cert_reqs = ssl.CERT_NONE - - # ca_certs - if configuration.ssl_ca_cert: - ca_certs = configuration.ssl_ca_cert - else: - # if not set certificate file, use Mozilla's root certificates. - ca_certs = certifi.where() - - addition_pool_args = {} - if configuration.assert_hostname is not None: - addition_pool_args[ - "assert_hostname" - ] = configuration.assert_hostname # noqa: E501 - - if maxsize is None: - if configuration.connection_pool_maxsize is not None: - maxsize = configuration.connection_pool_maxsize - else: - maxsize = 4 - - # https pool manager - if configuration.proxy: - self.pool_manager = urllib3.ProxyManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=ca_certs, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - proxy_url=configuration.proxy, - **addition_pool_args - ) - else: - self.pool_manager = urllib3.PoolManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=ca_certs, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - **addition_pool_args - ) - - def request( - self, - method, - url, - query_params=None, - headers=None, - body=None, - post_params=None, - _preload_content=True, - _request_timeout=None, - ): - """Perform requests. - - :param method: http request method - :param url: http request url - :param query_params: query parameters in the url - :param headers: http request headers - :param body: request json body, for `application/json` - :param post_params: request post parameters, - `application/x-www-form-urlencoded` - and `multipart/form-data` - :param _preload_content: if False, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is True. - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - """ - method = method.upper() - assert method in [ - "GET", - "HEAD", - "DELETE", - "POST", - "PUT", - "PATCH", - "OPTIONS", - ] - - if post_params and body: - raise ValueError( - "body parameter cannot be used with post_params parameter." - ) - - post_params = post_params or {} - headers = headers or {} - - timeout = None - if _request_timeout: - if isinstance( - _request_timeout, (int,) if six.PY3 else (int, long) - ): # noqa: E501,F821 - timeout = urllib3.Timeout(total=_request_timeout) - elif ( - isinstance(_request_timeout, tuple) - and len(_request_timeout) == 2 - ): - timeout = urllib3.Timeout( - connect=_request_timeout[0], read=_request_timeout[1] - ) - - if "Content-Type" not in headers: - headers["Content-Type"] = "application/json" - - try: - # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` - if method in ["POST", "PUT", "PATCH", "OPTIONS", "DELETE"]: - if query_params: - url += "?" + urlencode(query_params) - if re.search("json", headers["Content-Type"], re.IGNORECASE): - request_body = None - if body is not None: - request_body = json.dumps(body) - r = self.pool_manager.request( - method, - url, - body=request_body, - preload_content=_preload_content, - timeout=timeout, - headers=headers, - ) - elif ( - headers["Content-Type"] - == "application/x-www-form-urlencoded" - ): # noqa: E501 - r = self.pool_manager.request( - method, - url, - fields=post_params, - encode_multipart=False, - preload_content=_preload_content, - timeout=timeout, - headers=headers, - ) - elif headers["Content-Type"] == "multipart/form-data": - # must del headers['Content-Type'], or the correct - # Content-Type which generated by urllib3 will be - # overwritten. - del headers["Content-Type"] - r = self.pool_manager.request( - method, - url, - fields=post_params, - encode_multipart=True, - preload_content=_preload_content, - timeout=timeout, - headers=headers, - ) - # Pass a `string` parameter directly in the body to support - # other content types than Json when `body` argument is - # provided in serialized form - elif isinstance(body, str): - request_body = body - r = self.pool_manager.request( - method, - url, - body=request_body, - preload_content=_preload_content, - timeout=timeout, - headers=headers, - ) - else: - # Cannot generate the request from given parameters - msg = """Cannot prepare a request message for provided - arguments. Please check that your arguments match - declared content type.""" - raise ApiException(status=0, reason=msg) - # For `GET`, `HEAD` - else: - r = self.pool_manager.request( - method, - url, - fields=query_params, - preload_content=_preload_content, - timeout=timeout, - headers=headers, - ) - except urllib3.exceptions.SSLError as e: - msg = "{0}\n{1}".format(type(e).__name__, str(e)) - raise ApiException(status=0, reason=msg) - - if _preload_content: - r = RESTResponse(r) - - # In the python 3, the response.data is bytes. - # we need to decode it to string. - if six.PY3: - r.data = r.data.decode("utf8") - - # log response body - logger.debug("response body: %s", r.data) - - if not 200 <= r.status <= 299: - raise ApiException(http_resp=r) - - return r - - def GET( - self, - url, - headers=None, - query_params=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "GET", - url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params, - ) - - def HEAD( - self, - url, - headers=None, - query_params=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "HEAD", - url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params, - ) - - def OPTIONS( - self, - url, - headers=None, - query_params=None, - post_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "OPTIONS", - url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - - def DELETE( - self, - url, - headers=None, - query_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "DELETE", - url, - headers=headers, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - - def POST( - self, - url, - headers=None, - query_params=None, - post_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "POST", - url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - - def PUT( - self, - url, - headers=None, - query_params=None, - post_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "PUT", - url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - - def PATCH( - self, - url, - headers=None, - query_params=None, - post_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "PATCH", - url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - - -class ApiException(Exception): - def __init__(self, status=None, reason=None, http_resp=None): - if http_resp: - self.status = http_resp.status - self.reason = http_resp.reason - self.body = http_resp.data - self.headers = http_resp.getheaders() - else: - self.status = status - self.reason = reason - self.body = None - self.headers = None - - def __str__(self): - """Custom error messages for exception""" - error_message = "({0})\n" "Reason: {1}\n".format( - self.status, self.reason - ) - if self.headers: - error_message += "HTTP response headers: {0}\n".format( - self.headers - ) - - if self.body: - error_message += "HTTP response body: {0}\n".format(self.body) - - return error_message diff --git a/python-packages/sra_client/test-requirements.txt b/python-packages/sra_client/test-requirements.txt deleted file mode 100644 index 2702246c0e..0000000000 --- a/python-packages/sra_client/test-requirements.txt +++ /dev/null @@ -1,5 +0,0 @@ -coverage>=4.0.3 -nose>=1.3.7 -pluggy>=0.3.1 -py>=1.4.31 -randomize>=0.13 diff --git a/python-packages/sra_client/test/__init__.py b/python-packages/sra_client/test/__init__.py deleted file mode 100644 index 789ac3d7e7..0000000000 --- a/python-packages/sra_client/test/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Test for sra_client.""" diff --git a/python-packages/sra_client/test/relayer/docker-compose.yml b/python-packages/sra_client/test/relayer/docker-compose.yml deleted file mode 100644 index fe8c460e40..0000000000 --- a/python-packages/sra_client/test/relayer/docker-compose.yml +++ /dev/null @@ -1,41 +0,0 @@ -# Run Launch Kit Backend with Ganache and Mesh instances backing it. -version: '3' -services: - ganache: - image: "0xorg/ganache-cli:6.0.0" - ports: - - "8545:8545" - environment: - - VERSION=6.0.0 - mesh: - image: 0xorg/mesh:0xV3 - depends_on: - - ganache - environment: - ETHEREUM_RPC_URL: 'http://localhost:8545' - ETHEREUM_CHAIN_ID: '1337' - VERBOSITY: 5 - BLOCK_POLLING_INTERVAL: '5s' - ports: - - '60557:60557' - network_mode: "host" # to connect to ganache - command: | - sh -c "waitForGanache () { until printf 'POST /\r\nContent-Length: 26\r\n\r\n{\"method\":\"net_listening\"}' | nc localhost 8545 | grep true; do continue; done }; waitForGanache && ./mesh" - launch-kit-backend: - image: "0xorg/launch-kit-backend:v3" - depends_on: - - ganache - - mesh - ports: - - "3000:3000" - network_mode: "host" # to connect to ganache - environment: - - CHAIN_ID=1337 - - RPC_URL=http://localhost:8545 - - WHITELIST_ALL_TOKENS=True - - FEE_RECIPIENT=0x0000000000000000000000000000000000000001 - - MAKER_FEE_UNIT_AMOUNT=0 - - TAKER_FEE_UNIT_AMOUNT=0 - - MESH_ENDPOINT=ws://localhost:60557 - command: | - sh -c "waitForMesh () { sleep 30; }; waitForMesh && node_modules/.bin/forever ts/lib/index.js" diff --git a/python-packages/sra_client/tox.ini b/python-packages/sra_client/tox.ini deleted file mode 100644 index 2f40a07c89..0000000000 --- a/python-packages/sra_client/tox.ini +++ /dev/null @@ -1,24 +0,0 @@ -[tox] -envlist = py3 - -[testenv] -deps=-r{toxinidir}/requirements.txt - -r{toxinidir}/test-requirements.txt - -commands= - nosetests \ - [] - -[testenv:run_tests_against_test_deployment] -commands = - # install dependencies from real PyPI - pip install mypy_extensions pytest - # install package-under-test from test PyPI - pip install --index-url https://test.pypi.org/legacy/ 0x-sra-client - pytest test - -[testenv:run_tests_against_deployment] -setenv = PY_IGNORE_IMPORTMISMATCH = 1 -commands = - pip install 0x-sra-client[dev] - pytest --doctest-modules src test diff --git a/python-packages/test b/python-packages/test deleted file mode 100755 index 62c25dc1ec..0000000000 --- a/python-packages/test +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env bash - -./parallel ./setup.py test diff --git a/python-packages/tsort b/python-packages/tsort deleted file mode 100755 index 84b30ffb57..0000000000 --- a/python-packages/tsort +++ /dev/null @@ -1,17 +0,0 @@ -#!/usr/bin/env bash - -# extract package interdependencies and topographically sort them - -find -name setup.py -exec grep -H \"0x- {} \; | \ - grep -v name= | \ - grep -v NAME | \ - sed \ - -e 's/^\.\//0x-/' \ - -e 's/\/setup.py://' \ - -e 's/"//g' -e 's/,$//' \ - -e 's/_/-/g' | \ - tsort | \ - tac | \ - sed \ - -e 's/^0x-//' \ - -e 's/-/_/' diff --git a/python-packages/uninstall_all b/python-packages/uninstall_all deleted file mode 100755 index 2f25939937..0000000000 --- a/python-packages/uninstall_all +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash - -PKG_FOLDERS=$(find ./ -maxdepth 1 -type d -exec basename {} \; | grep -v -e '^.$' | grep -v '.mypy_cache' | tr '_' '-') -for i in $PKG_FOLDERS; do PKGS="${PKGS} 0x-$i"; done -echo pip uninstall --yes $PKGS 0x-web3 web3 - pip uninstall --yes $PKGS 0x-web3 web3