diff --git a/.gitattributes b/.gitattributes index f6d6b3c00a..10ff8a1bc3 100644 --- a/.gitattributes +++ b/.gitattributes @@ -4,4 +4,5 @@ *.svg linguist-generated=true packages/contract-artifacts/artifacts/*json linguist-generated=true packages/abi-gen-wrappers/src/generated-wrappers/*.ts linguist-generated=true +packages/contract-wrappers/src/generated-wrappers/*.ts linguist-generated=true diff --git a/contracts/dev-utils/package.json b/contracts/dev-utils/package.json index 3b2f398fe0..efdd13ecfa 100644 --- a/contracts/dev-utils/package.json +++ b/contracts/dev-utils/package.json @@ -48,7 +48,6 @@ "homepage": "https://github.com/0xProject/0x-monorepo/contracts/dev-utils/README.md", "devDependencies": { "@0x/abi-gen": "^3.1.2", - "@0x/contract-wrappers": "^10.1.0", "@0x/contracts-gen": "^1.0.12", "@0x/contracts-test-utils": "^3.1.12", "@0x/dev-utils": "^2.2.6", diff --git a/contracts/exchange-forwarder/package.json b/contracts/exchange-forwarder/package.json index 8f4b2f7fff..9c98a13e08 100644 --- a/contracts/exchange-forwarder/package.json +++ b/contracts/exchange-forwarder/package.json @@ -47,7 +47,6 @@ "homepage": "https://github.com/0xProject/0x-monorepo/contracts/extensions/README.md", "devDependencies": { "@0x/abi-gen": "^3.1.2", - "@0x/contract-wrappers": "^10.1.0", "@0x/contracts-gen": "^1.0.12", "@0x/contracts-test-utils": "^3.1.12", "@0x/dev-utils": "^2.2.6", diff --git a/contracts/extensions/package.json b/contracts/extensions/package.json index d8755d2000..e230ee599a 100644 --- a/contracts/extensions/package.json +++ b/contracts/extensions/package.json @@ -48,7 +48,7 @@ "homepage": "https://github.com/0xProject/0x-monorepo/contracts/extensions/README.md", "devDependencies": { "@0x/abi-gen": "^3.1.2", - "@0x/contract-wrappers": "^10.1.0", + "@0x/contract-wrappers": "10.1.0", "@0x/contracts-gen": "^1.0.12", "@0x/contracts-test-utils": "^3.1.12", "@0x/dev-utils": "^2.2.6", diff --git a/package.json b/package.json index 7398c8536f..a2f8958d4b 100644 --- a/package.json +++ b/package.json @@ -50,7 +50,7 @@ "config": { "contractsPackages": "@0x/contracts-asset-proxy @0x/contracts-erc20 @0x/contracts-erc721 @0x/contracts-erc1155 @0x/contracts-exchange @0x/contracts-exchange-forwarder @0x/contracts-exchange-libs @0x/contracts-extensions @0x/contracts-multisig @0x/contracts-test-utils @0x/contracts-utils @0x/contracts-coordinator @0x/contracts-dev-utils", "mnemonic": "concert load couple harbor equip island argue ramp clarify fence smart topic", - "packagesWithDocPages": "0x.js connect json-schemas subproviders web3-wrapper contract-wrappers order-utils order-watcher sol-compiler sol-coverage sol-profiler sol-trace ethereum-types asset-buyer migrations", + "packagesWithDocPages": "0x.js connect json-schemas subproviders web3-wrapper order-utils order-watcher sol-compiler sol-coverage sol-profiler sol-trace ethereum-types asset-buyer migrations", "ignoreDependencyVersions": "@types/styled-components @types/node", "ignoreDependencyVersionsForPackage": "website instant dev-tools-pages" }, diff --git a/packages/0x.js/package.json b/packages/0x.js/package.json index ddff028f2e..9f0ba02142 100644 --- a/packages/0x.js/package.json +++ b/packages/0x.js/package.json @@ -76,7 +76,7 @@ "@0x/assert": "^2.1.2", "@0x/asset-swapper": "^1.0.0", "@0x/base-contract": "^5.3.0", - "@0x/contract-wrappers": "^10.1.0", + "@0x/contract-wrappers": "10.1.0", "@0x/order-utils": "^8.2.4", "@0x/order-watcher": "^4.0.16", "@0x/subproviders": "^5.0.0", diff --git a/packages/0x.js/src/index.ts b/packages/0x.js/src/index.ts index ddd7100661..8d3890babe 100644 --- a/packages/0x.js/src/index.ts +++ b/packages/0x.js/src/index.ts @@ -40,6 +40,13 @@ export { } from '@0x/contract-wrappers'; export { + DutchAuctionContract, + ERC20ProxyContract, + ERC721ProxyContract, + ExchangeContract, + ForwarderContract, + OrderValidatorContract, + WETH9Contract, WETH9Events, WETH9WithdrawalEventArgs, WETH9ApprovalEventArgs, @@ -102,15 +109,12 @@ export { ObjectMap, OrderRelevantState, Stats, - DutchAuctionDetails, ZeroExTransaction, SignedZeroExTransaction, } from '@0x/types'; export { - BlockParamLiteral, ContractAbi, - BlockParam, LogWithDecodedArgs, ContractEventArg, SupportedProvider, diff --git a/packages/abi-gen-templates/contract.handlebars b/packages/abi-gen-templates/contract.handlebars index e54d3542fc..12ffaba4be 100644 --- a/packages/abi-gen-templates/contract.handlebars +++ b/packages/abi-gen-templates/contract.handlebars @@ -83,8 +83,10 @@ export class {{contractName}}Contract extends BaseContract { const bytecode = artifact.compilerOutput.evm.bytecode.object; const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + 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}}); } diff --git a/packages/abi-gen-wrappers/src/generated-wrappers/asset_proxy_owner.ts b/packages/abi-gen-wrappers/src/generated-wrappers/asset_proxy_owner.ts index 514bd3280a..4255ed3678 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/asset_proxy_owner.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/asset_proxy_owner.ts @@ -3119,8 +3119,10 @@ export class AssetProxyOwnerContract extends BaseContract { const bytecode = artifact.compilerOutput.evm.bytecode.object; const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + if (Object.keys(logDecodeDependencies) !== undefined) { + for (const key of Object.keys(logDecodeDependencies)) { + logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + } } return AssetProxyOwnerContract.deployAsync( bytecode, diff --git a/packages/abi-gen-wrappers/src/generated-wrappers/coordinator.ts b/packages/abi-gen-wrappers/src/generated-wrappers/coordinator.ts index 66e7c5b8cf..13d6bcff1d 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/coordinator.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/coordinator.ts @@ -1005,8 +1005,10 @@ export class CoordinatorContract extends BaseContract { const bytecode = artifact.compilerOutput.evm.bytecode.object; const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + if (Object.keys(logDecodeDependencies) !== undefined) { + for (const key of Object.keys(logDecodeDependencies)) { + logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + } } return CoordinatorContract.deployAsync( bytecode, diff --git a/packages/abi-gen-wrappers/src/generated-wrappers/coordinator_registry.ts b/packages/abi-gen-wrappers/src/generated-wrappers/coordinator_registry.ts index 701bafa774..373136ce51 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/coordinator_registry.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/coordinator_registry.ts @@ -298,8 +298,10 @@ export class CoordinatorRegistryContract extends BaseContract { const bytecode = artifact.compilerOutput.evm.bytecode.object; const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + if (Object.keys(logDecodeDependencies) !== undefined) { + for (const key of Object.keys(logDecodeDependencies)) { + logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + } } return CoordinatorRegistryContract.deployAsync( bytecode, diff --git a/packages/abi-gen-wrappers/src/generated-wrappers/dummy_erc20_token.ts b/packages/abi-gen-wrappers/src/generated-wrappers/dummy_erc20_token.ts index fd7f76a933..6dbf9f4b02 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/dummy_erc20_token.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/dummy_erc20_token.ts @@ -1660,8 +1660,10 @@ export class DummyERC20TokenContract extends BaseContract { const bytecode = artifact.compilerOutput.evm.bytecode.object; const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + if (Object.keys(logDecodeDependencies) !== undefined) { + for (const key of Object.keys(logDecodeDependencies)) { + logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + } } return DummyERC20TokenContract.deployAsync( bytecode, diff --git a/packages/abi-gen-wrappers/src/generated-wrappers/dummy_erc721_token.ts b/packages/abi-gen-wrappers/src/generated-wrappers/dummy_erc721_token.ts index 92ea73b244..0d5780f909 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/dummy_erc721_token.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/dummy_erc721_token.ts @@ -2116,8 +2116,10 @@ export class DummyERC721TokenContract extends BaseContract { const bytecode = artifact.compilerOutput.evm.bytecode.object; const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + if (Object.keys(logDecodeDependencies) !== undefined) { + for (const key of Object.keys(logDecodeDependencies)) { + logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + } } return DummyERC721TokenContract.deployAsync( bytecode, diff --git a/packages/abi-gen-wrappers/src/generated-wrappers/dutch_auction.ts b/packages/abi-gen-wrappers/src/generated-wrappers/dutch_auction.ts index 499fbaf43f..b4ab61b8de 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/dutch_auction.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/dutch_auction.ts @@ -795,8 +795,10 @@ export class DutchAuctionContract extends BaseContract { const bytecode = artifact.compilerOutput.evm.bytecode.object; const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + if (Object.keys(logDecodeDependencies) !== undefined) { + for (const key of Object.keys(logDecodeDependencies)) { + logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + } } return DutchAuctionContract.deployAsync( bytecode, diff --git a/packages/abi-gen-wrappers/src/generated-wrappers/erc20_proxy.ts b/packages/abi-gen-wrappers/src/generated-wrappers/erc20_proxy.ts index fb57c2744b..0b9f9752cd 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/erc20_proxy.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/erc20_proxy.ts @@ -1043,8 +1043,10 @@ export class ERC20ProxyContract extends BaseContract { const bytecode = artifact.compilerOutput.evm.bytecode.object; const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + if (Object.keys(logDecodeDependencies) !== undefined) { + for (const key of Object.keys(logDecodeDependencies)) { + logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + } } return ERC20ProxyContract.deployAsync(bytecode, abi, provider, txDefaults, logDecodeDependenciesAbiOnly); } diff --git a/packages/abi-gen-wrappers/src/generated-wrappers/erc20_token.ts b/packages/abi-gen-wrappers/src/generated-wrappers/erc20_token.ts index 79ec116da8..e910137065 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/erc20_token.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/erc20_token.ts @@ -866,8 +866,10 @@ export class ERC20TokenContract extends BaseContract { const bytecode = artifact.compilerOutput.evm.bytecode.object; const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + if (Object.keys(logDecodeDependencies) !== undefined) { + for (const key of Object.keys(logDecodeDependencies)) { + logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + } } return ERC20TokenContract.deployAsync(bytecode, abi, provider, txDefaults, logDecodeDependenciesAbiOnly); } diff --git a/packages/abi-gen-wrappers/src/generated-wrappers/erc721_proxy.ts b/packages/abi-gen-wrappers/src/generated-wrappers/erc721_proxy.ts index 1317b4db9d..63af02b710 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/erc721_proxy.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/erc721_proxy.ts @@ -1043,8 +1043,10 @@ export class ERC721ProxyContract extends BaseContract { const bytecode = artifact.compilerOutput.evm.bytecode.object; const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + if (Object.keys(logDecodeDependencies) !== undefined) { + for (const key of Object.keys(logDecodeDependencies)) { + logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + } } return ERC721ProxyContract.deployAsync(bytecode, abi, provider, txDefaults, logDecodeDependenciesAbiOnly); } diff --git a/packages/abi-gen-wrappers/src/generated-wrappers/erc721_token.ts b/packages/abi-gen-wrappers/src/generated-wrappers/erc721_token.ts index 4a17cd8e84..422f748c94 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/erc721_token.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/erc721_token.ts @@ -1428,8 +1428,10 @@ export class ERC721TokenContract extends BaseContract { const bytecode = artifact.compilerOutput.evm.bytecode.object; const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + if (Object.keys(logDecodeDependencies) !== undefined) { + for (const key of Object.keys(logDecodeDependencies)) { + logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + } } return ERC721TokenContract.deployAsync(bytecode, abi, provider, txDefaults, logDecodeDependenciesAbiOnly); } diff --git a/packages/abi-gen-wrappers/src/generated-wrappers/eth_balance_checker.ts b/packages/abi-gen-wrappers/src/generated-wrappers/eth_balance_checker.ts index cf454e9f99..1c9193cc33 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/eth_balance_checker.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/eth_balance_checker.ts @@ -119,8 +119,10 @@ export class EthBalanceCheckerContract extends BaseContract { const bytecode = artifact.compilerOutput.evm.bytecode.object; const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + if (Object.keys(logDecodeDependencies) !== undefined) { + for (const key of Object.keys(logDecodeDependencies)) { + logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + } } return EthBalanceCheckerContract.deployAsync(bytecode, abi, provider, txDefaults, logDecodeDependenciesAbiOnly); } diff --git a/packages/abi-gen-wrappers/src/generated-wrappers/exchange.ts b/packages/abi-gen-wrappers/src/generated-wrappers/exchange.ts index b513ea72bf..2df6b7ae3b 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/exchange.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/exchange.ts @@ -6498,8 +6498,10 @@ export class ExchangeContract extends BaseContract { const bytecode = artifact.compilerOutput.evm.bytecode.object; const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + if (Object.keys(logDecodeDependencies) !== undefined) { + for (const key of Object.keys(logDecodeDependencies)) { + logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + } } return ExchangeContract.deployAsync( bytecode, diff --git a/packages/abi-gen-wrappers/src/generated-wrappers/forwarder.ts b/packages/abi-gen-wrappers/src/generated-wrappers/forwarder.ts index 762f165d8a..d7d643b2ac 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/forwarder.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/forwarder.ts @@ -1501,8 +1501,10 @@ export class ForwarderContract extends BaseContract { const bytecode = artifact.compilerOutput.evm.bytecode.object; const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + if (Object.keys(logDecodeDependencies) !== undefined) { + for (const key of Object.keys(logDecodeDependencies)) { + logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + } } return ForwarderContract.deployAsync( bytecode, diff --git a/packages/abi-gen-wrappers/src/generated-wrappers/i_asset_proxy.ts b/packages/abi-gen-wrappers/src/generated-wrappers/i_asset_proxy.ts index 3354dc9bf3..00b079a261 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/i_asset_proxy.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/i_asset_proxy.ts @@ -1041,8 +1041,10 @@ export class IAssetProxyContract extends BaseContract { const bytecode = artifact.compilerOutput.evm.bytecode.object; const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + if (Object.keys(logDecodeDependencies) !== undefined) { + for (const key of Object.keys(logDecodeDependencies)) { + logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + } } return IAssetProxyContract.deployAsync(bytecode, abi, provider, txDefaults, logDecodeDependenciesAbiOnly); } diff --git a/packages/abi-gen-wrappers/src/generated-wrappers/i_validator.ts b/packages/abi-gen-wrappers/src/generated-wrappers/i_validator.ts index cdbf697fad..86dae30e10 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/i_validator.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/i_validator.ts @@ -137,8 +137,10 @@ export class IValidatorContract extends BaseContract { const bytecode = artifact.compilerOutput.evm.bytecode.object; const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + if (Object.keys(logDecodeDependencies) !== undefined) { + for (const key of Object.keys(logDecodeDependencies)) { + logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + } } return IValidatorContract.deployAsync(bytecode, abi, provider, txDefaults, logDecodeDependenciesAbiOnly); } diff --git a/packages/abi-gen-wrappers/src/generated-wrappers/i_wallet.ts b/packages/abi-gen-wrappers/src/generated-wrappers/i_wallet.ts index 526e852691..042fc5ce5b 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/i_wallet.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/i_wallet.ts @@ -127,8 +127,10 @@ export class IWalletContract extends BaseContract { const bytecode = artifact.compilerOutput.evm.bytecode.object; const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + if (Object.keys(logDecodeDependencies) !== undefined) { + for (const key of Object.keys(logDecodeDependencies)) { + logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + } } return IWalletContract.deployAsync(bytecode, abi, provider, txDefaults, logDecodeDependenciesAbiOnly); } diff --git a/packages/abi-gen-wrappers/src/generated-wrappers/multi_asset_proxy.ts b/packages/abi-gen-wrappers/src/generated-wrappers/multi_asset_proxy.ts index 5ae130a804..676dab94b4 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/multi_asset_proxy.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/multi_asset_proxy.ts @@ -1345,8 +1345,10 @@ export class MultiAssetProxyContract extends BaseContract { const bytecode = artifact.compilerOutput.evm.bytecode.object; const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + if (Object.keys(logDecodeDependencies) !== undefined) { + for (const key of Object.keys(logDecodeDependencies)) { + logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + } } return MultiAssetProxyContract.deployAsync(bytecode, abi, provider, txDefaults, logDecodeDependenciesAbiOnly); } diff --git a/packages/abi-gen-wrappers/src/generated-wrappers/order_validator.ts b/packages/abi-gen-wrappers/src/generated-wrappers/order_validator.ts index 1ae1be1559..b7499f179d 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/order_validator.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/order_validator.ts @@ -1014,8 +1014,10 @@ export class OrderValidatorContract extends BaseContract { const bytecode = artifact.compilerOutput.evm.bytecode.object; const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + if (Object.keys(logDecodeDependencies) !== undefined) { + for (const key of Object.keys(logDecodeDependencies)) { + logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + } } return OrderValidatorContract.deployAsync( bytecode, diff --git a/packages/abi-gen-wrappers/src/generated-wrappers/weth9.ts b/packages/abi-gen-wrappers/src/generated-wrappers/weth9.ts index 0482f5ccb8..208683f64b 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/weth9.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/weth9.ts @@ -1265,8 +1265,10 @@ export class WETH9Contract extends BaseContract { const bytecode = artifact.compilerOutput.evm.bytecode.object; const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + if (Object.keys(logDecodeDependencies) !== undefined) { + for (const key of Object.keys(logDecodeDependencies)) { + logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + } } return WETH9Contract.deployAsync(bytecode, abi, provider, txDefaults, logDecodeDependenciesAbiOnly); } diff --git a/packages/abi-gen-wrappers/src/generated-wrappers/zrx_token.ts b/packages/abi-gen-wrappers/src/generated-wrappers/zrx_token.ts index e43ca69e86..1ff3150abe 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/zrx_token.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/zrx_token.ts @@ -1009,8 +1009,10 @@ export class ZRXTokenContract extends BaseContract { const bytecode = artifact.compilerOutput.evm.bytecode.object; const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + if (Object.keys(logDecodeDependencies) !== undefined) { + for (const key of Object.keys(logDecodeDependencies)) { + logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + } } return ZRXTokenContract.deployAsync(bytecode, abi, provider, txDefaults, logDecodeDependenciesAbiOnly); } diff --git a/packages/abi-gen/test-cli/expected-output/typescript/abi_gen_dummy.ts b/packages/abi-gen/test-cli/expected-output/typescript/abi_gen_dummy.ts index 0ad5d8d9c9..69c45ace05 100644 --- a/packages/abi-gen/test-cli/expected-output/typescript/abi_gen_dummy.ts +++ b/packages/abi-gen/test-cli/expected-output/typescript/abi_gen_dummy.ts @@ -2372,8 +2372,10 @@ export class AbiGenDummyContract extends BaseContract { const bytecode = artifact.compilerOutput.evm.bytecode.object; const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + 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); } diff --git a/packages/abi-gen/test-cli/expected-output/typescript/lib_dummy.ts b/packages/abi-gen/test-cli/expected-output/typescript/lib_dummy.ts index 4a22ff8143..4403bbce8e 100644 --- a/packages/abi-gen/test-cli/expected-output/typescript/lib_dummy.ts +++ b/packages/abi-gen/test-cli/expected-output/typescript/lib_dummy.ts @@ -45,8 +45,10 @@ export class LibDummyContract extends BaseContract { const bytecode = artifact.compilerOutput.evm.bytecode.object; const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + 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); } diff --git a/packages/abi-gen/test-cli/expected-output/typescript/test_lib_dummy.ts b/packages/abi-gen/test-cli/expected-output/typescript/test_lib_dummy.ts index 0c94d83d9f..93d5185886 100644 --- a/packages/abi-gen/test-cli/expected-output/typescript/test_lib_dummy.ts +++ b/packages/abi-gen/test-cli/expected-output/typescript/test_lib_dummy.ts @@ -173,8 +173,10 @@ export class TestLibDummyContract extends BaseContract { const bytecode = artifact.compilerOutput.evm.bytecode.object; const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; - for (const key of Object.keys(logDecodeDependencies)) { - logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; + 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); } diff --git a/packages/asset-buyer/package.json b/packages/asset-buyer/package.json index 0749714e70..70817fc7fa 100644 --- a/packages/asset-buyer/package.json +++ b/packages/asset-buyer/package.json @@ -39,7 +39,7 @@ "dependencies": { "@0x/assert": "^2.1.2", "@0x/connect": "^5.0.15", - "@0x/contract-wrappers": "^10.1.0", + "@0x/contract-wrappers": "10.1.0", "@0x/json-schemas": "^3.1.12", "@0x/order-utils": "^8.2.4", "@0x/subproviders": "^5.0.0", diff --git a/packages/asset-swapper/package.json b/packages/asset-swapper/package.json index 3de01c2bde..5e1f4dcf9d 100644 --- a/packages/asset-swapper/package.json +++ b/packages/asset-swapper/package.json @@ -40,7 +40,7 @@ "@0x/assert": "^2.1.2", "@0x/connect": "^5.0.15", "@0x/contract-addresses": "^3.0.2", - "@0x/contract-wrappers": "^10.1.0", + "@0x/contract-wrappers": "10.1.0", "@0x/dev-utils": "^2.2.6", "@0x/fill-scenarios": "^3.0.15", "@0x/json-schemas": "^3.1.12", diff --git a/packages/asset-swapper/test/exchange_swap_quote_consumer_test.ts b/packages/asset-swapper/test/exchange_swap_quote_consumer_test.ts index ba63f88f25..ae0a9e1efc 100644 --- a/packages/asset-swapper/test/exchange_swap_quote_consumer_test.ts +++ b/packages/asset-swapper/test/exchange_swap_quote_consumer_test.ts @@ -1,6 +1,5 @@ import { ContractAddresses, ContractWrappers } from '@0x/contract-wrappers'; -import { tokenUtils } from '@0x/contract-wrappers/lib/test/utils/token_utils'; -import { BlockchainLifecycle } from '@0x/dev-utils'; +import { BlockchainLifecycle, tokenUtils } from '@0x/dev-utils'; import { FillScenarios } from '@0x/fill-scenarios'; import { assetDataUtils } from '@0x/order-utils'; import { MarketOperation, SignedOrder } from '@0x/types'; diff --git a/packages/asset-swapper/test/forwarder_swap_quote_consumer_test.ts b/packages/asset-swapper/test/forwarder_swap_quote_consumer_test.ts index 68d6178eae..9fef5a35b7 100644 --- a/packages/asset-swapper/test/forwarder_swap_quote_consumer_test.ts +++ b/packages/asset-swapper/test/forwarder_swap_quote_consumer_test.ts @@ -1,6 +1,5 @@ import { ContractAddresses, ContractWrappers } from '@0x/contract-wrappers'; -import { tokenUtils } from '@0x/contract-wrappers/lib/test/utils/token_utils'; -import { BlockchainLifecycle } from '@0x/dev-utils'; +import { BlockchainLifecycle, tokenUtils } from '@0x/dev-utils'; import { assetDataUtils } from '@0x/order-utils'; import { MarketOperation, SignedOrder } from '@0x/types'; import { BigNumber } from '@0x/utils'; diff --git a/packages/asset-swapper/test/swap_quote_consumer_utils_test.ts b/packages/asset-swapper/test/swap_quote_consumer_utils_test.ts index 79f00f5b0f..9ed535c7ce 100644 --- a/packages/asset-swapper/test/swap_quote_consumer_utils_test.ts +++ b/packages/asset-swapper/test/swap_quote_consumer_utils_test.ts @@ -1,6 +1,5 @@ import { ContractAddresses, ContractWrappers } from '@0x/contract-wrappers'; -import { tokenUtils } from '@0x/contract-wrappers/lib/test/utils/token_utils'; -import { BlockchainLifecycle } from '@0x/dev-utils'; +import { BlockchainLifecycle, tokenUtils } from '@0x/dev-utils'; import { assetDataUtils } from '@0x/order-utils'; import { MarketOperation, SignedOrder } from '@0x/types'; import { BigNumber } from '@0x/utils'; diff --git a/packages/contract-wrappers/CHANGELOG.json b/packages/contract-wrappers/CHANGELOG.json index abdffb1266..32397da8de 100644 --- a/packages/contract-wrappers/CHANGELOG.json +++ b/packages/contract-wrappers/CHANGELOG.json @@ -1,4 +1,13 @@ [ + { + "version": "11.0.0", + "changes": [ + { + "note": "Use @0x/abi-gen to generate wrappers. For a full list of changes, see https://github.com/0xProject/0x-monorepo/issues/2040", + "pr": 2037 + } + ] + }, { "version": "10.1.0", "changes": [ diff --git a/packages/contract-wrappers/README.md b/packages/contract-wrappers/README.md index 36f2f48fb4..0ab599a249 100644 --- a/packages/contract-wrappers/README.md +++ b/packages/contract-wrappers/README.md @@ -1,8 +1,6 @@ ## @0x/contract-wrappers -Smart TS wrappers for 0x smart contracts. The wrappers have simplified interfaces, perform client-side validation on transactions and throw helpful error messages. - -### Read the [Documentation](https://0xproject.com/docs/0x.js). +Wrappers for 0x smart contracts, generated using @0x/abi-gen. ## Installation @@ -14,7 +12,7 @@ npm install @0x/contract-wrappers --save **Import** -```javascript +```typescript import { ContractWrappers } from '@0x/contract-wrappers'; ``` @@ -28,7 +26,7 @@ If your project is in [TypeScript](https://www.typescriptlang.org/), add the fol ## 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. +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. @@ -54,22 +52,6 @@ To build this package and all other monorepo packages that it depends on, run th PKG=@0x/contract-wrappers yarn build ``` -Or continuously rebuild on change: - -```bash -PKG=@0x/contract-wrappers yarn watch -``` - -```bash -yarn build -``` - -or continuously rebuild on change: - -```bash -yarn watch -``` - ### Clean ```bash @@ -87,3 +69,9 @@ yarn lint ```bash yarn test ``` + +### Documentation + +Documentation for this package is generated by TypeDoc, using the Solidity source code for 0x contracts. Each contract corresponds to one global-level module, which contains relevant enums and interfaces for its events and structs. Most significantly, each module exports a class, `Contract`, e.g. `ExchangeContract`, which implements helper methods for all the functions defined in the corresponding contract. + +A convention to note is that these contract-specific helper methods are defined as _object literals_, which are separated from methods in the generated documentation. Each contract method has a number of sub-methods, e.g. `sendTransactionAsync`, or `estimateGasAsync`, which are documented separately. This is an example of an expected method call signature: `exchangeContractInstance.fillOrder.sendTransactionAsync(...arguments)`. diff --git a/packages/contract-wrappers/package.json b/packages/contract-wrappers/package.json index 24652027ce..e3a3231ba8 100644 --- a/packages/contract-wrappers/package.json +++ b/packages/contract-wrappers/package.json @@ -1,7 +1,10 @@ { "name": "@0x/contract-wrappers", - "version": "10.1.0", - "description": "Smart TS wrappers for 0x smart contracts", + "version": "11.0.0", + "engines": { + "node": ">=6.12" + }, + "description": "Wrappers for 0x smart contract wrappers generated using @0x/abi-gen", "keywords": [ "0xproject", "ethereum", @@ -10,34 +13,43 @@ ], "main": "lib/src/index.js", "types": "lib/src/index.d.ts", + "directories": { + "test": "test" + }, "scripts": { - "build": "tsc -b", + "build": "yarn pre_build && tsc -b", "build:ci": "yarn build", "lint": "tslint --format stylish --project . --exclude **/lib/**/*", - "fix": "tslint --fix --format stylish --project . --exclude **/lib/**/*", + "fix": "tslint --fix --format stylish --project .--exclude **/lib/**/*", "test:circleci": "run-s test:coverage", "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 lib/test/global_hooks.js --timeout 10000 --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 _bundles lib test_temp generated_docs", - "run_mocha": "mocha --require source-map-support/register --require make-promises-safe lib/test/**/*_test.js lib/test/global_hooks.js --timeout 10000 --bail --exit", - "docs:json": "typedoc --excludePrivate --excludeExternals --target ES5 --tsconfig typedoc-tsconfig.json --json $JSON_FILE_PATH $PROJECT_FILES" + "pre_build": "yarn generate_contract_wrappers && yarn prettier_contract_wrappers", + "prettier": "prettier --write **/* --config ../../.prettierrc", + "prettier_contract_wrappers": "prettier --write src/generated-wrappers/* --config ../../.prettierrc", + "clean": "shx rm -rf lib src/generated-wrappers", + "generate_contract_wrappers": "abi-gen --abis ${npm_package_config_abis} --template ../../node_modules/@0x/abi-gen-templates/contract.handlebars --partials '../../node_modules/@0x/abi-gen-templates/partials/**/*.handlebars' --output src/generated-wrappers --backend ethers", + "docs_test": "typedoc --excludePrivate --excludeExternals --target ES5 --tsconfig typedoc-tsconfig.json --out generated_docs ./src/generated-wrappers/*" }, "config": { - "postpublish": { - "assets": [] - } + "abis": "../contract-artifacts/artifacts/@(AssetProxyOwner|DutchAuction|DummyERC20Token|DummyERC721Token|ERC20Proxy|ERC20Token|ERC721Proxy|ERC721Token|Exchange|Forwarder|IAssetProxy|IValidator|IWallet|MultiAssetProxy|OrderValidator|WETH9|ZRXToken|Coordinator|CoordinatorRegistry|EthBalanceChecker).json" }, "repository": { "type": "git", - "url": "https://github.com/0xProject/0x-monorepo" + "url": "https://github.com/0xProject/0x-monorepo.git" }, "license": "Apache-2.0", - "engines": { - "node": ">=6.0.0" + "bugs": { + "url": "https://github.com/0xProject/0x-monorepo/issues" }, + "homepage": "https://github.com/0xProject/0x-monorepo/packages/contract-wrappers/README.md", "devDependencies": { + "@0x/abi-gen": "^3.1.2", + "@0x/abi-gen-templates": "^2.4.0", + "@0x/assert": "^2.1.2", + "@0x/json-schemas": "^3.1.12", "@0x/contracts-test-utils": "^3.1.12", "@0x/coordinator-server": "^0.1.3", "@0x/dev-utils": "^2.2.6", @@ -45,52 +57,34 @@ "@0x/migrations": "^4.1.11", "@0x/subproviders": "^5.0.0", "@0x/tslint-config": "^3.0.1", - "@types/lodash": "4.14.104", - "@types/mocha": "^5.2.7", - "@types/nock": "^10.0.1", - "@types/node": "*", - "@types/sinon": "^2.2.2", - "@types/uuid": "^3.4.3", - "@types/web3-provider-engine": "^14.0.0", + "@0x/types": "^2.4.1", + "@0x/utils": "^4.4.2", + "@0x/web3-wrapper": "^6.0.9", + "@types/nock": "^10.0.3", + "ethereum-types": "^2.1.4", + "ethers": "~4.0.4", + "lodash": "^4.17.11", + "shx": "^0.2.2", "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", - "nock": "^10.0.6", - "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", - "tslint": "5.11.0", - "typedoc": "0.13.0", - "typescript": "3.0.1", - "web3-provider-engine": "14.0.6" + "nock": "^10.0.6" }, "dependencies": { "@0x/abi-gen-wrappers": "^5.1.0", - "@0x/assert": "^2.1.2", "@0x/base-contract": "^5.3.0", "@0x/contract-addresses": "^3.0.2", "@0x/contract-artifacts": "^2.0.3", - "@0x/json-schemas": "^3.1.12", + "@0x/contracts-test-utils": "^3.1.12", + "@0x/coordinator-server": "^0.1.3", + "@0x/dev-utils": "^2.2.6", + "@0x/fill-scenarios": "^3.0.15", + "@0x/migrations": "^4.1.11", "@0x/order-utils": "^8.2.4", - "@0x/types": "^2.4.1", - "@0x/typescript-typings": "^4.2.4", - "@0x/utils": "^4.4.2", - "@0x/web3-wrapper": "^6.0.9", - "ethereum-types": "^2.1.4", - "ethereumjs-abi": "0.6.5", - "ethereumjs-blockstream": "6.0.0", - "ethereumjs-util": "^5.1.1", - "ethers": "~4.0.4", - "http-status-codes": "^1.3.2", - "js-sha3": "^0.7.0", - "lodash": "^4.17.11", - "uuid": "^3.3.2" + "@0x/subproviders": "^5.0.0", + "http-status-codes": "^1.3.2" }, "publishConfig": { "access": "public" diff --git a/packages/contract-wrappers/src/abstract/abstract_balance_and_proxy_allowance_lazy_store.ts b/packages/contract-wrappers/src/abstract/abstract_balance_and_proxy_allowance_lazy_store.ts deleted file mode 100644 index b095c8e79f..0000000000 --- a/packages/contract-wrappers/src/abstract/abstract_balance_and_proxy_allowance_lazy_store.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { BigNumber } from '@0x/utils'; - -export abstract class AbstractBalanceAndProxyAllowanceLazyStore { - public abstract async getBalanceAsync(tokenAddress: string, userAddress: string): Promise; - public abstract async getProxyAllowanceAsync(tokenAddress: string, userAddress: string): Promise; - public abstract setBalance(tokenAddress: string, userAddress: string, balance: BigNumber): void; - public abstract deleteBalance(tokenAddress: string, userAddress: string): void; - public abstract setProxyAllowance(tokenAddress: string, userAddress: string, proxyAllowance: BigNumber): void; - public abstract deleteProxyAllowance(tokenAddress: string, userAddress: string): void; - public abstract deleteAll(): void; -} diff --git a/packages/contract-wrappers/src/contract_wrappers.ts b/packages/contract-wrappers/src/contract_wrappers.ts index 40b0651558..7eae2ef857 100644 --- a/packages/contract-wrappers/src/contract_wrappers.ts +++ b/packages/contract-wrappers/src/contract_wrappers.ts @@ -15,20 +15,18 @@ import { Web3Wrapper } from '@0x/web3-wrapper'; import { SupportedProvider } from 'ethereum-types'; import * as _ from 'lodash'; -import { CoordinatorWrapper } from './contract_wrappers/coordinator_wrapper'; -import { DutchAuctionWrapper } from './contract_wrappers/dutch_auction_wrapper'; -import { ERC20ProxyWrapper } from './contract_wrappers/erc20_proxy_wrapper'; -import { ERC20TokenWrapper } from './contract_wrappers/erc20_token_wrapper'; -import { ERC721ProxyWrapper } from './contract_wrappers/erc721_proxy_wrapper'; -import { ERC721TokenWrapper } from './contract_wrappers/erc721_token_wrapper'; -import { EtherTokenWrapper } from './contract_wrappers/ether_token_wrapper'; -import { ExchangeWrapper } from './contract_wrappers/exchange_wrapper'; -import { ForwarderWrapper } from './contract_wrappers/forwarder_wrapper'; -import { OrderValidatorWrapper } from './contract_wrappers/order_validator_wrapper'; +import { CoordinatorWrapper } from './coordinator_wrapper'; +import { DutchAuctionContract } from './generated-wrappers/dutch_auction'; +import { ERC20ProxyContract } from './generated-wrappers/erc20_proxy'; +import { ERC721ProxyContract } from './generated-wrappers/erc721_proxy'; +import { ExchangeContract } from './generated-wrappers/exchange'; +import { ForwarderContract } from './generated-wrappers/forwarder'; +import { OrderValidatorContract } from './generated-wrappers/order_validator'; + +import { WETH9Contract } from './generated-wrappers/weth9'; import { ContractWrappersConfigSchema } from './schemas/contract_wrappers_config_schema'; import { ContractWrappersConfig } from './types'; import { assert } from './utils/assert'; -import { constants } from './utils/constants'; import { _getDefaultContractAddresses } from './utils/contract_addresses'; /** @@ -36,45 +34,36 @@ import { _getDefaultContractAddresses } from './utils/contract_addresses'; */ export class ContractWrappers { /** - * An instance of the ExchangeWrapper class containing methods for interacting with the 0x Exchange smart contract. - */ - public exchange: ExchangeWrapper; - /** - * An instance of the ERC20TokenWrapper class containing methods for interacting with any ERC20 token smart contract. - */ - public erc20Token: ERC20TokenWrapper; - /** - * An instance of the ERC721TokenWrapper class containing methods for interacting with any ERC721 token smart contract. - */ - public erc721Token: ERC721TokenWrapper; - /** - * An instance of the EtherTokenWrapper class containing methods for interacting with the - * wrapped ETH ERC20 token smart contract. + * An instance of the ExchangeContract class containing methods for interacting with the 0x Exchange smart contract. */ - public etherToken: EtherTokenWrapper; + public exchange: ExchangeContract; /** - * An instance of the ERC20ProxyWrapper class containing methods for interacting with the + * An instance of the ERC20ProxyContract class containing methods for interacting with the * erc20Proxy smart contract. */ - public erc20Proxy: ERC20ProxyWrapper; + public erc20Proxy: ERC20ProxyContract; /** - * An instance of the ERC721ProxyWrapper class containing methods for interacting with the + * An instance of the ERC721ProxyContract class containing methods for interacting with the * erc721Proxy smart contract. */ - public erc721Proxy: ERC721ProxyWrapper; + public erc721Proxy: ERC721ProxyContract; /** - * An instance of the ForwarderWrapper class containing methods for interacting with any Forwarder smart contract. + * An instance of the WETH9Contract class containing methods for interacting with the + * WETH9 smart contract. */ - public forwarder: ForwarderWrapper; + public weth9: WETH9Contract; /** - * An instance of the OrderValidatorWrapper class containing methods for interacting with any OrderValidator smart contract. + * An instance of the ForwarderContract class containing methods for interacting with any Forwarder smart contract. */ - public orderValidator: OrderValidatorWrapper; + public forwarder: ForwarderContract; /** - * An instance of the DutchAuctionWrapper class containing methods for interacting with any DutchAuction smart contract. + * An instance of the OrderValidatorContract class containing methods for interacting with any OrderValidator smart contract. */ - public dutchAuction: DutchAuctionWrapper; - + public orderValidator: OrderValidatorContract; + /** + * An instance of the DutchAuctionContract class containing methods for interacting with any DutchAuction smart contract. + */ + public dutchAuction: DutchAuctionContract; /** * An instance of the CoordinatorWrapper class containing methods for interacting with the Coordinator extension contract. */ @@ -109,45 +98,17 @@ export class ContractWrappers { _.forEach(artifactsArray, artifact => { this._web3Wrapper.abiDecoder.addABI(artifact.compilerOutput.abi, artifact.contractName); }); - const blockPollingIntervalMs = - config.blockPollingIntervalMs === undefined - ? constants.DEFAULT_BLOCK_POLLING_INTERVAL - : config.blockPollingIntervalMs; const contractAddresses = config.contractAddresses === undefined ? _getDefaultContractAddresses(config.networkId) : config.contractAddresses; - this.erc20Proxy = new ERC20ProxyWrapper(this._web3Wrapper, config.networkId, contractAddresses.erc20Proxy); - this.erc721Proxy = new ERC721ProxyWrapper(this._web3Wrapper, config.networkId, contractAddresses.erc721Proxy); - this.erc20Token = new ERC20TokenWrapper(this._web3Wrapper, this.erc20Proxy, blockPollingIntervalMs); - this.erc721Token = new ERC721TokenWrapper(this._web3Wrapper, this.erc721Proxy, blockPollingIntervalMs); - this.etherToken = new EtherTokenWrapper(this._web3Wrapper, this.erc20Token, blockPollingIntervalMs); - this.exchange = new ExchangeWrapper( - this._web3Wrapper, - config.networkId, - this.erc20Token, - this.erc721Token, - contractAddresses.exchange, - contractAddresses.zrxToken, - blockPollingIntervalMs, - ); - this.forwarder = new ForwarderWrapper( - this._web3Wrapper, - config.networkId, - contractAddresses.forwarder, - contractAddresses.zrxToken, - contractAddresses.etherToken, - ); - this.orderValidator = new OrderValidatorWrapper( - this._web3Wrapper, - config.networkId, - contractAddresses.orderValidator, - ); - this.dutchAuction = new DutchAuctionWrapper( - this._web3Wrapper, - config.networkId, - contractAddresses.dutchAuction, - ); + this.erc20Proxy = new ERC20ProxyContract(contractAddresses.erc20Proxy, this.getProvider()); + this.erc721Proxy = new ERC721ProxyContract(contractAddresses.erc721Proxy, this.getProvider()); + this.weth9 = new WETH9Contract(contractAddresses.etherToken, this.getProvider()); + this.exchange = new ExchangeContract(contractAddresses.exchange, this.getProvider()); + this.forwarder = new ForwarderContract(contractAddresses.forwarder, this.getProvider()); + this.orderValidator = new OrderValidatorContract(contractAddresses.orderValidator, this.getProvider()); + this.dutchAuction = new DutchAuctionContract(contractAddresses.dutchAuction, this.getProvider()); this.coordinator = new CoordinatorWrapper( this._web3Wrapper, config.networkId, @@ -161,9 +122,9 @@ export class ContractWrappers { */ public unsubscribeAll(): void { this.exchange.unsubscribeAll(); - this.erc20Token.unsubscribeAll(); - this.erc721Token.unsubscribeAll(); - this.etherToken.unsubscribeAll(); + this.erc20Proxy.unsubscribeAll(); + this.erc721Proxy.unsubscribeAll(); + this.weth9.unsubscribeAll(); } /** * Get the provider instance currently used by contract-wrappers diff --git a/packages/contract-wrappers/src/contract_wrappers/dutch_auction_wrapper.ts b/packages/contract-wrappers/src/contract_wrappers/dutch_auction_wrapper.ts deleted file mode 100644 index 1cc8625acc..0000000000 --- a/packages/contract-wrappers/src/contract_wrappers/dutch_auction_wrapper.ts +++ /dev/null @@ -1,138 +0,0 @@ -import { DutchAuctionContract } from '@0x/abi-gen-wrappers'; -import { DutchAuction } from '@0x/contract-artifacts'; -import { schemas } from '@0x/json-schemas'; -import { assetDataUtils } from '@0x/order-utils'; -import { DutchAuctionData, DutchAuctionDetails, SignedOrder } from '@0x/types'; -import { BigNumber } from '@0x/utils'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import { ContractAbi } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { orderTxOptsSchema } from '../schemas/order_tx_opts_schema'; -import { txOptsSchema } from '../schemas/tx_opts_schema'; -import { DutchAuctionWrapperError, OrderTransactionOpts } from '../types'; -import { assert } from '../utils/assert'; -import { _getDefaultContractAddresses } from '../utils/contract_addresses'; - -export class DutchAuctionWrapper { - public abi: ContractAbi = DutchAuction.compilerOutput.abi; - public address: string; - private readonly _web3Wrapper: Web3Wrapper; - private readonly _dutchAuctionContract: DutchAuctionContract; - /** - * Dutch auction details are encoded with the asset data for a 0x order. This function produces a hex - * encoded assetData string, containing information both about the asset being traded and the - * dutch auction; which is usable in the makerAssetData or takerAssetData fields in a 0x order. - * @param assetData Hex encoded assetData string for the asset being auctioned. - * @param beginTimeSeconds Begin time of the dutch auction. - * @param beginAmount Starting amount being sold in the dutch auction. - * @return The hex encoded assetData string. - */ - public static encodeDutchAuctionAssetData( - assetData: string, - beginTimeSeconds: BigNumber, - beginAmount: BigNumber, - ): string { - const dutchAuctionData = assetDataUtils.encodeDutchAuctionAssetData(assetData, beginTimeSeconds, beginAmount); - return dutchAuctionData; - } - /** - * Dutch auction details are encoded with the asset data for a 0x order. This function decodes a hex - * encoded assetData string, containing information both about the asset being traded and the - * dutch auction. - * @param dutchAuctionData Hex encoded assetData string for the asset being auctioned. - * @return An object containing the auction asset, auction begin time and auction begin amount. - */ - public static decodeDutchAuctionData(dutchAuctionData: string): DutchAuctionData { - const decoded = assetDataUtils.decodeDutchAuctionData(dutchAuctionData); - return decoded; - } - /** - * Instantiate DutchAuctionWrapper - * @param web3Wrapper Web3Wrapper instance to use. - * @param networkId Desired networkId. - * @param address The address of the Dutch Auction contract. If undefined, will - * default to the known address corresponding to the networkId. - */ - public constructor(web3Wrapper: Web3Wrapper, networkId: number, address?: string) { - this.address = address === undefined ? _getDefaultContractAddresses(networkId).dutchAuction : address; - this._web3Wrapper = web3Wrapper; - this._dutchAuctionContract = new DutchAuctionContract( - this.address, - this._web3Wrapper.getProvider(), - this._web3Wrapper.getContractDefaults(), - ); - } - /** - * Matches the buy and sell orders at an amount given the following: the current block time, the auction - * start time and the auction begin amount. The sell order is a an order at the lowest amount - * at the end of the auction. Excess from the match is transferred to the seller. - * Over time the price moves from beginAmount to endAmount given the current block.timestamp. - * @param buyOrder The Buyer's order. This order is for the current expected price of the auction. - * @param sellOrder The Seller's order. This order is for the lowest amount (at the end of the auction). - * @param takerAddress The user Ethereum address who would like to fill this order. Must be available via the supplied - * Provider provided at instantiation. - * @return Transaction hash. - */ - public async matchOrdersAsync( - buyOrder: SignedOrder, - sellOrder: SignedOrder, - takerAddress: string, - orderTransactionOpts: OrderTransactionOpts = { shouldValidate: true }, - ): Promise { - // type assertions - assert.doesConformToSchema('buyOrder', buyOrder, schemas.signedOrderSchema); - assert.doesConformToSchema('sellOrder', sellOrder, schemas.signedOrderSchema); - await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); - assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); - const normalizedTakerAddress = takerAddress.toLowerCase(); - // other assertions - if ( - sellOrder.makerAssetData !== buyOrder.takerAssetData || - sellOrder.takerAssetData !== buyOrder.makerAssetData - ) { - throw new Error(DutchAuctionWrapperError.AssetDataMismatch); - } - // validate transaction - if (orderTransactionOpts.shouldValidate) { - await this._dutchAuctionContract.matchOrders.callAsync( - buyOrder, - sellOrder, - buyOrder.signature, - sellOrder.signature, - { - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }, - ); - } - // send transaction - const txHash = await this._dutchAuctionContract.matchOrders.sendTransactionAsync( - buyOrder, - sellOrder, - buyOrder.signature, - sellOrder.signature, - { - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }, - ); - return txHash; - } - /** - * Fetches the Auction Details for the given order - * @param sellOrder The Seller's order. This order is for the lowest amount (at the end of the auction). - * @return The dutch auction details. - */ - public async getAuctionDetailsAsync(sellOrder: SignedOrder): Promise { - // type assertions - assert.doesConformToSchema('sellOrder', sellOrder, schemas.signedOrderSchema); - // call contract - const auctionDetails = await this._dutchAuctionContract.getAuctionDetails.callAsync(sellOrder); - return auctionDetails; - } -} diff --git a/packages/contract-wrappers/src/contract_wrappers/erc20_proxy_wrapper.ts b/packages/contract-wrappers/src/contract_wrappers/erc20_proxy_wrapper.ts deleted file mode 100644 index 88af962471..0000000000 --- a/packages/contract-wrappers/src/contract_wrappers/erc20_proxy_wrapper.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { ERC20ProxyContract } from '@0x/abi-gen-wrappers'; -import { ERC20Proxy } from '@0x/contract-artifacts'; -import { AssetProxyId } from '@0x/types'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import { ContractAbi } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { assert } from '../utils/assert'; -import { _getDefaultContractAddresses } from '../utils/contract_addresses'; - -/** - * This class includes the functionality related to interacting with the ERC20Proxy contract. - */ -export class ERC20ProxyWrapper { - public abi: ContractAbi = ERC20Proxy.compilerOutput.abi; - public address: string; - private readonly _web3Wrapper: Web3Wrapper; - private readonly _erc20ProxyContract: ERC20ProxyContract; - /** - * Instantiate ERC20ProxyWrapper - * @param web3Wrapper Web3Wrapper instance to use - * @param networkId Desired networkId - * @param address The address of the ERC20Proxy contract. If undefined, will - * default to the known address corresponding to the networkId. - */ - constructor(web3Wrapper: Web3Wrapper, networkId: number, address?: string) { - this._web3Wrapper = web3Wrapper; - this.address = address === undefined ? _getDefaultContractAddresses(networkId).erc20Proxy : address; - this._erc20ProxyContract = new ERC20ProxyContract( - this.address, - this._web3Wrapper.getProvider(), - this._web3Wrapper.getContractDefaults(), - ); - } - /** - * Get the 4 bytes ID of this asset proxy - * @return Proxy id - */ - public async getProxyIdAsync(): Promise { - // Note(albrow): Below is a TSLint false positive. Code won't compile if - // you remove the type assertion. - /* tslint:disable-next-line:no-unnecessary-type-assertion */ - const proxyId = (await this._erc20ProxyContract.getProxyId.callAsync()) as AssetProxyId; - return proxyId; - } - /** - * Check if the Exchange contract address is authorized by the ERC20Proxy contract. - * @param exchangeContractAddress The hex encoded address of the Exchange contract to call. - * @return Whether the exchangeContractAddress is authorized. - */ - public async isAuthorizedAsync(exchangeContractAddress: string): Promise { - assert.isETHAddressHex('exchangeContractAddress', exchangeContractAddress); - const normalizedExchangeContractAddress = exchangeContractAddress.toLowerCase(); - const isAuthorized = await this._erc20ProxyContract.authorized.callAsync(normalizedExchangeContractAddress); - return isAuthorized; - } - /** - * Get the list of all Exchange contract addresses authorized by the ERC20Proxy contract. - * @return The list of authorized addresses. - */ - public async getAuthorizedAddressesAsync(): Promise { - const authorizedAddresses = await this._erc20ProxyContract.getAuthorizedAddresses.callAsync(); - return authorizedAddresses; - } -} diff --git a/packages/contract-wrappers/src/contract_wrappers/erc20_token_wrapper.ts b/packages/contract-wrappers/src/contract_wrappers/erc20_token_wrapper.ts deleted file mode 100644 index 3944424380..0000000000 --- a/packages/contract-wrappers/src/contract_wrappers/erc20_token_wrapper.ts +++ /dev/null @@ -1,444 +0,0 @@ -import { ERC20TokenContract, ERC20TokenEventArgs, ERC20TokenEvents } from '@0x/abi-gen-wrappers'; -import { SubscriptionManager } from '@0x/base-contract'; -import { ERC20Token } from '@0x/contract-artifacts'; -import { schemas } from '@0x/json-schemas'; -import { BigNumber } from '@0x/utils'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import { ContractAbi, LogWithDecodedArgs } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { methodOptsSchema } from '../schemas/method_opts_schema'; -import { txOptsSchema } from '../schemas/tx_opts_schema'; -import { - BlockRange, - ContractWrappersError, - EventCallback, - IndexedFilterValues, - MethodOpts, - TransactionOpts, -} from '../types'; -import { assert } from '../utils/assert'; -import { constants } from '../utils/constants'; -import { utils } from '../utils/utils'; - -import { ERC20ProxyWrapper } from './erc20_proxy_wrapper'; - -/** - * This class includes all the functionality related to interacting with ERC20 token contracts. - * All ERC20 method calls are supported, along with some convenience methods for getting/setting allowances - * to the 0x ERC20 Proxy smart contract. - */ -export class ERC20TokenWrapper { - public abi: ContractAbi = ERC20Token.compilerOutput.abi; - public UNLIMITED_ALLOWANCE_IN_BASE_UNITS = constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS; - private readonly _web3Wrapper: Web3Wrapper; - private readonly _blockPollingIntervalMs?: number; - private readonly _subscriptionManager: SubscriptionManager; - private readonly _tokenContractsByAddress: { [address: string]: ERC20TokenContract }; - private readonly _erc20ProxyWrapper: ERC20ProxyWrapper; - /** - * Instantiate ERC20TokenWrapper - * @param web3Wrapper Web3Wrapper instance to use - * @param erc20ProxyWrapper The ERC20ProxyWrapper instance to use - */ - constructor(web3Wrapper: Web3Wrapper, erc20ProxyWrapper: ERC20ProxyWrapper, blockPollingIntervalMs?: number) { - this._web3Wrapper = web3Wrapper; - this._tokenContractsByAddress = {}; - this._erc20ProxyWrapper = erc20ProxyWrapper; - this._blockPollingIntervalMs = blockPollingIntervalMs; - this._subscriptionManager = new SubscriptionManager( - ERC20TokenContract.ABI(), - web3Wrapper, - ); - } - /** - * Retrieves an owner's ERC20 token balance. - * @param tokenAddress The hex encoded contract Ethereum address where the ERC20 token is deployed. - * @param ownerAddress The hex encoded user Ethereum address whose balance you would like to check. - * @param methodOpts Optional arguments this method accepts. - * @return The owner's ERC20 token balance in base units. - */ - public async getBalanceAsync( - tokenAddress: string, - ownerAddress: string, - methodOpts: MethodOpts = {}, - ): Promise { - assert.isETHAddressHex('ownerAddress', ownerAddress); - assert.isETHAddressHex('tokenAddress', tokenAddress); - assert.doesConformToSchema('methodOpts', methodOpts, methodOptsSchema); - const normalizedTokenAddress = tokenAddress.toLowerCase(); - const normalizedOwnerAddress = ownerAddress.toLowerCase(); - - const tokenContract = await this._getTokenContractAsync(normalizedTokenAddress); - - const txData = {}; - let balance = await tokenContract.balanceOf.callAsync(normalizedOwnerAddress, txData, methodOpts.defaultBlock); - // Wrap BigNumbers returned from web3 with our own (later) version of BigNumber - balance = new BigNumber(balance); - return balance; - } - /** - * Sets the spender's allowance to a specified number of baseUnits on behalf of the owner address. - * Equivalent to the ERC20 spec method `approve`. - * @param tokenAddress The hex encoded contract Ethereum address where the ERC20 token is deployed. - * @param ownerAddress The hex encoded user Ethereum address who would like to set an allowance - * for spenderAddress. - * @param spenderAddress The hex encoded user Ethereum address who will be able to spend the set allowance. - * @param amountInBaseUnits The allowance amount you would like to set. - * @param txOpts Transaction parameters. - * @return Transaction hash. - */ - public async setAllowanceAsync( - tokenAddress: string, - ownerAddress: string, - spenderAddress: string, - amountInBaseUnits: BigNumber, - txOpts: TransactionOpts = {}, - ): Promise { - assert.isETHAddressHex('tokenAddress', tokenAddress); - await assert.isSenderAddressAsync('ownerAddress', ownerAddress, this._web3Wrapper); - assert.isETHAddressHex('spenderAddress', spenderAddress); - assert.isValidBaseUnitAmount('amountInBaseUnits', amountInBaseUnits); - assert.doesConformToSchema('txOpts', txOpts, txOptsSchema); - const normalizedTokenAddress = tokenAddress.toLowerCase(); - const normalizedOwnerAddress = ownerAddress.toLowerCase(); - const normalizedSpenderAddress = spenderAddress.toLowerCase(); - - const tokenContract = await this._getTokenContractAsync(normalizedTokenAddress); - const txHash = await tokenContract.approve.sendTransactionAsync( - normalizedSpenderAddress, - amountInBaseUnits, - utils.removeUndefinedProperties({ - from: normalizedOwnerAddress, - gas: txOpts.gasLimit, - gasPrice: txOpts.gasPrice, - nonce: txOpts.nonce, - }), - ); - return txHash; - } - /** - * Sets the spender's allowance to an unlimited number of baseUnits on behalf of the owner address. - * Equivalent to the ERC20 spec method `approve`. - * Setting an unlimited allowance will lower the gas cost for filling orders involving tokens that forego updating - * allowances set to the max amount (e.g ZRX, WETH) - * @param tokenAddress The hex encoded contract Ethereum address where the ERC20 token is deployed. - * @param ownerAddress The hex encoded user Ethereum address who would like to set an allowance - * for spenderAddress. - * @param spenderAddress The hex encoded user Ethereum address who will be able to spend the set allowance. - * @param txOpts Transaction parameters. - * @return Transaction hash. - */ - public async setUnlimitedAllowanceAsync( - tokenAddress: string, - ownerAddress: string, - spenderAddress: string, - txOpts: TransactionOpts = {}, - ): Promise { - const txHash = await this.setAllowanceAsync( - tokenAddress, - ownerAddress, - spenderAddress, - this.UNLIMITED_ALLOWANCE_IN_BASE_UNITS, - txOpts, - ); - return txHash; - } - /** - * Retrieves the owners allowance in baseUnits set to the spender's address. - * @param tokenAddress The hex encoded contract Ethereum address where the ERC20 token is deployed. - * @param ownerAddress The hex encoded user Ethereum address whose allowance to spenderAddress - * you would like to retrieve. - * @param spenderAddress The hex encoded user Ethereum address who can spend the allowance you are fetching. - * @param methodOpts Optional arguments this method accepts. - */ - public async getAllowanceAsync( - tokenAddress: string, - ownerAddress: string, - spenderAddress: string, - methodOpts: MethodOpts = {}, - ): Promise { - assert.isETHAddressHex('tokenAddress', tokenAddress); - assert.isETHAddressHex('ownerAddress', ownerAddress); - assert.isETHAddressHex('spenderAddress', spenderAddress); - assert.doesConformToSchema('methodOpts', methodOpts, methodOptsSchema); - const normalizedTokenAddress = tokenAddress.toLowerCase(); - const normalizedOwnerAddress = ownerAddress.toLowerCase(); - const normalizedSpenderAddress = spenderAddress.toLowerCase(); - - const tokenContract = await this._getTokenContractAsync(normalizedTokenAddress); - - const txData = {}; - let allowanceInBaseUnits = await tokenContract.allowance.callAsync( - normalizedOwnerAddress, - normalizedSpenderAddress, - txData, - methodOpts.defaultBlock, - ); - // Wrap BigNumbers returned from web3 with our own (later) version of BigNumber - allowanceInBaseUnits = new BigNumber(allowanceInBaseUnits); - return allowanceInBaseUnits; - } - /** - * Retrieves the owner's allowance in baseUnits set to the 0x proxy contract. - * @param tokenAddress The hex encoded contract Ethereum address where the ERC20 token is deployed. - * @param ownerAddress The hex encoded user Ethereum address whose proxy contract allowance we are retrieving. - * @param methodOpts Optional arguments this method accepts. - */ - public async getProxyAllowanceAsync( - tokenAddress: string, - ownerAddress: string, - methodOpts: MethodOpts = {}, - ): Promise { - const proxyAddress = this._erc20ProxyWrapper.address; - const allowanceInBaseUnits = await this.getAllowanceAsync(tokenAddress, ownerAddress, proxyAddress, methodOpts); - return allowanceInBaseUnits; - } - /** - * Sets the 0x proxy contract's allowance to a specified number of a tokens' baseUnits on behalf - * of an owner address. - * @param tokenAddress The hex encoded contract Ethereum address where the ERC20 token is deployed. - * @param ownerAddress The hex encoded user Ethereum address who is setting an allowance - * for the Proxy contract. - * @param amountInBaseUnits The allowance amount specified in baseUnits. - * @param txOpts Transaction parameters. - * @return Transaction hash. - */ - public async setProxyAllowanceAsync( - tokenAddress: string, - ownerAddress: string, - amountInBaseUnits: BigNumber, - txOpts: TransactionOpts = {}, - ): Promise { - const proxyAddress = this._erc20ProxyWrapper.address; - const txHash = await this.setAllowanceAsync( - tokenAddress, - ownerAddress, - proxyAddress, - amountInBaseUnits, - txOpts, - ); - return txHash; - } - /** - * Sets the 0x proxy contract's allowance to a unlimited number of a tokens' baseUnits on behalf - * of an owner address. - * Setting an unlimited allowance will lower the gas cost for filling orders involving tokens that forego updating - * allowances set to the max amount (e.g ZRX, WETH) - * @param tokenAddress The hex encoded contract Ethereum address where the ERC20 token is deployed. - * @param ownerAddress The hex encoded user Ethereum address who is setting an allowance - * for the Proxy contract. - * @param txOpts Transaction parameters. - * @return Transaction hash. - */ - public async setUnlimitedProxyAllowanceAsync( - tokenAddress: string, - ownerAddress: string, - txOpts: TransactionOpts = {}, - ): Promise { - const txHash = await this.setProxyAllowanceAsync( - tokenAddress, - ownerAddress, - this.UNLIMITED_ALLOWANCE_IN_BASE_UNITS, - txOpts, - ); - return txHash; - } - /** - * Transfers `amountInBaseUnits` ERC20 tokens from `fromAddress` to `toAddress`. - * @param tokenAddress The hex encoded contract Ethereum address where the ERC20 token is deployed. - * @param fromAddress The hex encoded user Ethereum address that will send the funds. - * @param toAddress The hex encoded user Ethereum address that will receive the funds. - * @param amountInBaseUnits The amount (specified in baseUnits) of the token to transfer. - * @param txOpts Transaction parameters. - * @return Transaction hash. - */ - public async transferAsync( - tokenAddress: string, - fromAddress: string, - toAddress: string, - amountInBaseUnits: BigNumber, - txOpts: TransactionOpts = {}, - ): Promise { - assert.isETHAddressHex('tokenAddress', tokenAddress); - await assert.isSenderAddressAsync('fromAddress', fromAddress, this._web3Wrapper); - assert.isETHAddressHex('toAddress', toAddress); - assert.isValidBaseUnitAmount('amountInBaseUnits', amountInBaseUnits); - assert.doesConformToSchema('txOpts', txOpts, txOptsSchema); - const normalizedTokenAddress = tokenAddress.toLowerCase(); - const normalizedFromAddress = fromAddress.toLowerCase(); - const normalizedToAddress = toAddress.toLowerCase(); - - const tokenContract = await this._getTokenContractAsync(normalizedTokenAddress); - - const fromAddressBalance = await this.getBalanceAsync(normalizedTokenAddress, normalizedFromAddress); - if (fromAddressBalance.isLessThan(amountInBaseUnits)) { - throw new Error(ContractWrappersError.InsufficientBalanceForTransfer); - } - - const txHash = await tokenContract.transfer.sendTransactionAsync( - normalizedToAddress, - amountInBaseUnits, - utils.removeUndefinedProperties({ - from: normalizedFromAddress, - gas: txOpts.gasLimit, - gasPrice: txOpts.gasPrice, - nonce: txOpts.nonce, - }), - ); - return txHash; - } - /** - * Transfers `amountInBaseUnits` ERC20 tokens from `fromAddress` to `toAddress`. - * Requires the fromAddress to have sufficient funds and to have approved an allowance of - * `amountInBaseUnits` to `senderAddress`. - * @param tokenAddress The hex encoded contract Ethereum address where the ERC20 token is deployed. - * @param fromAddress The hex encoded user Ethereum address whose funds are being sent. - * @param toAddress The hex encoded user Ethereum address that will receive the funds. - * @param senderAddress The hex encoded user Ethereum address whose initiates the fund transfer. The - * `fromAddress` must have set an allowance to the `senderAddress` - * before this call. - * @param amountInBaseUnits The amount (specified in baseUnits) of the token to transfer. - * @param txOpts Transaction parameters. - * @return Transaction hash. - */ - public async transferFromAsync( - tokenAddress: string, - fromAddress: string, - toAddress: string, - senderAddress: string, - amountInBaseUnits: BigNumber, - txOpts: TransactionOpts = {}, - ): Promise { - assert.isETHAddressHex('tokenAddress', tokenAddress); - assert.isETHAddressHex('fromAddress', fromAddress); - assert.isETHAddressHex('toAddress', toAddress); - await assert.isSenderAddressAsync('senderAddress', senderAddress, this._web3Wrapper); - assert.isValidBaseUnitAmount('amountInBaseUnits', amountInBaseUnits); - assert.doesConformToSchema('txOpts', txOpts, txOptsSchema); - const normalizedToAddress = toAddress.toLowerCase(); - const normalizedFromAddress = fromAddress.toLowerCase(); - const normalizedTokenAddress = tokenAddress.toLowerCase(); - const normalizedSenderAddress = senderAddress.toLowerCase(); - - const tokenContract = await this._getTokenContractAsync(normalizedTokenAddress); - - const fromAddressAllowance = await this.getAllowanceAsync( - normalizedTokenAddress, - normalizedFromAddress, - normalizedSenderAddress, - ); - if (fromAddressAllowance.isLessThan(amountInBaseUnits)) { - throw new Error(ContractWrappersError.InsufficientAllowanceForTransfer); - } - - const fromAddressBalance = await this.getBalanceAsync(normalizedTokenAddress, normalizedFromAddress); - if (fromAddressBalance.isLessThan(amountInBaseUnits)) { - throw new Error(ContractWrappersError.InsufficientBalanceForTransfer); - } - - const txHash = await tokenContract.transferFrom.sendTransactionAsync( - normalizedFromAddress, - normalizedToAddress, - amountInBaseUnits, - utils.removeUndefinedProperties({ - from: normalizedSenderAddress, - gas: txOpts.gasLimit, - gasPrice: txOpts.gasPrice, - nonce: txOpts.nonce, - }), - ); - return txHash; - } - /** - * Subscribe to an event type emitted by the Token contract. - * @param tokenAddress The hex encoded address where the ERC20 token is deployed. - * @param eventName The token 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( - tokenAddress: string, - eventName: ERC20TokenEvents, - indexFilterValues: IndexedFilterValues, - callback: EventCallback, - isVerbose: boolean = false, - ): string { - assert.isETHAddressHex('tokenAddress', tokenAddress); - assert.doesBelongToStringEnum('eventName', eventName, ERC20TokenEvents); - assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); - assert.isFunction('callback', callback); - const normalizedTokenAddress = tokenAddress.toLowerCase(); - const subscriptionToken = this._subscriptionManager.subscribe( - normalizedTokenAddress, - eventName, - indexFilterValues, - ERC20Token.compilerOutput.abi, - callback, - isVerbose, - this._blockPollingIntervalMs, - ); - return subscriptionToken; - } - /** - * Cancel a subscription - * @param subscriptionToken Subscription token returned by `subscribe()` - */ - public unsubscribe(subscriptionToken: string): void { - assert.isValidSubscriptionToken('subscriptionToken', subscriptionToken); - this._subscriptionManager.unsubscribe(subscriptionToken); // doesn't matter which contract is used - } - /** - * Cancels all existing subscriptions - */ - public unsubscribeAll(): void { - this._subscriptionManager.unsubscribeAll(); - } - /** - * Gets historical logs without creating a subscription - * @param tokenAddress An address of the token that emitted the logs. - * @param eventName The token 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( - tokenAddress: string, - eventName: ERC20TokenEvents, - blockRange: BlockRange, - indexFilterValues: IndexedFilterValues, - ): Promise>> { - assert.isETHAddressHex('tokenAddress', tokenAddress); - assert.doesBelongToStringEnum('eventName', eventName, ERC20TokenEvents); - assert.doesConformToSchema('blockRange', blockRange, schemas.blockRangeSchema); - assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); - const normalizedTokenAddress = tokenAddress.toLowerCase(); - const logs = await this._subscriptionManager.getLogsAsync( - normalizedTokenAddress, - eventName, - blockRange, - indexFilterValues, - ERC20Token.compilerOutput.abi, - ); - return logs; - } - private async _getTokenContractAsync(tokenAddress: string): Promise { - const normalizedTokenAddress = tokenAddress.toLowerCase(); - let tokenContract = this._tokenContractsByAddress[normalizedTokenAddress]; - if (tokenContract !== undefined) { - return tokenContract; - } - const contractInstance = new ERC20TokenContract( - normalizedTokenAddress, - this._web3Wrapper.getProvider(), - this._web3Wrapper.getContractDefaults(), - ); - tokenContract = contractInstance; - this._tokenContractsByAddress[normalizedTokenAddress] = tokenContract; - return tokenContract; - } -} diff --git a/packages/contract-wrappers/src/contract_wrappers/erc721_proxy_wrapper.ts b/packages/contract-wrappers/src/contract_wrappers/erc721_proxy_wrapper.ts deleted file mode 100644 index 30fe1e77c6..0000000000 --- a/packages/contract-wrappers/src/contract_wrappers/erc721_proxy_wrapper.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { ERC721ProxyContract } from '@0x/abi-gen-wrappers'; -import { ERC721Proxy } from '@0x/contract-artifacts'; -import { AssetProxyId } from '@0x/types'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import { ContractAbi } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { assert } from '../utils/assert'; -import { _getDefaultContractAddresses } from '../utils/contract_addresses'; - -/** - * This class includes the functionality related to interacting with the ERC721Proxy contract. - */ -export class ERC721ProxyWrapper { - public abi: ContractAbi = ERC721Proxy.compilerOutput.abi; - public address: string; - private readonly _web3Wrapper: Web3Wrapper; - private readonly _erc721ProxyContract: ERC721ProxyContract; - /** - * Instantiate ERC721ProxyWrapper - * @param web3Wrapper Web3Wrapper instance to use - * @param networkId Desired networkId - * @param address The address of the ERC721Proxy contract. If undefined, - * will default to the known address corresponding to the networkId. - */ - constructor(web3Wrapper: Web3Wrapper, networkId: number, address?: string) { - this._web3Wrapper = web3Wrapper; - this.address = address === undefined ? _getDefaultContractAddresses(networkId).erc721Proxy : address; - this._erc721ProxyContract = new ERC721ProxyContract( - this.address, - this._web3Wrapper.getProvider(), - this._web3Wrapper.getContractDefaults(), - ); - } - /** - * Get the 4 bytes ID of this asset proxy - * @return Proxy id - */ - public async getProxyIdAsync(): Promise { - // Note(albrow): Below is a TSLint false positive. Code won't compile if - // you remove the type assertion. - /* tslint:disable-next-line:no-unnecessary-type-assertion */ - const proxyId = (await this._erc721ProxyContract.getProxyId.callAsync()) as AssetProxyId; - return proxyId; - } - /** - * Check if the Exchange contract address is authorized by the ERC721Proxy contract. - * @param exchangeContractAddress The hex encoded address of the Exchange contract to call. - * @return Whether the exchangeContractAddress is authorized. - */ - public async isAuthorizedAsync(exchangeContractAddress: string): Promise { - assert.isETHAddressHex('exchangeContractAddress', exchangeContractAddress); - const normalizedExchangeContractAddress = exchangeContractAddress.toLowerCase(); - const isAuthorized = await this._erc721ProxyContract.authorized.callAsync(normalizedExchangeContractAddress); - return isAuthorized; - } - /** - * Get the list of all Exchange contract addresses authorized by the ERC721Proxy contract. - * @return The list of authorized addresses. - */ - public async getAuthorizedAddressesAsync(): Promise { - const authorizedAddresses = await this._erc721ProxyContract.getAuthorizedAddresses.callAsync(); - return authorizedAddresses; - } -} diff --git a/packages/contract-wrappers/src/contract_wrappers/erc721_token_wrapper.ts b/packages/contract-wrappers/src/contract_wrappers/erc721_token_wrapper.ts deleted file mode 100644 index 8b6711daae..0000000000 --- a/packages/contract-wrappers/src/contract_wrappers/erc721_token_wrapper.ts +++ /dev/null @@ -1,471 +0,0 @@ -import { ERC721TokenContract, ERC721TokenEventArgs, ERC721TokenEvents } from '@0x/abi-gen-wrappers'; -import { SubscriptionManager } from '@0x/base-contract'; -import { ERC721Token } from '@0x/contract-artifacts'; -import { schemas } from '@0x/json-schemas'; -import { BigNumber } from '@0x/utils'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import { ContractAbi, LogWithDecodedArgs } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { methodOptsSchema } from '../schemas/method_opts_schema'; -import { txOptsSchema } from '../schemas/tx_opts_schema'; -import { - BlockRange, - ContractWrappersError, - EventCallback, - IndexedFilterValues, - MethodOpts, - TransactionOpts, -} from '../types'; -import { assert } from '../utils/assert'; -import { constants } from '../utils/constants'; -import { utils } from '../utils/utils'; - -import { ERC721ProxyWrapper } from './erc721_proxy_wrapper'; - -/** - * This class includes all the functionality related to interacting with ERC721 token contracts. - * All ERC721 method calls are supported, along with some convenience methods for getting/setting allowances - * to the 0x ERC721 Proxy smart contract. - */ -export class ERC721TokenWrapper { - public abi: ContractAbi = ERC721Token.compilerOutput.abi; - private readonly _web3Wrapper: Web3Wrapper; - private readonly _subscriptionManager: SubscriptionManager; - private readonly _blockPollingIntervalMs?: number; - private readonly _tokenContractsByAddress: { [address: string]: ERC721TokenContract }; - private readonly _erc721ProxyWrapper: ERC721ProxyWrapper; - /** - * Instantiate ERC721TokenWrapper - * @param web3Wrapper Web3Wrapper instance to use - * @param erc721ProxyWrapper The ERC721ProxyWrapper instance to use - */ - constructor(web3Wrapper: Web3Wrapper, erc721ProxyWrapper: ERC721ProxyWrapper, blockPollingIntervalMs?: number) { - this._web3Wrapper = web3Wrapper; - this._tokenContractsByAddress = {}; - this._erc721ProxyWrapper = erc721ProxyWrapper; - this._blockPollingIntervalMs = blockPollingIntervalMs; - this._subscriptionManager = new SubscriptionManager( - ERC721TokenContract.ABI(), - web3Wrapper, - ); - } - /** - * Count all NFTs assigned to an owner - * NFTs assigned to the zero address are considered invalid, and this function throws for queries about the zero address. - * @param tokenAddress The hex encoded contract Ethereum address where the ERC721 token is deployed. - * @param ownerAddress The hex encoded user Ethereum address whose balance you would like to check. - * @param methodOpts Optional arguments this method accepts. - * @return The number of NFTs owned by `ownerAddress`, possibly zero - */ - public async getTokenCountAsync( - tokenAddress: string, - ownerAddress: string, - methodOpts: MethodOpts = {}, - ): Promise { - assert.isETHAddressHex('tokenAddress', tokenAddress); - assert.isETHAddressHex('ownerAddress', ownerAddress); - assert.doesConformToSchema('methodOpts', methodOpts, methodOptsSchema); - const normalizedTokenAddress = tokenAddress.toLowerCase(); - const normalizedOwnerAddress = ownerAddress.toLowerCase(); - - const tokenContract = await this._getTokenContractAsync(normalizedTokenAddress); - - const txData = {}; - let balance = await tokenContract.balanceOf.callAsync(normalizedOwnerAddress, txData, methodOpts.defaultBlock); - // Wrap BigNumbers returned from web3 with our own (later) version of BigNumber - balance = new BigNumber(balance); - return balance; - } - /** - * Find the owner of an NFT - * NFTs assigned to zero address are considered invalid, and queries about them do throw. - * @param tokenAddress The hex encoded contract Ethereum address where the ERC721 token is deployed. - * @param tokenId The identifier for an NFT - * @param methodOpts Optional arguments this method accepts. - * @return The address of the owner of the NFT - */ - public async getOwnerOfAsync( - tokenAddress: string, - tokenId: BigNumber, - methodOpts: MethodOpts = {}, - ): Promise { - assert.isETHAddressHex('tokenAddress', tokenAddress); - assert.isBigNumber('tokenId', tokenId); - assert.doesConformToSchema('methodOpts', methodOpts, methodOptsSchema); - const normalizedTokenAddress = tokenAddress.toLowerCase(); - - const tokenContract = await this._getTokenContractAsync(normalizedTokenAddress); - - const txData = {}; - try { - const tokenOwner = await tokenContract.ownerOf.callAsync(tokenId, txData, methodOpts.defaultBlock); - return tokenOwner; - } catch (err) { - throw new Error(ContractWrappersError.ERC721OwnerNotFound); - } - } - /** - * Query if an address is an authorized operator for all NFT's of `ownerAddress` - * @param tokenAddress The hex encoded contract Ethereum address where the ERC721 token is deployed. - * @param ownerAddress The hex encoded user Ethereum address of the token owner. - * @param operatorAddress The hex encoded user Ethereum address of the operator you'd like to check if approved. - * @param methodOpts Optional arguments this method accepts. - * @return True if `operatorAddress` is an approved operator for `ownerAddress`, false otherwise - */ - public async isApprovedForAllAsync( - tokenAddress: string, - ownerAddress: string, - operatorAddress: string, - methodOpts: MethodOpts = {}, - ): Promise { - assert.isETHAddressHex('tokenAddress', tokenAddress); - assert.isETHAddressHex('ownerAddress', ownerAddress); - assert.isETHAddressHex('operatorAddress', operatorAddress); - assert.doesConformToSchema('methodOpts', methodOpts, methodOptsSchema); - const normalizedTokenAddress = tokenAddress.toLowerCase(); - const normalizedOwnerAddress = ownerAddress.toLowerCase(); - const normalizedOperatorAddress = operatorAddress.toLowerCase(); - - const tokenContract = await this._getTokenContractAsync(normalizedTokenAddress); - - const txData = {}; - const isApprovedForAll = await tokenContract.isApprovedForAll.callAsync( - normalizedOwnerAddress, - normalizedOperatorAddress, - txData, - methodOpts.defaultBlock, - ); - return isApprovedForAll; - } - /** - * Query if 0x proxy is an authorized operator for all NFT's of `ownerAddress` - * @param tokenAddress The hex encoded contract Ethereum address where the ERC721 token is deployed. - * @param ownerAddress The hex encoded user Ethereum address of the token owner. - * @param methodOpts Optional arguments this method accepts. - * @return True if `operatorAddress` is an approved operator for `ownerAddress`, false otherwise - */ - public async isProxyApprovedForAllAsync( - tokenAddress: string, - ownerAddress: string, - methodOpts: MethodOpts = {}, - ): Promise { - const proxyAddress = this._erc721ProxyWrapper.address; - const isProxyApprovedForAll = await this.isApprovedForAllAsync( - tokenAddress, - ownerAddress, - proxyAddress, - methodOpts, - ); - return isProxyApprovedForAll; - } - /** - * Get the approved address for a single NFT. Returns undefined if no approval was set - * Throws if `_tokenId` is not a valid NFT - * @param tokenAddress The hex encoded contract Ethereum address where the ERC721 token is deployed. - * @param tokenId The identifier for an NFT - * @param methodOpts Optional arguments this method accepts. - * @return The approved address for this NFT, or the undefined if there is none - */ - public async getApprovedIfExistsAsync( - tokenAddress: string, - tokenId: BigNumber, - methodOpts: MethodOpts = {}, - ): Promise { - assert.isETHAddressHex('tokenAddress', tokenAddress); - assert.isBigNumber('tokenId', tokenId); - assert.doesConformToSchema('methodOpts', methodOpts, methodOptsSchema); - const normalizedTokenAddress = tokenAddress.toLowerCase(); - - const tokenContract = await this._getTokenContractAsync(normalizedTokenAddress); - - const txData = {}; - const approvedAddress = await tokenContract.getApproved.callAsync(tokenId, txData, methodOpts.defaultBlock); - if (approvedAddress === constants.NULL_ADDRESS) { - return undefined; - } - return approvedAddress; - } - /** - * Checks if 0x proxy is approved for a single NFT - * Throws if `_tokenId` is not a valid NFT - * @param tokenAddress The hex encoded contract Ethereum address where the ERC721 token is deployed. - * @param tokenId The identifier for an NFT - * @param methodOpts Optional arguments this method accepts. - * @return True if 0x proxy is approved - */ - public async isProxyApprovedAsync( - tokenAddress: string, - tokenId: BigNumber, - methodOpts: MethodOpts = {}, - ): Promise { - const proxyAddress = this._erc721ProxyWrapper.address; - const approvedAddress = await this.getApprovedIfExistsAsync(tokenAddress, tokenId, methodOpts); - const isProxyApproved = approvedAddress === proxyAddress; - return isProxyApproved; - } - /** - * Enable or disable approval for a third party ("operator") to manage all of `ownerAddress`'s assets. - * Throws if `_tokenId` is not a valid NFT - * Emits the ApprovalForAll event. - * @param tokenAddress The hex encoded contract Ethereum address where the ERC721 token is deployed. - * @param ownerAddress The hex encoded user Ethereum address of the token owner. - * @param operatorAddress The hex encoded user Ethereum address of the operator you'd like to set approval for. - * @param isApproved The boolean variable to set the approval to. - * @param txOpts Transaction parameters. - * @return Transaction hash. - */ - public async setApprovalForAllAsync( - tokenAddress: string, - ownerAddress: string, - operatorAddress: string, - isApproved: boolean, - txOpts: TransactionOpts = {}, - ): Promise { - assert.isETHAddressHex('tokenAddress', tokenAddress); - await assert.isSenderAddressAsync('ownerAddress', ownerAddress, this._web3Wrapper); - assert.isETHAddressHex('operatorAddress', operatorAddress); - assert.isBoolean('isApproved', isApproved); - assert.doesConformToSchema('txOpts', txOpts, txOptsSchema); - const normalizedTokenAddress = tokenAddress.toLowerCase(); - const normalizedOwnerAddress = ownerAddress.toLowerCase(); - const normalizedOperatorAddress = operatorAddress.toLowerCase(); - - const tokenContract = await this._getTokenContractAsync(normalizedTokenAddress); - const txHash = await tokenContract.setApprovalForAll.sendTransactionAsync( - normalizedOperatorAddress, - isApproved, - utils.removeUndefinedProperties({ - gas: txOpts.gasLimit, - gasPrice: txOpts.gasPrice, - from: normalizedOwnerAddress, - nonce: txOpts.nonce, - }), - ); - return txHash; - } - /** - * Enable or disable approval for a third party ("operator") to manage all of `ownerAddress`'s assets. - * Throws if `_tokenId` is not a valid NFT - * Emits the ApprovalForAll event. - * @param tokenAddress The hex encoded contract Ethereum address where the ERC721 token is deployed. - * @param ownerAddress The hex encoded user Ethereum address of the token owner. - * @param operatorAddress The hex encoded user Ethereum address of the operator you'd like to set approval for. - * @param isApproved The boolean variable to set the approval to. - * @param txOpts Transaction parameters. - * @return Transaction hash. - */ - public async setProxyApprovalForAllAsync( - tokenAddress: string, - ownerAddress: string, - isApproved: boolean, - txOpts: TransactionOpts = {}, - ): Promise { - const proxyAddress = this._erc721ProxyWrapper.address; - const txHash = await this.setApprovalForAllAsync(tokenAddress, ownerAddress, proxyAddress, isApproved, txOpts); - return txHash; - } - /** - * Set or reaffirm the approved address for an NFT - * 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. - * Throws if `_tokenId` is not a valid NFT - * Emits the Approval event. - * @param tokenAddress The hex encoded contract Ethereum address where the ERC721 token is deployed. - * @param approvedAddress The hex encoded user Ethereum address you'd like to set approval for. - * @param tokenId The identifier for an NFT - * @param txOpts Transaction parameters. - * @return Transaction hash. - */ - public async setApprovalAsync( - tokenAddress: string, - approvedAddress: string, - tokenId: BigNumber, - txOpts: TransactionOpts = {}, - ): Promise { - assert.isETHAddressHex('tokenAddress', tokenAddress); - assert.isETHAddressHex('approvedAddress', approvedAddress); - assert.isBigNumber('tokenId', tokenId); - assert.doesConformToSchema('txOpts', txOpts, txOptsSchema); - const normalizedTokenAddress = tokenAddress.toLowerCase(); - const normalizedApprovedAddress = approvedAddress.toLowerCase(); - - const tokenContract = await this._getTokenContractAsync(normalizedTokenAddress); - const tokenOwnerAddress = await tokenContract.ownerOf.callAsync(tokenId); - await assert.isSenderAddressAsync('tokenOwnerAddress', tokenOwnerAddress, this._web3Wrapper); - const txHash = await tokenContract.approve.sendTransactionAsync( - normalizedApprovedAddress, - tokenId, - utils.removeUndefinedProperties({ - gas: txOpts.gasLimit, - gasPrice: txOpts.gasPrice, - from: tokenOwnerAddress, - nonce: txOpts.nonce, - }), - ); - return txHash; - } - /** - * Set or reaffirm 0x proxy as an approved address for an NFT - * Throws unless `msg.sender` is the current NFT owner, or an authorized operator of the current owner. - * Throws if `_tokenId` is not a valid NFT - * Emits the Approval event. - * @param tokenAddress The hex encoded contract Ethereum address where the ERC721 token is deployed. - * @param tokenId The identifier for an NFT - * @param txOpts Transaction parameters. - * @return Transaction hash. - */ - public async setProxyApprovalAsync( - tokenAddress: string, - tokenId: BigNumber, - txOpts: TransactionOpts = {}, - ): Promise { - const proxyAddress = this._erc721ProxyWrapper.address; - const txHash = await this.setApprovalAsync(tokenAddress, proxyAddress, tokenId, txOpts); - return txHash; - } - /** - * Enable or disable approval for a third party ("operator") to manage all of `ownerAddress`'s assets. - * Throws if `_tokenId` is not a valid NFT - * Emits the ApprovalForAll event. - * @param tokenAddress The hex encoded contract Ethereum address where the ERC721 token is deployed. - * @param receiverAddress The hex encoded Ethereum address of the user to send the NFT to. - * @param senderAddress The hex encoded Ethereum address of the user to send the NFT to. - * @param tokenId The identifier for an NFT - * @param txOpts Transaction parameters. - * @return Transaction hash. - */ - public async transferFromAsync( - tokenAddress: string, - receiverAddress: string, - senderAddress: string, - tokenId: BigNumber, - txOpts: TransactionOpts = {}, - ): Promise { - assert.isETHAddressHex('tokenAddress', tokenAddress); - assert.isETHAddressHex('receiverAddress', receiverAddress); - await assert.isSenderAddressAsync('senderAddress', senderAddress, this._web3Wrapper); - assert.doesConformToSchema('txOpts', txOpts, txOptsSchema); - const normalizedTokenAddress = tokenAddress.toLowerCase(); - const normalizedReceiverAddress = receiverAddress.toLowerCase(); - const normalizedSenderAddress = senderAddress.toLowerCase(); - const tokenContract = await this._getTokenContractAsync(normalizedTokenAddress); - const ownerAddress = await this.getOwnerOfAsync(tokenAddress, tokenId); - if (normalizedSenderAddress !== ownerAddress) { - const isApprovedForAll = await this.isApprovedForAllAsync( - normalizedTokenAddress, - ownerAddress, - normalizedSenderAddress, - ); - if (!isApprovedForAll) { - const approvedAddress = await this.getApprovedIfExistsAsync(normalizedTokenAddress, tokenId); - if (approvedAddress !== normalizedSenderAddress) { - throw new Error(ContractWrappersError.ERC721NoApproval); - } - } - } - const txHash = await tokenContract.transferFrom.sendTransactionAsync( - ownerAddress, - normalizedReceiverAddress, - tokenId, - utils.removeUndefinedProperties({ - gas: txOpts.gasLimit, - gasPrice: txOpts.gasPrice, - from: normalizedSenderAddress, - nonce: txOpts.nonce, - }), - ); - return txHash; - } - /** - * Subscribe to an event type emitted by the Token contract. - * @param tokenAddress The hex encoded address where the ERC721 token is deployed. - * @param eventName The token 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( - tokenAddress: string, - eventName: ERC721TokenEvents, - indexFilterValues: IndexedFilterValues, - callback: EventCallback, - isVerbose: boolean = false, - ): string { - assert.isETHAddressHex('tokenAddress', tokenAddress); - assert.doesBelongToStringEnum('eventName', eventName, ERC721TokenEvents); - assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); - assert.isFunction('callback', callback); - const normalizedTokenAddress = tokenAddress.toLowerCase(); - const subscriptionToken = this._subscriptionManager.subscribe( - normalizedTokenAddress, - eventName, - indexFilterValues, - ERC721Token.compilerOutput.abi, - callback, - isVerbose, - this._blockPollingIntervalMs, - ); - return subscriptionToken; - } - /** - * Cancel a subscription - * @param subscriptionToken Subscription token returned by `subscribe()` - */ - public unsubscribe(subscriptionToken: string): void { - assert.isValidSubscriptionToken('subscriptionToken', subscriptionToken); - this._subscriptionManager.unsubscribe(subscriptionToken); - } - /** - * Cancels all existing subscriptions - */ - public unsubscribeAll(): void { - this._subscriptionManager.unsubscribeAll(); - } - /** - * Gets historical logs without creating a subscription - * @param tokenAddress An address of the token that emitted the logs. - * @param eventName The token 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( - tokenAddress: string, - eventName: ERC721TokenEvents, - blockRange: BlockRange, - indexFilterValues: IndexedFilterValues, - ): Promise>> { - assert.isETHAddressHex('tokenAddress', tokenAddress); - assert.doesBelongToStringEnum('eventName', eventName, ERC721TokenEvents); - assert.doesConformToSchema('blockRange', blockRange, schemas.blockRangeSchema); - assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); - const normalizedTokenAddress = tokenAddress.toLowerCase(); - const logs = await this._subscriptionManager.getLogsAsync( - normalizedTokenAddress, - eventName, - blockRange, - indexFilterValues, - ERC721Token.compilerOutput.abi, - ); - return logs; - } - private async _getTokenContractAsync(tokenAddress: string): Promise { - const normalizedTokenAddress = tokenAddress.toLowerCase(); - let tokenContract = this._tokenContractsByAddress[normalizedTokenAddress]; - if (tokenContract !== undefined) { - return tokenContract; - } - const contractInstance = new ERC721TokenContract( - normalizedTokenAddress, - this._web3Wrapper.getProvider(), - this._web3Wrapper.getContractDefaults(), - ); - tokenContract = contractInstance; - this._tokenContractsByAddress[normalizedTokenAddress] = tokenContract; - return tokenContract; - } -} diff --git a/packages/contract-wrappers/src/contract_wrappers/ether_token_wrapper.ts b/packages/contract-wrappers/src/contract_wrappers/ether_token_wrapper.ts deleted file mode 100644 index 599c73dcc0..0000000000 --- a/packages/contract-wrappers/src/contract_wrappers/ether_token_wrapper.ts +++ /dev/null @@ -1,212 +0,0 @@ -import { WETH9Contract, WETH9EventArgs, WETH9Events } from '@0x/abi-gen-wrappers'; -import { SubscriptionManager } from '@0x/base-contract'; -import { WETH9 } from '@0x/contract-artifacts'; -import { schemas } from '@0x/json-schemas'; -import { BigNumber } from '@0x/utils'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import { ContractAbi, LogWithDecodedArgs } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { BlockRange, ContractWrappersError, EventCallback, IndexedFilterValues, TransactionOpts } from '../types'; -import { assert } from '../utils/assert'; -import { utils } from '../utils/utils'; - -import { ERC20TokenWrapper } from './erc20_token_wrapper'; - -/** - * This class includes all the functionality related to interacting with a wrapped Ether ERC20 token contract. - * The caller can convert ETH into the equivalent number of wrapped ETH ERC20 tokens and back. - */ -export class EtherTokenWrapper { - public abi: ContractAbi = WETH9.compilerOutput.abi; - private readonly _web3Wrapper: Web3Wrapper; - private readonly _subscriptionManager: SubscriptionManager; - private readonly _blockPollingIntervalMs?: number; - private readonly _etherTokenContractsByAddress: { - [address: string]: WETH9Contract; - } = {}; - private readonly _erc20TokenWrapper: ERC20TokenWrapper; - /** - * Instantiate EtherTokenWrapper. - * @param web3Wrapper Web3Wrapper instance to use - * @param erc20TokenWrapper The ERC20TokenWrapper instance to use - */ - constructor(web3Wrapper: Web3Wrapper, erc20TokenWrapper: ERC20TokenWrapper, blockPollingIntervalMs?: number) { - this._web3Wrapper = web3Wrapper; - this._erc20TokenWrapper = erc20TokenWrapper; - this._blockPollingIntervalMs = blockPollingIntervalMs; - this._subscriptionManager = new SubscriptionManager( - WETH9Contract.ABI(), - web3Wrapper, - ); - } - /** - * Deposit ETH into the Wrapped ETH smart contract and issues the equivalent number of wrapped ETH tokens - * to the depositor address. These wrapped ETH tokens can be used in 0x trades and are redeemable for 1-to-1 - * for ETH. - * @param etherTokenAddress EtherToken address you wish to deposit into. - * @param amountInWei Amount of ETH in Wei the caller wishes to deposit. - * @param depositor The hex encoded user Ethereum address that would like to make the deposit. - * @param txOpts Transaction parameters. - * @return Transaction hash. - */ - public async depositAsync( - etherTokenAddress: string, - amountInWei: BigNumber, - depositor: string, - txOpts: TransactionOpts = {}, - ): Promise { - assert.isETHAddressHex('etherTokenAddress', etherTokenAddress); - assert.isValidBaseUnitAmount('amountInWei', amountInWei); - await assert.isSenderAddressAsync('depositor', depositor, this._web3Wrapper); - const normalizedEtherTokenAddress = etherTokenAddress.toLowerCase(); - const normalizedDepositorAddress = depositor.toLowerCase(); - - const ethBalanceInWei = await this._web3Wrapper.getBalanceInWeiAsync(normalizedDepositorAddress); - assert.assert(ethBalanceInWei.gte(amountInWei), ContractWrappersError.InsufficientEthBalanceForDeposit); - - const wethContract = await this._getEtherTokenContractAsync(normalizedEtherTokenAddress); - const txHash = await wethContract.deposit.sendTransactionAsync( - utils.removeUndefinedProperties({ - from: normalizedDepositorAddress, - value: amountInWei, - gas: txOpts.gasLimit, - gasPrice: txOpts.gasPrice, - nonce: txOpts.nonce, - }), - ); - return txHash; - } - /** - * Withdraw ETH to the withdrawer's address from the wrapped ETH smart contract in exchange for the - * equivalent number of wrapped ETH tokens. - * @param etherTokenAddress EtherToken address you wish to withdraw from. - * @param amountInWei Amount of ETH in Wei the caller wishes to withdraw. - * @param withdrawer The hex encoded user Ethereum address that would like to make the withdrawal. - * @param txOpts Transaction parameters. - * @return Transaction hash. - */ - public async withdrawAsync( - etherTokenAddress: string, - amountInWei: BigNumber, - withdrawer: string, - txOpts: TransactionOpts = {}, - ): Promise { - assert.isValidBaseUnitAmount('amountInWei', amountInWei); - assert.isETHAddressHex('etherTokenAddress', etherTokenAddress); - await assert.isSenderAddressAsync('withdrawer', withdrawer, this._web3Wrapper); - const normalizedEtherTokenAddress = etherTokenAddress.toLowerCase(); - const normalizedWithdrawerAddress = withdrawer.toLowerCase(); - - const WETHBalanceInBaseUnits = await this._erc20TokenWrapper.getBalanceAsync( - normalizedEtherTokenAddress, - normalizedWithdrawerAddress, - ); - assert.assert( - WETHBalanceInBaseUnits.gte(amountInWei), - ContractWrappersError.InsufficientWEthBalanceForWithdrawal, - ); - - const wethContract = await this._getEtherTokenContractAsync(normalizedEtherTokenAddress); - const txHash = await wethContract.withdraw.sendTransactionAsync( - amountInWei, - utils.removeUndefinedProperties({ - from: normalizedWithdrawerAddress, - gas: txOpts.gasLimit, - gasPrice: txOpts.gasPrice, - nonce: txOpts.nonce, - }), - ); - return txHash; - } - /** - * Gets historical logs without creating a subscription - * @param etherTokenAddress An address of the ether token that emitted the logs. - * @param eventName The ether token 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 `{_owner: aUserAddressHex}` - * @return Array of logs that match the parameters - */ - public async getLogsAsync( - etherTokenAddress: string, - eventName: WETH9Events, - blockRange: BlockRange, - indexFilterValues: IndexedFilterValues, - ): Promise>> { - assert.isETHAddressHex('etherTokenAddress', etherTokenAddress); - const normalizedEtherTokenAddress = etherTokenAddress.toLowerCase(); - assert.doesBelongToStringEnum('eventName', eventName, WETH9Events); - assert.doesConformToSchema('blockRange', blockRange, schemas.blockRangeSchema); - assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); - const logs = await this._subscriptionManager.getLogsAsync( - normalizedEtherTokenAddress, - eventName, - blockRange, - indexFilterValues, - WETH9.compilerOutput.abi, - ); - return logs; - } - /** - * Subscribe to an event type emitted by the Token contract. - * @param etherTokenAddress The hex encoded address where the ether token is deployed. - * @param eventName The ether token 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 `{_owner: 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( - etherTokenAddress: string, - eventName: WETH9Events, - indexFilterValues: IndexedFilterValues, - callback: EventCallback, - isVerbose: boolean = false, - ): string { - assert.isETHAddressHex('etherTokenAddress', etherTokenAddress); - const normalizedEtherTokenAddress = etherTokenAddress.toLowerCase(); - assert.doesBelongToStringEnum('eventName', eventName, WETH9Events); - assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); - assert.isFunction('callback', callback); - const subscriptionToken = this._subscriptionManager.subscribe( - normalizedEtherTokenAddress, - eventName, - indexFilterValues, - WETH9.compilerOutput.abi, - callback, - isVerbose, - this._blockPollingIntervalMs, - ); - return subscriptionToken; - } - /** - * Cancel a subscription - * @param subscriptionToken Subscription token returned by `subscribe()` - */ - public unsubscribe(subscriptionToken: string): void { - assert.isValidSubscriptionToken('subscriptionToken', subscriptionToken); - this._subscriptionManager.unsubscribe(subscriptionToken); - } - /** - * Cancels all existing subscriptions - */ - public unsubscribeAll(): void { - this._subscriptionManager.unsubscribeAll(); - } - private async _getEtherTokenContractAsync(etherTokenAddress: string): Promise { - let etherTokenContract = this._etherTokenContractsByAddress[etherTokenAddress]; - if (etherTokenContract !== undefined) { - return etherTokenContract; - } - const contractInstance = new WETH9Contract( - etherTokenAddress, - this._web3Wrapper.getProvider(), - this._web3Wrapper.getContractDefaults(), - ); - etherTokenContract = contractInstance; - this._etherTokenContractsByAddress[etherTokenAddress] = etherTokenContract; - return etherTokenContract; - } -} diff --git a/packages/contract-wrappers/src/contract_wrappers/exchange_wrapper.ts b/packages/contract-wrappers/src/contract_wrappers/exchange_wrapper.ts deleted file mode 100644 index bb948ee8a2..0000000000 --- a/packages/contract-wrappers/src/contract_wrappers/exchange_wrapper.ts +++ /dev/null @@ -1,1272 +0,0 @@ -import { ExchangeContract, ExchangeEventArgs, ExchangeEvents } from '@0x/abi-gen-wrappers'; -import { Exchange } from '@0x/contract-artifacts'; -import { schemas } from '@0x/json-schemas'; -import { - assetDataUtils, - BalanceAndProxyAllowanceLazyStore, - ExchangeTransferSimulator, - orderCalculationUtils, - orderHashUtils, - OrderStateUtils, - OrderValidationUtils, -} from '@0x/order-utils'; -import { AssetProxyId, Order, SignedOrder } from '@0x/types'; -import { BigNumber } from '@0x/utils'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import { BlockParamLiteral, ContractAbi, LogWithDecodedArgs } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { AssetBalanceAndProxyAllowanceFetcher } from '../fetchers/asset_balance_and_proxy_allowance_fetcher'; -import { OrderFilledCancelledFetcher } from '../fetchers/order_filled_cancelled_fetcher'; -import { methodOptsSchema } from '../schemas/method_opts_schema'; -import { orderTxOptsSchema } from '../schemas/order_tx_opts_schema'; -import { txOptsSchema } from '../schemas/tx_opts_schema'; -import { validateOrderFillableOptsSchema } from '../schemas/validate_order_fillable_opts_schema'; -import { - BlockRange, - EventCallback, - ExchangeWrapperError, - IndexedFilterValues, - MethodOpts, - OrderInfo, - OrderTransactionOpts, - ValidateOrderFillableOpts, -} from '../types'; -import { assert } from '../utils/assert'; -import { _getDefaultContractAddresses } from '../utils/contract_addresses'; -import { decorators } from '../utils/decorators'; -import { TransactionEncoder } from '../utils/transaction_encoder'; - -import { ERC20TokenWrapper } from './erc20_token_wrapper'; -import { ERC721TokenWrapper } from './erc721_token_wrapper'; - -/** - * This class includes all the functionality related to calling methods, sending transactions and subscribing to - * events of the 0x V2 Exchange smart contract. - */ -export class ExchangeWrapper { - public abi: ContractAbi = Exchange.compilerOutput.abi; - public address: string; - public zrxTokenAddress: string; - private readonly _web3Wrapper: Web3Wrapper; - private readonly _exchangeContract: ExchangeContract; - private readonly _blockPollingIntervalMs?: number; - private readonly _erc721TokenWrapper: ERC721TokenWrapper; - private readonly _erc20TokenWrapper: ERC20TokenWrapper; - /** - * Instantiate ExchangeWrapper - * @param web3Wrapper Web3Wrapper instance to use. - * @param networkId Desired networkId. - * @param erc20TokenWrapper ERC20TokenWrapper instance to use. - * @param erc721TokenWrapper ERC721TokenWrapper instance to use. - * @param address The address of the Exchange contract. If undefined, will - * default to the known address corresponding to the networkId. - * @param zrxTokenAddress The address of the ZRXToken contract. If - * undefined, will default to the known address corresponding to the - * networkId. - * @param blockPollingIntervalMs The block polling interval to use for active subscriptions. - */ - constructor( - web3Wrapper: Web3Wrapper, - networkId: number, - erc20TokenWrapper: ERC20TokenWrapper, - erc721TokenWrapper: ERC721TokenWrapper, - address?: string, - zrxTokenAddress?: string, - blockPollingIntervalMs?: number, - ) { - this._web3Wrapper = web3Wrapper; - this._erc20TokenWrapper = erc20TokenWrapper; - this._erc721TokenWrapper = erc721TokenWrapper; - this._blockPollingIntervalMs = blockPollingIntervalMs; - this.address = address === undefined ? _getDefaultContractAddresses(networkId).exchange : address; - this.zrxTokenAddress = - zrxTokenAddress === undefined ? _getDefaultContractAddresses(networkId).zrxToken : zrxTokenAddress; - this._exchangeContract = new ExchangeContract( - this.address, - this._web3Wrapper.getProvider(), - this._web3Wrapper.getContractDefaults(), - ); - } - /** - * Retrieve the address of an asset proxy by signature. - * @param proxyId The 4 bytes signature of an asset proxy - * @param methodOpts Optional arguments this method accepts. - * @return The address of an asset proxy for a given signature - */ - public async getAssetProxyBySignatureAsync(proxyId: AssetProxyId, methodOpts: MethodOpts = {}): Promise { - assert.doesBelongToStringEnum('proxyId', proxyId, AssetProxyId); - assert.doesConformToSchema('methodOpts', methodOpts, methodOptsSchema); - - const callData = {}; - const assetProxy = await this._exchangeContract.getAssetProxy.callAsync( - proxyId, - callData, - methodOpts.defaultBlock, - ); - return assetProxy; - } - /** - * Retrieve the takerAssetAmount of an order that has already been filled. - * @param orderHash The hex encoded orderHash for which you would like to retrieve the filled takerAssetAmount. - * @param methodOpts Optional arguments this method accepts. - * @return The amount of the order (in taker asset base units) that has already been filled. - */ - public async getFilledTakerAssetAmountAsync(orderHash: string, methodOpts: MethodOpts = {}): Promise { - assert.doesConformToSchema('orderHash', orderHash, schemas.orderHashSchema); - assert.doesConformToSchema('methodOpts', methodOpts, methodOptsSchema); - - const callData = {}; - const filledTakerAssetAmountInBaseUnits = await this._exchangeContract.filled.callAsync( - orderHash, - callData, - methodOpts.defaultBlock, - ); - return filledTakerAssetAmountInBaseUnits; - } - /** - * Retrieve the exchange contract version - * @param methodOpts Optional arguments this method accepts. - * @return Version - */ - public async getVersionAsync(methodOpts: MethodOpts = {}): Promise { - assert.doesConformToSchema('methodOpts', methodOpts, methodOptsSchema); - const callData = {}; - const version = await this._exchangeContract.VERSION.callAsync(callData, methodOpts.defaultBlock); - return version; - } - /** - * Retrieve the set order epoch for a given makerAddress & senderAddress pair. - * Orders can be bulk cancelled by setting the order epoch to a value lower then the salt value of orders one wishes to cancel. - * @param makerAddress Maker address - * @param senderAddress Sender address - * @param methodOpts Optional arguments this method accepts. - * @return Order epoch. Defaults to 0. - */ - public async getOrderEpochAsync( - makerAddress: string, - senderAddress: string, - methodOpts: MethodOpts = {}, - ): Promise { - assert.isETHAddressHex('makerAddress', makerAddress); - assert.isETHAddressHex('senderAddress', senderAddress); - assert.doesConformToSchema('methodOpts', methodOpts, methodOptsSchema); - const callData = {}; - const orderEpoch = await this._exchangeContract.orderEpoch.callAsync( - makerAddress, - senderAddress, - callData, - methodOpts.defaultBlock, - ); - return orderEpoch; - } - /** - * Check if an order has been cancelled. Order cancellations are binary - * @param orderHash The hex encoded orderHash for which you would like to retrieve the cancelled takerAmount. - * @param methodOpts Optional arguments this method accepts. - * @return Whether the order has been cancelled. - */ - public async isCancelledAsync(orderHash: string, methodOpts: MethodOpts = {}): Promise { - assert.doesConformToSchema('orderHash', orderHash, schemas.orderHashSchema); - assert.doesConformToSchema('methodOpts', methodOpts, methodOptsSchema); - const callData = {}; - const isCancelled = await this._exchangeContract.cancelled.callAsync( - orderHash, - callData, - methodOpts.defaultBlock, - ); - return isCancelled; - } - /** - * Fills a signed order with an amount denominated in baseUnits of the taker asset. - * @param signedOrder An object that conforms to the SignedOrder interface. - * @param takerAssetFillAmount The amount of the order (in taker asset baseUnits) that you wish to fill. - * @param takerAddress The user Ethereum address who would like to fill this order. Must be available via the supplied - * Provider provided at instantiation. - * @param orderTransactionOpts Optional arguments this method accepts. - * @return Transaction hash. - */ - @decorators.asyncZeroExErrorHandler - public async fillOrderAsync( - signedOrder: SignedOrder, - takerAssetFillAmount: BigNumber, - takerAddress: string, - orderTransactionOpts: OrderTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.doesConformToSchema('signedOrder', signedOrder, schemas.signedOrderSchema); - assert.isValidBaseUnitAmount('takerAssetFillAmount', takerAssetFillAmount); - await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); - assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); - const normalizedTakerAddress = takerAddress.toLowerCase(); - - if (orderTransactionOpts.shouldValidate) { - await this._exchangeContract.fillOrder.callAsync(signedOrder, takerAssetFillAmount, signedOrder.signature, { - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }); - } - - const txHash = await this._exchangeContract.fillOrder.sendTransactionAsync( - signedOrder, - takerAssetFillAmount, - signedOrder.signature, - { - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }, - ); - return txHash; - } - /** - * No-throw version of fillOrderAsync. This version will not throw if the fill fails. This allows the caller to save gas at the expense of not knowing the reason the fill failed. - * @param signedOrder An object that conforms to the SignedOrder interface. - * @param takerAssetFillAmount The amount of the order (in taker asset baseUnits) that you wish to fill. - * @param takerAddress The user Ethereum address who would like to fill this order. - * Must be available via the supplied Provider provided at instantiation. - * @param orderTransactionOpts Optional arguments this method accepts. - * @return Transaction hash. - */ - @decorators.asyncZeroExErrorHandler - public async fillOrderNoThrowAsync( - signedOrder: SignedOrder, - takerAssetFillAmount: BigNumber, - takerAddress: string, - orderTransactionOpts: OrderTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.doesConformToSchema('signedOrder', signedOrder, schemas.signedOrderSchema); - assert.isValidBaseUnitAmount('takerAssetFillAmount', takerAssetFillAmount); - await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); - assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); - const normalizedTakerAddress = takerAddress.toLowerCase(); - - if (orderTransactionOpts.shouldValidate) { - await this._exchangeContract.fillOrderNoThrow.callAsync( - signedOrder, - takerAssetFillAmount, - signedOrder.signature, - { - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }, - ); - } - const txHash = await this._exchangeContract.fillOrderNoThrow.sendTransactionAsync( - signedOrder, - takerAssetFillAmount, - signedOrder.signature, - { - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }, - ); - return txHash; - } - /** - * Attempts to fill a specific amount of an order. If the entire amount specified cannot be filled, - * the fill order is abandoned. - * @param signedOrder An object that conforms to the SignedOrder interface. - * @param takerAssetFillAmount The amount of the order (in taker asset baseUnits) that you wish to fill. - * @param takerAddress The user Ethereum address who would like to fill this order. Must be available via the supplied - * Provider provided at instantiation. - * @param orderTransactionOpts Optional arguments this method accepts. - * @return Transaction hash. - */ - @decorators.asyncZeroExErrorHandler - public async fillOrKillOrderAsync( - signedOrder: SignedOrder, - takerAssetFillAmount: BigNumber, - takerAddress: string, - orderTransactionOpts: OrderTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.doesConformToSchema('signedOrder', signedOrder, schemas.signedOrderSchema); - assert.isValidBaseUnitAmount('takerAssetFillAmount', takerAssetFillAmount); - await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); - assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); - const normalizedTakerAddress = takerAddress.toLowerCase(); - - if (orderTransactionOpts.shouldValidate) { - await this._exchangeContract.fillOrKillOrder.callAsync( - signedOrder, - takerAssetFillAmount, - signedOrder.signature, - { - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }, - ); - } - const txHash = await this._exchangeContract.fillOrKillOrder.sendTransactionAsync( - signedOrder, - takerAssetFillAmount, - signedOrder.signature, - { - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }, - ); - return txHash; - } - /** - * Executes a 0x transaction. Transaction messages exist for the purpose of calling methods on the Exchange contract - * in the context of another address (see [ZEIP18](https://github.com/0xProject/ZEIPs/issues/18)). - * This is especially useful for implementing filter contracts. - * @param salt Salt - * @param signerAddress Signer address - * @param data Transaction data - * @param signature Signature - * @param senderAddress Sender address - * @param orderTransactionOpts Optional arguments this method accepts. - * @return Transaction hash. - */ - @decorators.asyncZeroExErrorHandler - public async executeTransactionAsync( - salt: BigNumber, - signerAddress: string, - data: string, - signature: string, - senderAddress: string, - orderTransactionOpts: OrderTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isBigNumber('salt', salt); - assert.isETHAddressHex('signerAddress', signerAddress); - assert.isHexString('data', data); - assert.isHexString('signature', signature); - await assert.isSenderAddressAsync('senderAddress', senderAddress, this._web3Wrapper); - assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); - const normalizedSenderAddress = senderAddress.toLowerCase(); - - if (orderTransactionOpts.shouldValidate) { - await this._exchangeContract.executeTransaction.callAsync(salt, signerAddress, data, signature, { - from: normalizedSenderAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }); - } - const txHash = await this._exchangeContract.executeTransaction.sendTransactionAsync( - salt, - signerAddress, - data, - signature, - { - from: normalizedSenderAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }, - ); - return txHash; - } - /** - * Batch version of fillOrderAsync. Executes multiple fills atomically in a single transaction. - * @param signedOrders An array of signed orders to fill. - * @param takerAssetFillAmounts The amounts of the orders (in taker asset baseUnits) that you wish to fill. - * @param takerAddress The user Ethereum address who would like to fill these orders. Must be available via the supplied - * Provider provided at instantiation. - * @param orderTransactionOpts Optional arguments this method accepts. - * @return Transaction hash. - */ - @decorators.asyncZeroExErrorHandler - public async batchFillOrdersAsync( - signedOrders: SignedOrder[], - takerAssetFillAmounts: BigNumber[], - takerAddress: string, - orderTransactionOpts: OrderTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.doesConformToSchema('signedOrders', signedOrders, schemas.signedOrdersSchema); - _.forEach(takerAssetFillAmounts, takerAssetFillAmount => - assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount), - ); - await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); - assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); - const normalizedTakerAddress = takerAddress.toLowerCase(); - - const signatures = _.map(signedOrders, signedOrder => signedOrder.signature); - if (orderTransactionOpts.shouldValidate) { - await this._exchangeContract.batchFillOrders.callAsync(signedOrders, takerAssetFillAmounts, signatures, { - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }); - } - const txHash = await this._exchangeContract.batchFillOrders.sendTransactionAsync( - signedOrders, - takerAssetFillAmounts, - signatures, - { - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }, - ); - return txHash; - } - /** - * Synchronously executes multiple calls to fillOrder until total amount of makerAsset is bought by taker. - * @param signedOrders An array of signed orders to fill. - * @param makerAssetFillAmount Maker asset fill amount. - * @param takerAddress The user Ethereum address who would like to fill these orders. Must be available via the supplied - * Provider provided at instantiation. - * @param orderTransactionOpts Optional arguments this method accepts. - * @return Transaction hash. - */ - @decorators.asyncZeroExErrorHandler - public async marketBuyOrdersAsync( - signedOrders: SignedOrder[], - makerAssetFillAmount: BigNumber, - takerAddress: string, - orderTransactionOpts: OrderTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.doesConformToSchema('signedOrders', signedOrders, schemas.signedOrdersSchema); - assert.isBigNumber('makerAssetFillAmount', makerAssetFillAmount); - await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); - assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); - const normalizedTakerAddress = takerAddress.toLowerCase(); - - const signatures = _.map(signedOrders, signedOrder => signedOrder.signature); - if (orderTransactionOpts.shouldValidate) { - await this._exchangeContract.marketBuyOrders.callAsync(signedOrders, makerAssetFillAmount, signatures, { - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }); - } - const txHash = await this._exchangeContract.marketBuyOrders.sendTransactionAsync( - signedOrders, - makerAssetFillAmount, - signatures, - { - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }, - ); - return txHash; - } - /** - * Synchronously executes multiple calls to fillOrder until total amount of makerAsset is bought by taker. - * @param signedOrders An array of signed orders to fill. - * @param takerAssetFillAmount Taker asset fill amount. - * @param takerAddress The user Ethereum address who would like to fill these orders. Must be available via the supplied - * Provider provided at instantiation. - * @param orderTransactionOpts Optional arguments this method accepts. - * @return Transaction hash. - */ - @decorators.asyncZeroExErrorHandler - public async marketSellOrdersAsync( - signedOrders: SignedOrder[], - takerAssetFillAmount: BigNumber, - takerAddress: string, - orderTransactionOpts: OrderTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.doesConformToSchema('signedOrders', signedOrders, schemas.signedOrdersSchema); - assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); - await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); - assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); - const normalizedTakerAddress = takerAddress.toLowerCase(); - - const signatures = _.map(signedOrders, signedOrder => signedOrder.signature); - if (orderTransactionOpts.shouldValidate) { - await this._exchangeContract.marketSellOrders.callAsync(signedOrders, takerAssetFillAmount, signatures, { - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }); - } - const txHash = await this._exchangeContract.marketSellOrders.sendTransactionAsync( - signedOrders, - takerAssetFillAmount, - signatures, - { - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }, - ); - return txHash; - } - /** - * No throw version of marketBuyOrdersAsync - * @param signedOrders An array of signed orders to fill. - * @param makerAssetFillAmount Maker asset fill amount. - * @param takerAddress The user Ethereum address who would like to fill these orders. Must be available via the supplied - * Provider provided at instantiation. - * @param orderTransactionOpts Optional arguments this method accepts. - * @return Transaction hash. - */ - @decorators.asyncZeroExErrorHandler - public async marketBuyOrdersNoThrowAsync( - signedOrders: SignedOrder[], - makerAssetFillAmount: BigNumber, - takerAddress: string, - orderTransactionOpts: OrderTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.doesConformToSchema('signedOrders', signedOrders, schemas.signedOrdersSchema); - assert.isBigNumber('makerAssetFillAmount', makerAssetFillAmount); - await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); - assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); - const normalizedTakerAddress = takerAddress.toLowerCase(); - - const signatures = _.map(signedOrders, signedOrder => signedOrder.signature); - if (orderTransactionOpts.shouldValidate) { - await this._exchangeContract.marketBuyOrdersNoThrow.callAsync( - signedOrders, - makerAssetFillAmount, - signatures, - { - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }, - ); - } - const txHash = await this._exchangeContract.marketBuyOrdersNoThrow.sendTransactionAsync( - signedOrders, - makerAssetFillAmount, - signatures, - { - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }, - ); - return txHash; - } - /** - * No throw version of marketSellOrdersAsync - * @param signedOrders An array of signed orders to fill. - * @param takerAssetFillAmount Taker asset fill amount. - * @param takerAddress The user Ethereum address who would like to fill these orders. Must be available via the supplied - * Provider provided at instantiation. - * @param orderTransactionOpts Optional arguments this method accepts. - * @return Transaction hash. - */ - @decorators.asyncZeroExErrorHandler - public async marketSellOrdersNoThrowAsync( - signedOrders: SignedOrder[], - takerAssetFillAmount: BigNumber, - takerAddress: string, - orderTransactionOpts: OrderTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.doesConformToSchema('signedOrders', signedOrders, schemas.signedOrdersSchema); - assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); - await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); - assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); - const normalizedTakerAddress = takerAddress.toLowerCase(); - - const signatures = _.map(signedOrders, signedOrder => signedOrder.signature); - if (orderTransactionOpts.shouldValidate) { - await this._exchangeContract.marketSellOrdersNoThrow.callAsync( - signedOrders, - takerAssetFillAmount, - signatures, - { - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }, - ); - } - const txHash = await this._exchangeContract.marketSellOrdersNoThrow.sendTransactionAsync( - signedOrders, - takerAssetFillAmount, - signatures, - { - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }, - ); - return txHash; - } - /** - * No throw version of batchFillOrdersAsync - * @param signedOrders An array of signed orders to fill. - * @param takerAssetFillAmounts The amounts of the orders (in taker asset baseUnits) that you wish to fill. - * @param takerAddress The user Ethereum address who would like to fill these orders. Must be available via the supplied - * Provider provided at instantiation. - * @param orderTransactionOpts Optional arguments this method accepts. - * @return Transaction hash. - */ - @decorators.asyncZeroExErrorHandler - public async batchFillOrdersNoThrowAsync( - signedOrders: SignedOrder[], - takerAssetFillAmounts: BigNumber[], - takerAddress: string, - orderTransactionOpts: OrderTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.doesConformToSchema('signedOrders', signedOrders, schemas.signedOrdersSchema); - _.forEach(takerAssetFillAmounts, takerAssetFillAmount => - assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount), - ); - await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); - assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); - const normalizedTakerAddress = takerAddress.toLowerCase(); - - const signatures = _.map(signedOrders, signedOrder => signedOrder.signature); - if (orderTransactionOpts.shouldValidate) { - await this._exchangeContract.batchFillOrdersNoThrow.callAsync( - signedOrders, - takerAssetFillAmounts, - signatures, - { - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }, - ); - } - const txHash = await this._exchangeContract.batchFillOrdersNoThrow.sendTransactionAsync( - signedOrders, - takerAssetFillAmounts, - signatures, - { - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }, - ); - return txHash; - } - /** - * Batch version of fillOrKillOrderAsync. Executes multiple fills atomically in a single transaction. - * @param signedOrders An array of signed orders to fill. - * @param takerAssetFillAmounts The amounts of the orders (in taker asset baseUnits) that you wish to fill. - * @param takerAddress The user Ethereum address who would like to fill these orders. Must be available via the supplied - * Provider provided at instantiation. - * @param orderTransactionOpts Optional arguments this method accepts. - * @return Transaction hash. - */ - @decorators.asyncZeroExErrorHandler - public async batchFillOrKillOrdersAsync( - signedOrders: SignedOrder[], - takerAssetFillAmounts: BigNumber[], - takerAddress: string, - orderTransactionOpts: OrderTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.doesConformToSchema('signedOrders', signedOrders, schemas.signedOrdersSchema); - _.forEach(takerAssetFillAmounts, takerAssetFillAmount => - assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount), - ); - await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); - assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); - const normalizedTakerAddress = takerAddress.toLowerCase(); - - const signatures = _.map(signedOrders, signedOrder => signedOrder.signature); - if (orderTransactionOpts.shouldValidate) { - await this._exchangeContract.batchFillOrKillOrders.callAsync( - signedOrders, - takerAssetFillAmounts, - signatures, - { - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }, - ); - } - const txHash = await this._exchangeContract.batchFillOrKillOrders.sendTransactionAsync( - signedOrders, - takerAssetFillAmounts, - signatures, - { - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }, - ); - return txHash; - } - /** - * Batch version of cancelOrderAsync. Executes multiple cancels atomically in a single transaction. - * @param orders An array of orders to cancel. - * @param orderTransactionOpts Optional arguments this method accepts. - * @return Transaction hash. - */ - @decorators.asyncZeroExErrorHandler - public async batchCancelOrdersAsync( - orders: Array, - orderTransactionOpts: OrderTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.doesConformToSchema('orders', orders, schemas.ordersSchema); - assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); - const makerAddresses = _.map(orders, order => order.makerAddress); - const makerAddress = makerAddresses[0]; - await assert.isSenderAddressAsync('makerAddress', makerAddress, this._web3Wrapper); - const normalizedMakerAddress = makerAddress.toLowerCase(); - - if (orderTransactionOpts.shouldValidate) { - await this._exchangeContract.batchCancelOrders.callAsync(orders, { - from: normalizedMakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }); - } - const txHash = await this._exchangeContract.batchCancelOrders.sendTransactionAsync(orders, { - from: normalizedMakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }); - return txHash; - } - /** - * 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 (whoever matched the two orders). - * @param leftSignedOrder First order to match. - * @param rightSignedOrder Second order to match. - * @param takerAddress The address that sends the transaction and gets the spread. - * @param orderTransactionOpts Optional arguments this method accepts. - * @return Transaction hash. - */ - @decorators.asyncZeroExErrorHandler - public async matchOrdersAsync( - leftSignedOrder: SignedOrder, - rightSignedOrder: SignedOrder, - takerAddress: string, - orderTransactionOpts: OrderTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.doesConformToSchema('leftSignedOrder', leftSignedOrder, schemas.signedOrderSchema); - assert.doesConformToSchema('rightSignedOrder', rightSignedOrder, schemas.signedOrderSchema); - await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); - assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); - const normalizedTakerAddress = takerAddress.toLowerCase(); - if ( - rightSignedOrder.makerAssetData !== leftSignedOrder.takerAssetData || - rightSignedOrder.takerAssetData !== leftSignedOrder.makerAssetData - ) { - throw new Error(ExchangeWrapperError.AssetDataMismatch); - } - if (orderTransactionOpts.shouldValidate) { - await this._exchangeContract.matchOrders.callAsync( - leftSignedOrder, - rightSignedOrder, - leftSignedOrder.signature, - rightSignedOrder.signature, - { - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }, - ); - } - const txHash = await this._exchangeContract.matchOrders.sendTransactionAsync( - leftSignedOrder, - rightSignedOrder, - leftSignedOrder.signature, - rightSignedOrder.signature, - { - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }, - ); - return txHash; - } - /** - * Approves a hash on-chain using any valid signature type. - * After presigning a hash, the preSign signature type will become valid for that hash and signer. - * @param hash Hash to pre-sign - * @param signerAddress Address that should have signed the given hash. - * @param signature Proof that the hash has been signed by signer. - * @param senderAddress Address that should send the transaction. - * @param orderTransactionOpts Optional arguments this method accepts. - * @returns Transaction hash. - */ - @decorators.asyncZeroExErrorHandler - public async preSignAsync( - hash: string, - signerAddress: string, - signature: string, - senderAddress: string, - orderTransactionOpts: OrderTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isHexString('hash', hash); - assert.isETHAddressHex('signerAddress', signerAddress); - assert.isHexString('signature', signature); - await assert.isSenderAddressAsync('senderAddress', senderAddress, this._web3Wrapper); - assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); - const normalizedTakerAddress = senderAddress.toLowerCase(); - if (orderTransactionOpts.shouldValidate) { - await this._exchangeContract.preSign.callAsync(hash, signerAddress, signature, { - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }); - } - const txHash = await this._exchangeContract.preSign.sendTransactionAsync(hash, signerAddress, signature, { - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }); - return txHash; - } - /** - * Checks if the signature is valid. - * @param hash Hash to pre-sign - * @param signerAddress Address that should have signed the given hash. - * @param signature Proof that the hash has been signed by signer. - * @param methodOpts Optional arguments this method accepts. - * @returns If the signature is valid - */ - @decorators.asyncZeroExErrorHandler - public async isValidSignatureAsync( - hash: string, - signerAddress: string, - signature: string, - methodOpts: MethodOpts = {}, - ): Promise { - assert.isHexString('hash', hash); - assert.isETHAddressHex('signerAddress', signerAddress); - assert.isHexString('signature', signature); - assert.doesConformToSchema('methodOpts', methodOpts, methodOptsSchema); - const callData = {}; - const isValidSignature = await this._exchangeContract.isValidSignature.callAsync( - hash, - signerAddress, - signature, - callData, - methodOpts.defaultBlock, - ); - return isValidSignature; - } - /** - * Checks if the validator is allowed by the signer. - * @param validatorAddress Address of a validator - * @param signerAddress Address of a signer - * @param methodOpts Optional arguments this method accepts. - * @returns If the validator is allowed - */ - @decorators.asyncZeroExErrorHandler - public async isAllowedValidatorAsync( - signerAddress: string, - validatorAddress: string, - methodOpts: MethodOpts = {}, - ): Promise { - assert.isETHAddressHex('signerAddress', signerAddress); - assert.isETHAddressHex('validatorAddress', validatorAddress); - if (methodOpts !== undefined) { - assert.doesConformToSchema('methodOpts', methodOpts, methodOptsSchema); - } - const normalizedSignerAddress = signerAddress.toLowerCase(); - const normalizedValidatorAddress = validatorAddress.toLowerCase(); - const callData = {}; - const isValidSignature = await this._exchangeContract.allowedValidators.callAsync( - normalizedSignerAddress, - normalizedValidatorAddress, - callData, - methodOpts.defaultBlock, - ); - return isValidSignature; - } - /** - * Check whether the hash is pre-signed on-chain. - * @param hash Hash to check if pre-signed - * @param signerAddress Address that should have signed the given hash. - * @param methodOpts Optional arguments this method accepts. - * @returns Whether the hash is pre-signed. - */ - @decorators.asyncZeroExErrorHandler - public async isPreSignedAsync(hash: string, signerAddress: string, methodOpts: MethodOpts = {}): Promise { - assert.isHexString('hash', hash); - assert.isETHAddressHex('signerAddress', signerAddress); - if (methodOpts !== undefined) { - assert.doesConformToSchema('methodOpts', methodOpts, methodOptsSchema); - } - - const callData = {}; - const isPreSigned = await this._exchangeContract.preSigned.callAsync( - hash, - signerAddress, - callData, - methodOpts.defaultBlock, - ); - return isPreSigned; - } - /** - * Checks if transaction is already executed. - * @param transactionHash Transaction hash to check - * @param signerAddress Address that should have signed the given hash. - * @param methodOpts Optional arguments this method accepts. - * @returns If transaction is already executed. - */ - @decorators.asyncZeroExErrorHandler - public async isTransactionExecutedAsync(transactionHash: string, methodOpts: MethodOpts = {}): Promise { - assert.isHexString('transactionHash', transactionHash); - if (methodOpts !== undefined) { - assert.doesConformToSchema('methodOpts', methodOpts, methodOptsSchema); - } - const callData = {}; - const isExecuted = await this._exchangeContract.transactions.callAsync( - transactionHash, - callData, - methodOpts.defaultBlock, - ); - return isExecuted; - } - /** - * Get order info - * @param order Order - * @param methodOpts Optional arguments this method accepts. - * @returns Order info - */ - @decorators.asyncZeroExErrorHandler - public async getOrderInfoAsync(order: Order | SignedOrder, methodOpts: MethodOpts = {}): Promise { - assert.doesConformToSchema('order', order, schemas.orderSchema); - if (methodOpts !== undefined) { - assert.doesConformToSchema('methodOpts', methodOpts, methodOptsSchema); - } - const callData = {}; - const orderInfo = await this._exchangeContract.getOrderInfo.callAsync(order, callData, methodOpts.defaultBlock); - return orderInfo; - } - /** - * Get order info for multiple orders - * @param orders Orders - * @param methodOpts Optional arguments this method accepts. - * @returns Array of Order infos - */ - @decorators.asyncZeroExErrorHandler - public async getOrdersInfoAsync( - orders: Array, - methodOpts: MethodOpts = {}, - ): Promise { - assert.doesConformToSchema('orders', orders, schemas.ordersSchema); - if (methodOpts !== undefined) { - assert.doesConformToSchema('methodOpts', methodOpts, methodOptsSchema); - } - const callData = {}; - const ordersInfo = await this._exchangeContract.getOrdersInfo.callAsync( - orders, - callData, - methodOpts.defaultBlock, - ); - return ordersInfo; - } - /** - * Cancel a given order. - * @param order An object that conforms to the Order or SignedOrder interface. The order you would like to cancel. - * @param orderTransactionOpts Optional arguments this method accepts. - * @return Transaction hash. - */ - @decorators.asyncZeroExErrorHandler - public async cancelOrderAsync( - order: Order | SignedOrder, - orderTransactionOpts: OrderTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.doesConformToSchema('order', order, schemas.orderSchema); - await assert.isSenderAddressAsync('order.maker', order.makerAddress, this._web3Wrapper); - assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); - const normalizedMakerAddress = order.makerAddress.toLowerCase(); - - if (orderTransactionOpts.shouldValidate) { - await this._exchangeContract.cancelOrder.callAsync(order, { - from: normalizedMakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }); - } - const txHash = await this._exchangeContract.cancelOrder.sendTransactionAsync(order, { - from: normalizedMakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }); - return txHash; - } - /** - * Sets the signature validator approval - * @param validatorAddress Validator contract address. - * @param isApproved Boolean value to set approval to. - * @param senderAddress Sender address. - * @param orderTransactionOpts Optional arguments this method accepts. - * @return Transaction hash. - */ - @decorators.asyncZeroExErrorHandler - public async setSignatureValidatorApprovalAsync( - validatorAddress: string, - isApproved: boolean, - senderAddress: string, - orderTransactionOpts: OrderTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isETHAddressHex('validatorAddress', validatorAddress); - assert.isBoolean('isApproved', isApproved); - await assert.isSenderAddressAsync('senderAddress', senderAddress, this._web3Wrapper); - assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); - const normalizedSenderAddress = senderAddress.toLowerCase(); - - if (orderTransactionOpts.shouldValidate) { - await this._exchangeContract.setSignatureValidatorApproval.callAsync(validatorAddress, isApproved, { - from: normalizedSenderAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }); - } - const txHash = await this._exchangeContract.setSignatureValidatorApproval.sendTransactionAsync( - validatorAddress, - isApproved, - { - from: normalizedSenderAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }, - ); - return txHash; - } - /** - * 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). - * @param targetOrderEpoch Target order epoch. - * @param senderAddress Address that should send the transaction. - * @param orderTransactionOpts Optional arguments this method accepts. - * @return Transaction hash. - */ - @decorators.asyncZeroExErrorHandler - public async cancelOrdersUpToAsync( - targetOrderEpoch: BigNumber, - senderAddress: string, - orderTransactionOpts: OrderTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isBigNumber('targetOrderEpoch', targetOrderEpoch); - await assert.isSenderAddressAsync('senderAddress', senderAddress, this._web3Wrapper); - assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); - const normalizedSenderAddress = senderAddress.toLowerCase(); - - if (orderTransactionOpts.shouldValidate) { - await this._exchangeContract.cancelOrdersUpTo.callAsync(targetOrderEpoch, { - from: normalizedSenderAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }); - } - const txHash = await this._exchangeContract.cancelOrdersUpTo.sendTransactionAsync(targetOrderEpoch, { - from: normalizedSenderAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }); - return txHash; - } - /** - * Subscribe to an event type emitted by the Exchange contract. - * @param eventName The exchange 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: ExchangeEvents, - indexFilterValues: IndexedFilterValues, - callback: EventCallback, - isVerbose: boolean = false, - ): string { - assert.doesBelongToStringEnum('eventName', eventName, ExchangeEvents); - assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); - assert.isFunction('callback', callback); - const subscriptionToken = this._exchangeContract.subscribe( - eventName, - indexFilterValues, - callback, - isVerbose, - this._blockPollingIntervalMs, - ); - return subscriptionToken; - } - /** - * Cancel a subscription - * @param subscriptionToken Subscription token returned by `subscribe()` - */ - public unsubscribe(subscriptionToken: string): void { - this._exchangeContract.unsubscribe(subscriptionToken); - } - /** - * Cancels all existing subscriptions - */ - public unsubscribeAll(): void { - this._exchangeContract.unsubscribeAll(); - } - /** - * Gets historical logs without creating a subscription - * @param eventName The exchange 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: ExchangeEvents, - blockRange: BlockRange, - indexFilterValues: IndexedFilterValues, - ): Promise>> { - assert.doesBelongToStringEnum('eventName', eventName, ExchangeEvents); - assert.doesConformToSchema('blockRange', blockRange, schemas.blockRangeSchema); - assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); - const logs = await this._exchangeContract.getLogsAsync(eventName, blockRange, indexFilterValues); - return logs; - } - /** - * Validate if the supplied order is fillable, and throw if it isn't - * @param signedOrder SignedOrder of interest - * @param opts ValidateOrderFillableOpts options (e.g expectedFillTakerTokenAmount. - * If it isn't supplied, we check if the order is fillable for the remaining amount. - * To check if the order is fillable for a non-zero amount, set `validateRemainingOrderAmountIsFillable` to false.) - */ - public async validateOrderFillableOrThrowAsync( - signedOrder: SignedOrder, - opts: ValidateOrderFillableOpts = {}, - ): Promise { - assert.doesConformToSchema('signedOrder', signedOrder, schemas.signedOrderSchema); - assert.doesConformToSchema('opts', opts, validateOrderFillableOptsSchema); - - const balanceAllowanceFetcher = new AssetBalanceAndProxyAllowanceFetcher( - this._erc20TokenWrapper, - this._erc721TokenWrapper, - BlockParamLiteral.Latest, - ); - const balanceAllowanceStore = new BalanceAndProxyAllowanceLazyStore(balanceAllowanceFetcher); - const exchangeTradeSimulator = new ExchangeTransferSimulator(balanceAllowanceStore); - const filledCancelledFetcher = new OrderFilledCancelledFetcher(this, BlockParamLiteral.Latest); - - let fillableTakerAssetAmount; - const shouldValidateRemainingOrderAmountIsFillable = - opts.validateRemainingOrderAmountIsFillable === undefined - ? true - : opts.validateRemainingOrderAmountIsFillable; - if (opts.expectedFillTakerTokenAmount) { - // If the caller has specified a taker fill amount, we use this for all validation - fillableTakerAssetAmount = opts.expectedFillTakerTokenAmount; - } else if (shouldValidateRemainingOrderAmountIsFillable) { - // Default behaviour is to validate the amount left on the order. - const filledTakerTokenAmount = await this.getFilledTakerAssetAmountAsync( - orderHashUtils.getOrderHashHex(signedOrder), - ); - fillableTakerAssetAmount = signedOrder.takerAssetAmount.minus(filledTakerTokenAmount); - } else { - const orderStateUtils = new OrderStateUtils(balanceAllowanceStore, filledCancelledFetcher); - // Calculate the taker amount fillable given the maker balance and allowance - const orderRelevantState = await orderStateUtils.getOpenOrderRelevantStateAsync(signedOrder); - fillableTakerAssetAmount = orderRelevantState.remainingFillableTakerAssetAmount; - } - - const orderValidationUtils = new OrderValidationUtils(filledCancelledFetcher, this._web3Wrapper.getProvider()); - await orderValidationUtils.validateOrderFillableOrThrowAsync( - exchangeTradeSimulator, - signedOrder, - this.getZRXAssetData(), - fillableTakerAssetAmount, - ); - const makerTransferAmount = orderCalculationUtils.getMakerFillAmount(signedOrder, fillableTakerAssetAmount); - await this.validateMakerTransferThrowIfInvalidAsync( - signedOrder, - makerTransferAmount, - opts.simulationTakerAddress, - ); - } - /** - * Validate the transfer from the maker to the taker. This is simulated on-chain - * via an eth_call. If this call fails, the asset is currently nontransferable. - * @param signedOrder SignedOrder of interest - * @param makerAssetAmount Amount to transfer from the maker - * @param takerAddress The address to transfer to, defaults to signedOrder.takerAddress - */ - public async validateMakerTransferThrowIfInvalidAsync( - signedOrder: SignedOrder, - makerAssetAmount: BigNumber, - takerAddress?: string, - ): Promise { - const networkId = await this._web3Wrapper.getNetworkIdAsync(); - await OrderValidationUtils.validateMakerTransferThrowIfInvalidAsync( - networkId, - this._web3Wrapper.getProvider(), - signedOrder, - makerAssetAmount, - takerAddress, - ); - } - /** - * Validate a call to FillOrder and throw if it wouldn't succeed - * @param signedOrder SignedOrder of interest - * @param fillTakerAssetAmount Amount we'd like to fill the order for - * @param takerAddress The taker of the order - */ - public async validateFillOrderThrowIfInvalidAsync( - signedOrder: SignedOrder, - fillTakerAssetAmount: BigNumber, - takerAddress: string, - ): Promise { - const balanceAllowanceFetcher = new AssetBalanceAndProxyAllowanceFetcher( - this._erc20TokenWrapper, - this._erc721TokenWrapper, - BlockParamLiteral.Latest, - ); - const balanceAllowanceStore = new BalanceAndProxyAllowanceLazyStore(balanceAllowanceFetcher); - const exchangeTradeSimulator = new ExchangeTransferSimulator(balanceAllowanceStore); - - const filledCancelledFetcher = new OrderFilledCancelledFetcher(this, BlockParamLiteral.Latest); - const orderValidationUtils = new OrderValidationUtils(filledCancelledFetcher, this._web3Wrapper.getProvider()); - await orderValidationUtils.validateFillOrderThrowIfInvalidAsync( - exchangeTradeSimulator, - this._web3Wrapper.getProvider(), - signedOrder, - fillTakerAssetAmount, - takerAddress, - this.getZRXAssetData(), - ); - } - /** - * Returns the ZRX asset data used by the exchange contract. - * @return ZRX asset data - */ - public getZRXAssetData(): string { - const zrxAssetData = assetDataUtils.encodeERC20AssetData(this.zrxTokenAddress); - return zrxAssetData; - } - /** - * Returns a Transaction Encoder. Transaction messages exist for the purpose of calling methods on the Exchange contract - * in the context of another address. - * @return TransactionEncoder - */ - public async transactionEncoderAsync(): Promise { - const encoder = new TransactionEncoder(this._exchangeContract); - return encoder; - } -} // tslint:disable:max-file-line-count diff --git a/packages/contract-wrappers/src/contract_wrappers/forwarder_wrapper.ts b/packages/contract-wrappers/src/contract_wrappers/forwarder_wrapper.ts deleted file mode 100644 index ecca85c1bd..0000000000 --- a/packages/contract-wrappers/src/contract_wrappers/forwarder_wrapper.ts +++ /dev/null @@ -1,239 +0,0 @@ -import { ForwarderContract } from '@0x/abi-gen-wrappers'; -import { Forwarder } from '@0x/contract-artifacts'; -import { schemas } from '@0x/json-schemas'; -import { SignedOrder } from '@0x/types'; -import { BigNumber } from '@0x/utils'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import { ContractAbi } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { orderTxOptsSchema } from '../schemas/order_tx_opts_schema'; -import { txOptsSchema } from '../schemas/tx_opts_schema'; -import { OrderTransactionOpts } from '../types'; -import { assert } from '../utils/assert'; -import { calldataOptimizationUtils } from '../utils/calldata_optimization_utils'; -import { constants } from '../utils/constants'; -import { _getDefaultContractAddresses } from '../utils/contract_addresses'; -import { decorators } from '../utils/decorators'; -import { utils } from '../utils/utils'; - -/** - * This class includes the functionality related to interacting with the Forwarder contract. - */ -export class ForwarderWrapper { - public abi: ContractAbi = Forwarder.compilerOutput.abi; - public address: string; - public zrxTokenAddress: string; - public etherTokenAddress: string; - private readonly _web3Wrapper: Web3Wrapper; - private readonly _forwarderContract: ForwarderContract; - - /** - * Instantiate ForwarderWrapper - * @param web3Wrapper Web3Wrapper instance to use. - * @param networkId Desired networkId. - * @param address The address of the Exchange contract. If undefined, will - * default to the known address corresponding to the networkId. - * @param zrxTokenAddress The address of the ZRXToken contract. If - * undefined, will default to the known address corresponding to the - * networkId. - * @param etherTokenAddress The address of a WETH (Ether token) contract. If - * undefined, will default to the known address corresponding to the - * networkId. - */ - constructor( - web3Wrapper: Web3Wrapper, - networkId: number, - address?: string, - zrxTokenAddress?: string, - etherTokenAddress?: string, - ) { - this._web3Wrapper = web3Wrapper; - this.address = address === undefined ? _getDefaultContractAddresses(networkId).exchange : address; - this.zrxTokenAddress = - zrxTokenAddress === undefined ? _getDefaultContractAddresses(networkId).zrxToken : zrxTokenAddress; - this.etherTokenAddress = - etherTokenAddress === undefined ? _getDefaultContractAddresses(networkId).etherToken : etherTokenAddress; - this._forwarderContract = new ForwarderContract( - this.address, - this._web3Wrapper.getProvider(), - this._web3Wrapper.getContractDefaults(), - ); - } - /** - * Purchases as much of orders' makerAssets as possible by selling up to 95% of transaction's ETH value. - * Any ZRX required to pay fees for primary orders will automatically be purchased by this contract. - * 5% of ETH value is reserved for paying fees to order feeRecipients (in ZRX) and forwarding contract feeRecipient (in ETH). - * Any ETH not spent will be refunded to sender. - * @param signedOrders An array of objects that conform to the SignedOrder interface. All orders must specify the same makerAsset. - * All orders must specify WETH as the takerAsset - * @param takerAddress The user Ethereum address who would like to fill this order. Must be available via the supplied - * Provider provided at instantiation. - * @param ethAmount The amount of eth to send with the transaction (in wei). - * @param signedFeeOrders An array of objects that conform to the SignedOrder interface. All orders must specify ZRX as makerAsset and WETH as takerAsset. - * Used to purchase ZRX for primary order fees. - * @param feePercentage The percentage of WETH sold that will payed as fee to forwarding contract feeRecipient. - * Defaults to 0. - * @param feeRecipientAddress The address that will receive ETH when signedFeeOrders are filled. - * @param orderTransactionOpts Transaction parameters. - * @return Transaction hash. - */ - @decorators.asyncZeroExErrorHandler - public async marketSellOrdersWithEthAsync( - signedOrders: SignedOrder[], - takerAddress: string, - ethAmount: BigNumber, - signedFeeOrders: SignedOrder[] = [], - feePercentage: number = 0, - feeRecipientAddress: string = constants.NULL_ADDRESS, - orderTransactionOpts: OrderTransactionOpts = { shouldValidate: true }, - ): Promise { - // type assertions - assert.doesConformToSchema('signedOrders', signedOrders, schemas.signedOrdersSchema); - await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); - assert.isBigNumber('ethAmount', ethAmount); - assert.doesConformToSchema('signedFeeOrders', signedFeeOrders, schemas.signedOrdersSchema); - assert.isNumber('feePercentage', feePercentage); - assert.isETHAddressHex('feeRecipientAddress', feeRecipientAddress); - assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); - // other assertions - assert.ordersCanBeUsedForForwarderContract(signedOrders, this.etherTokenAddress); - assert.feeOrdersCanBeUsedForForwarderContract(signedFeeOrders, this.zrxTokenAddress, this.etherTokenAddress); - // format feePercentage - const formattedFeePercentage = utils.numberPercentageToEtherTokenAmountPercentage(feePercentage); - // lowercase input addresses - const normalizedTakerAddress = takerAddress.toLowerCase(); - const normalizedFeeRecipientAddress = feeRecipientAddress.toLowerCase(); - // optimize orders - const optimizedMarketOrders = calldataOptimizationUtils.optimizeForwarderOrders(signedOrders); - const optimizedFeeOrders = calldataOptimizationUtils.optimizeForwarderFeeOrders(signedFeeOrders); - // compile signatures - const signatures = _.map(optimizedMarketOrders, order => order.signature); - const feeSignatures = _.map(optimizedFeeOrders, order => order.signature); - // validate transaction - if (orderTransactionOpts.shouldValidate) { - await this._forwarderContract.marketSellOrdersWithEth.callAsync( - optimizedMarketOrders, - signatures, - optimizedFeeOrders, - feeSignatures, - formattedFeePercentage, - normalizedFeeRecipientAddress, - { - value: ethAmount, - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }, - ); - } - // send transaction - const txHash = await this._forwarderContract.marketSellOrdersWithEth.sendTransactionAsync( - optimizedMarketOrders, - signatures, - optimizedFeeOrders, - feeSignatures, - formattedFeePercentage, - feeRecipientAddress, - { - value: ethAmount, - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }, - ); - return txHash; - } - /** - * Attempt to purchase makerAssetFillAmount of makerAsset by selling ethAmount provided with transaction. - * Any ZRX required to pay fees for primary orders will automatically be purchased by the contract. - * Any ETH not spent will be refunded to sender. - * @param signedOrders An array of objects that conform to the SignedOrder interface. All orders must specify the same makerAsset. - * All orders must specify WETH as the takerAsset - * @param makerAssetFillAmount The amount of the order (in taker asset baseUnits) that you wish to fill. - * @param takerAddress The user Ethereum address who would like to fill this order. Must be available via the supplied - * Provider provided at instantiation. - * @param ethAmount The amount of eth to send with the transaction (in wei). - * @param signedFeeOrders An array of objects that conform to the SignedOrder interface. All orders must specify ZRX as makerAsset and WETH as takerAsset. - * Used to purchase ZRX for primary order fees. - * @param feePercentage The percentage of WETH sold that will payed as fee to forwarding contract feeRecipient. - * Defaults to 0. - * @param feeRecipientAddress The address that will receive ETH when signedFeeOrders are filled. - * @param orderTransactionOpts Transaction parameters. - * @return Transaction hash. - */ - @decorators.asyncZeroExErrorHandler - public async marketBuyOrdersWithEthAsync( - signedOrders: SignedOrder[], - makerAssetFillAmount: BigNumber, - takerAddress: string, - ethAmount: BigNumber, - signedFeeOrders: SignedOrder[] = [], - feePercentage: number = 0, - feeRecipientAddress: string = constants.NULL_ADDRESS, - orderTransactionOpts: OrderTransactionOpts = { shouldValidate: true }, - ): Promise { - // type assertions - assert.doesConformToSchema('signedOrders', signedOrders, schemas.signedOrdersSchema); - assert.isBigNumber('makerAssetFillAmount', makerAssetFillAmount); - await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); - assert.isBigNumber('ethAmount', ethAmount); - assert.doesConformToSchema('signedFeeOrders', signedFeeOrders, schemas.signedOrdersSchema); - assert.isNumber('feePercentage', feePercentage); - assert.isETHAddressHex('feeRecipientAddress', feeRecipientAddress); - assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); - // other assertions - assert.ordersCanBeUsedForForwarderContract(signedOrders, this.etherTokenAddress); - assert.feeOrdersCanBeUsedForForwarderContract(signedFeeOrders, this.zrxTokenAddress, this.etherTokenAddress); - // format feePercentage - const formattedFeePercentage = utils.numberPercentageToEtherTokenAmountPercentage(feePercentage); - // lowercase input addresses - const normalizedTakerAddress = takerAddress.toLowerCase(); - const normalizedFeeRecipientAddress = feeRecipientAddress.toLowerCase(); - // optimize orders - const optimizedMarketOrders = calldataOptimizationUtils.optimizeForwarderOrders(signedOrders); - const optimizedFeeOrders = calldataOptimizationUtils.optimizeForwarderFeeOrders(signedFeeOrders); - // compile signatures - const signatures = _.map(optimizedMarketOrders, order => order.signature); - const feeSignatures = _.map(optimizedFeeOrders, order => order.signature); - // validate transaction - if (orderTransactionOpts.shouldValidate) { - await this._forwarderContract.marketBuyOrdersWithEth.callAsync( - optimizedMarketOrders, - makerAssetFillAmount, - signatures, - optimizedFeeOrders, - feeSignatures, - formattedFeePercentage, - normalizedFeeRecipientAddress, - { - value: ethAmount, - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }, - ); - } - // send transaction - const txHash = await this._forwarderContract.marketBuyOrdersWithEth.sendTransactionAsync( - optimizedMarketOrders, - makerAssetFillAmount, - signatures, - optimizedFeeOrders, - feeSignatures, - formattedFeePercentage, - feeRecipientAddress, - { - value: ethAmount, - from: normalizedTakerAddress, - gas: orderTransactionOpts.gasLimit, - gasPrice: orderTransactionOpts.gasPrice, - nonce: orderTransactionOpts.nonce, - }, - ); - return txHash; - } -} diff --git a/packages/contract-wrappers/src/contract_wrappers/order_validator_wrapper.ts b/packages/contract-wrappers/src/contract_wrappers/order_validator_wrapper.ts deleted file mode 100644 index e5c1ce8a6c..0000000000 --- a/packages/contract-wrappers/src/contract_wrappers/order_validator_wrapper.ts +++ /dev/null @@ -1,169 +0,0 @@ -import { OrderValidatorContract } from '@0x/abi-gen-wrappers'; -import { OrderValidator } from '@0x/contract-artifacts'; -import { schemas } from '@0x/json-schemas'; -import { SignedOrder } from '@0x/types'; -import { BigNumber } from '@0x/utils'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import { ContractAbi } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { BalanceAndAllowance, OrderAndTraderInfo, TraderInfo } from '../types'; -import { assert } from '../utils/assert'; -import { _getDefaultContractAddresses } from '../utils/contract_addresses'; - -/** - * This class includes the functionality related to interacting with the OrderValidator contract. - */ -export class OrderValidatorWrapper { - public abi: ContractAbi = OrderValidator.compilerOutput.abi; - public address: string; - private readonly _web3Wrapper: Web3Wrapper; - private readonly _orderValidatorContract: OrderValidatorContract; - /** - * Instantiate OrderValidatorWrapper - * @param web3Wrapper Web3Wrapper instance to use. - * @param networkId Desired networkId. - * @param address The address of the OrderValidator contract. If undefined, - * will default to the known address corresponding to the networkId. - */ - constructor(web3Wrapper: Web3Wrapper, networkId: number, address?: string) { - this._web3Wrapper = web3Wrapper; - this.address = address === undefined ? _getDefaultContractAddresses(networkId).orderValidator : address; - this._orderValidatorContract = new OrderValidatorContract( - this.address, - this._web3Wrapper.getProvider(), - this._web3Wrapper.getContractDefaults(), - ); - } - /** - * Get an object conforming to OrderAndTraderInfo containing on-chain information of the provided order and address - * @param order An object conforming to SignedOrder - * @param takerAddress An ethereum address - * @return OrderAndTraderInfo - */ - public async getOrderAndTraderInfoAsync(order: SignedOrder, takerAddress: string): Promise { - assert.doesConformToSchema('order', order, schemas.signedOrderSchema); - assert.isETHAddressHex('takerAddress', takerAddress); - const orderAndTraderInfo = await this._orderValidatorContract.getOrderAndTraderInfo.callAsync( - order, - takerAddress, - ); - const result = { - orderInfo: orderAndTraderInfo[0], - traderInfo: orderAndTraderInfo[1], - }; - return result; - } - /** - * Get an array of objects conforming to OrderAndTraderInfo containing on-chain information of the provided orders and addresses - * @param orders An array of objects conforming to SignedOrder - * @param takerAddresses An array of ethereum addresses - * @return array of OrderAndTraderInfo - */ - public async getOrdersAndTradersInfoAsync( - orders: SignedOrder[], - takerAddresses: string[], - ): Promise { - assert.doesConformToSchema('orders', orders, schemas.signedOrdersSchema); - _.forEach(takerAddresses, (takerAddress, index) => - assert.isETHAddressHex(`takerAddresses[${index}]`, takerAddress), - ); - assert.assert(orders.length === takerAddresses.length, 'Expected orders.length to equal takerAddresses.length'); - const ordersAndTradersInfo = await this._orderValidatorContract.getOrdersAndTradersInfo.callAsync( - orders, - takerAddresses, - ); - const orderInfos = ordersAndTradersInfo[0]; - const traderInfos = ordersAndTradersInfo[1]; - const result = _.map(orderInfos, (orderInfo, index) => { - const traderInfo = traderInfos[index]; - return { - orderInfo, - traderInfo, - }; - }); - return result; - } - /** - * Get an object conforming to TraderInfo containing on-chain balance and allowances for maker and taker of order - * @param order An object conforming to SignedOrder - * @param takerAddress An ethereum address - * @return TraderInfo - */ - public async getTraderInfoAsync(order: SignedOrder, takerAddress: string): Promise { - assert.doesConformToSchema('order', order, schemas.signedOrderSchema); - assert.isETHAddressHex('takerAddress', takerAddress); - const result = await this._orderValidatorContract.getTraderInfo.callAsync(order, takerAddress); - return result; - } - /** - * Get an array of objects conforming to TraderInfo containing on-chain balance and allowances for maker and taker of order - * @param orders An array of objects conforming to SignedOrder - * @param takerAddresses An array of ethereum addresses - * @return array of TraderInfo - */ - public async getTradersInfoAsync(orders: SignedOrder[], takerAddresses: string[]): Promise { - assert.doesConformToSchema('orders', orders, schemas.signedOrdersSchema); - _.forEach(takerAddresses, (takerAddress, index) => - assert.isETHAddressHex(`takerAddresses[${index}]`, takerAddress), - ); - assert.assert(orders.length === takerAddresses.length, 'Expected orders.length to equal takerAddresses.length'); - const result = await this._orderValidatorContract.getTradersInfo.callAsync(orders, takerAddresses); - return result; - } - /** - * Get an object conforming to BalanceAndAllowance containing on-chain balance and allowance for some address and assetData - * @param address An ethereum address - * @param assetData An encoded string that can be decoded by a specified proxy contract - * @return BalanceAndAllowance - */ - public async getBalanceAndAllowanceAsync(address: string, assetData: string): Promise { - assert.isETHAddressHex('address', address); - assert.isHexString('assetData', assetData); - const balanceAndAllowance = await this._orderValidatorContract.getBalanceAndAllowance.callAsync( - address, - assetData, - ); - const result = { - balance: balanceAndAllowance[0], - allowance: balanceAndAllowance[1], - }; - return result; - } - /** - * Get an array of objects conforming to BalanceAndAllowance containing on-chain balance and allowance for some address and array of assetDatas - * @param address An ethereum address - * @param assetDatas An array of encoded strings that can be decoded by a specified proxy contract - * @return BalanceAndAllowance - */ - public async getBalancesAndAllowancesAsync(address: string, assetDatas: string[]): Promise { - assert.isETHAddressHex('address', address); - _.forEach(assetDatas, (assetData, index) => assert.isHexString(`assetDatas[${index}]`, assetData)); - const balancesAndAllowances = await this._orderValidatorContract.getBalancesAndAllowances.callAsync( - address, - assetDatas, - ); - const balances = balancesAndAllowances[0]; - const allowances = balancesAndAllowances[1]; - const result = _.map(balances, (balance, index) => { - const allowance = allowances[index]; - return { - balance, - allowance, - }; - }); - return result; - } - /** - * Get owner address of tokenId by calling `token.ownerOf(tokenId)`, but returns a null owner instead of reverting on an unowned token. - * @param tokenAddress An ethereum address - * @param tokenId An ERC721 tokenId - * @return Owner of tokenId or null address if unowned - */ - public async getERC721TokenOwnerAsync(tokenAddress: string, tokenId: BigNumber): Promise { - assert.isETHAddressHex('tokenAddress', tokenAddress); - assert.isBigNumber('tokenId', tokenId); - const result = await this._orderValidatorContract.getERC721TokenOwner.callAsync(tokenAddress, tokenId); - return result; - } -} diff --git a/packages/contract-wrappers/src/contract_wrappers/coordinator_wrapper.ts b/packages/contract-wrappers/src/coordinator_wrapper.ts similarity index 92% rename from packages/contract-wrappers/src/contract_wrappers/coordinator_wrapper.ts rename to packages/contract-wrappers/src/coordinator_wrapper.ts index 8a1659363e..8c0445cef4 100644 --- a/packages/contract-wrappers/src/contract_wrappers/coordinator_wrapper.ts +++ b/packages/contract-wrappers/src/coordinator_wrapper.ts @@ -1,4 +1,3 @@ -import { CoordinatorContract, CoordinatorRegistryContract, ExchangeContract } from '@0x/abi-gen-wrappers'; import { getContractAddressesForNetworkOrThrow } from '@0x/contract-addresses'; import { Coordinator } from '@0x/contract-artifacts'; import { schemas } from '@0x/json-schemas'; @@ -10,10 +9,12 @@ import { ContractAbi } from 'ethereum-types'; import * as HttpStatus from 'http-status-codes'; import { flatten } from 'lodash'; -import { orderTxOptsSchema } from '../schemas/order_tx_opts_schema'; -import { txOptsSchema } from '../schemas/tx_opts_schema'; -import { CoordinatorTransaction, OrderTransactionOpts } from '../types'; -import { assert } from '../utils/assert'; +import { CoordinatorContract, CoordinatorRegistryContract, ExchangeContract } from './index'; + +import { orderTxOptsSchema } from './schemas/order_tx_opts_schema'; +import { txOptsSchema } from './schemas/tx_opts_schema'; +import { CoordinatorTransaction, OrderTransactionOpts } from './types'; +import { assert } from './utils/assert'; import { CoordinatorServerApprovalRawResponse, CoordinatorServerApprovalResponse, @@ -21,9 +22,9 @@ import { CoordinatorServerError, CoordinatorServerErrorMsg, CoordinatorServerResponse, -} from '../utils/coordinator_server_types'; -import { decorators } from '../utils/decorators'; -import { TransactionEncoder } from '../utils/transaction_encoder'; +} from './utils/coordinator_server_types'; +import { decorators } from './utils/decorators'; +import { getAbiEncodedTransactionData } from './utils/getAbiEncodedTransactionData'; /** * This class includes all the functionality related to filling or cancelling orders through @@ -39,7 +40,6 @@ export class CoordinatorWrapper { private readonly _contractInstance: CoordinatorContract; private readonly _registryInstance: CoordinatorRegistryContract; private readonly _exchangeInstance: ExchangeContract; - private readonly _transactionEncoder: TransactionEncoder; private readonly _feeRecipientToEndpoint: { [feeRecipient: string]: string } = {}; /** @@ -82,8 +82,6 @@ export class CoordinatorWrapper { this._web3Wrapper.getProvider(), this._web3Wrapper.getContractDefaults(), ); - - this._transactionEncoder = new TransactionEncoder(this._exchangeInstance); } /** @@ -112,7 +110,12 @@ export class CoordinatorWrapper { assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); - const data = this._transactionEncoder.fillOrderTx(signedOrder, takerAssetFillAmount); + const data = this._getAbiEncodedTransactionData( + 'fillOrder', + signedOrder, + takerAssetFillAmount, + signedOrder.signature, + ); const txHash = await this._handleFillsAsync(data, takerAddress, [signedOrder], orderTransactionOpts); return txHash; } @@ -139,7 +142,12 @@ export class CoordinatorWrapper { assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); - const data = this._transactionEncoder.fillOrderNoThrowTx(signedOrder, takerAssetFillAmount); + const data = this._getAbiEncodedTransactionData( + 'fillOrderNoThrow', + signedOrder, + takerAssetFillAmount, + signedOrder.signature, + ); const txHash = await this._handleFillsAsync(data, takerAddress, [signedOrder], orderTransactionOpts); return txHash; } @@ -167,7 +175,12 @@ export class CoordinatorWrapper { assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); - const data = this._transactionEncoder.fillOrKillOrderTx(signedOrder, takerAssetFillAmount); + const data = this._getAbiEncodedTransactionData( + 'fillOrKillOrder', + signedOrder, + takerAssetFillAmount, + signedOrder.signature, + ); const txHash = await this._handleFillsAsync(data, takerAddress, [signedOrder], orderTransactionOpts); return txHash; } @@ -201,7 +214,13 @@ export class CoordinatorWrapper { assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); - const data = this._transactionEncoder.batchFillOrdersTx(signedOrders, takerAssetFillAmounts); + const signatures = signedOrders.map(o => o.signature); + const data = this._getAbiEncodedTransactionData( + 'batchFillOrders', + signedOrders, + takerAssetFillAmounts, + signatures, + ); const txHash = await this._handleFillsAsync(data, takerAddress, signedOrders, orderTransactionOpts); return txHash; } @@ -230,7 +249,13 @@ export class CoordinatorWrapper { assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); - const data = this._transactionEncoder.batchFillOrdersNoThrowTx(signedOrders, takerAssetFillAmounts); + const signatures = signedOrders.map(o => o.signature); + const data = this._getAbiEncodedTransactionData( + 'batchFillOrdersNoThrow', + signedOrders, + takerAssetFillAmounts, + signatures, + ); const txHash = await this._handleFillsAsync(data, takerAddress, signedOrders, orderTransactionOpts); return txHash; } @@ -259,7 +284,13 @@ export class CoordinatorWrapper { assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); - const data = this._transactionEncoder.batchFillOrKillOrdersTx(signedOrders, takerAssetFillAmounts); + const signatures = signedOrders.map(o => o.signature); + const data = this._getAbiEncodedTransactionData( + 'batchFillOrKillOrders', + signedOrders, + takerAssetFillAmounts, + signatures, + ); const txHash = await this._handleFillsAsync(data, takerAddress, signedOrders, orderTransactionOpts); return txHash; } @@ -291,7 +322,13 @@ export class CoordinatorWrapper { assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); - const data = this._transactionEncoder.marketBuyOrdersTx(signedOrders, makerAssetFillAmount); + const signatures = signedOrders.map(o => o.signature); + const data = this._getAbiEncodedTransactionData( + 'marketBuyOrders', + signedOrders, + makerAssetFillAmount, + signatures, + ); const txHash = await this._handleFillsAsync(data, takerAddress, signedOrders, orderTransactionOpts); return txHash; } @@ -323,7 +360,13 @@ export class CoordinatorWrapper { assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); - const data = this._transactionEncoder.marketSellOrdersTx(signedOrders, takerAssetFillAmount); + const signatures = signedOrders.map(o => o.signature); + const data = this._getAbiEncodedTransactionData( + 'marketSellOrders', + signedOrders, + takerAssetFillAmount, + signatures, + ); const txHash = await this._handleFillsAsync(data, takerAddress, signedOrders, orderTransactionOpts); return txHash; } @@ -350,7 +393,13 @@ export class CoordinatorWrapper { assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); - const data = this._transactionEncoder.marketBuyOrdersNoThrowTx(signedOrders, makerAssetFillAmount); + const signatures = signedOrders.map(o => o.signature); + const data = this._getAbiEncodedTransactionData( + 'marketBuyOrdersNoThrow', + signedOrders, + makerAssetFillAmount, + signatures, + ); const txHash = await this._handleFillsAsync(data, takerAddress, signedOrders, orderTransactionOpts); return txHash; } @@ -377,7 +426,13 @@ export class CoordinatorWrapper { assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); - const data = this._transactionEncoder.marketSellOrdersNoThrowTx(signedOrders, takerAssetFillAmount); + const signatures = signedOrders.map(o => o.signature); + const data = this._getAbiEncodedTransactionData( + 'marketSellOrdersNoThrow', + signedOrders, + takerAssetFillAmount, + signatures, + ); const txHash = await this._handleFillsAsync(data, takerAddress, signedOrders, orderTransactionOpts); return txHash; } @@ -394,7 +449,7 @@ export class CoordinatorWrapper { assert.isETHAddressHex('feeRecipientAddress', order.feeRecipientAddress); assert.isSenderAddressAsync('makerAddress', order.makerAddress, this._web3Wrapper); - const data = this._transactionEncoder.cancelOrderTx(order); + const data = this._getAbiEncodedTransactionData('cancelOrder', order); const transaction = await this._generateSignedZeroExTransactionAsync(data, order.makerAddress); const endpoint = await this._getServerEndpointOrThrowAsync(order.feeRecipientAddress); @@ -428,7 +483,7 @@ export class CoordinatorWrapper { assert.doesConformToSchema('orders', orders, schemas.ordersSchema); const makerAddress = getMakerAddressOrThrow(orders); assert.isSenderAddressAsync('makerAddress', makerAddress, this._web3Wrapper); - const data = this._transactionEncoder.batchCancelOrdersTx(orders); + const data = this._getAbiEncodedTransactionData('batchCancelOrders', orders); const serverEndpointsToOrders = await this._mapServerEndpointsToOrdersAsync(orders); @@ -486,7 +541,7 @@ export class CoordinatorWrapper { assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); await assert.isSenderAddressAsync('makerAddress', order.makerAddress, this._web3Wrapper); - const data = this._transactionEncoder.cancelOrderTx(order); + const data = this._getAbiEncodedTransactionData('cancelOrder', order); const transaction = await this._generateSignedZeroExTransactionAsync(data, order.makerAddress); const approvalSignatures = new Array(); @@ -519,7 +574,7 @@ export class CoordinatorWrapper { assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); await assert.isSenderAddressAsync('makerAddress', makerAddress, this._web3Wrapper); - const data = this._transactionEncoder.batchCancelOrdersTx(orders); + const data = this._getAbiEncodedTransactionData('batchCancelOrders', orders); const transaction = await this._generateSignedZeroExTransactionAsync(data, makerAddress); const approvalSignatures = new Array(); @@ -554,7 +609,7 @@ export class CoordinatorWrapper { assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); await assert.isSenderAddressAsync('senderAddress', senderAddress, this._web3Wrapper); - const data = this._transactionEncoder.cancelOrdersUpToTx(targetOrderEpoch); + const data = this._getAbiEncodedTransactionData('cancelOrdersUpTo', targetOrderEpoch); const transaction = await this._generateSignedZeroExTransactionAsync(data, senderAddress); const approvalSignatures = new Array(); @@ -618,6 +673,10 @@ export class CoordinatorWrapper { return signerAddress; } + private _getAbiEncodedTransactionData(methodName: K, ...args: any[]): string { + return getAbiEncodedTransactionData(this._exchangeInstance, methodName, ...args); + } + private async _handleFillsAsync( data: string, takerAddress: string, diff --git a/packages/contract-wrappers/src/fetchers/asset_balance_and_proxy_allowance_fetcher.ts b/packages/contract-wrappers/src/fetchers/asset_balance_and_proxy_allowance_fetcher.ts deleted file mode 100644 index e5ff03862d..0000000000 --- a/packages/contract-wrappers/src/fetchers/asset_balance_and_proxy_allowance_fetcher.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { AbstractBalanceAndProxyAllowanceFetcher, assetDataUtils } from '@0x/order-utils'; -import { BigNumber } from '@0x/utils'; -import { BlockParamLiteral } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { ERC20TokenWrapper } from '../contract_wrappers/erc20_token_wrapper'; -import { ERC721TokenWrapper } from '../contract_wrappers/erc721_token_wrapper'; - -export class AssetBalanceAndProxyAllowanceFetcher implements AbstractBalanceAndProxyAllowanceFetcher { - private readonly _erc20Token: ERC20TokenWrapper; - private readonly _erc721Token: ERC721TokenWrapper; - private readonly _stateLayer: BlockParamLiteral; - constructor(erc20Token: ERC20TokenWrapper, erc721Token: ERC721TokenWrapper, stateLayer: BlockParamLiteral) { - this._erc20Token = erc20Token; - this._erc721Token = erc721Token; - this._stateLayer = stateLayer; - } - public async getBalanceAsync(assetData: string, userAddress: string): Promise { - const decodedAssetData = assetDataUtils.decodeAssetDataOrThrow(assetData); - let balance: BigNumber | undefined; - if (assetDataUtils.isERC20AssetData(decodedAssetData)) { - balance = await this._erc20Token.getBalanceAsync(decodedAssetData.tokenAddress, userAddress, { - defaultBlock: this._stateLayer, - }); - } else if (assetDataUtils.isERC721AssetData(decodedAssetData)) { - const tokenOwner = await this._erc721Token.getOwnerOfAsync( - decodedAssetData.tokenAddress, - decodedAssetData.tokenId, - { - defaultBlock: this._stateLayer, - }, - ); - balance = tokenOwner === userAddress ? new BigNumber(1) : new BigNumber(0); - } else if (assetDataUtils.isMultiAssetData(decodedAssetData)) { - // The `balance` for MultiAssetData is the total units of the entire `assetData` that are held by the `userAddress`. - for (const [index, nestedAssetDataElement] of decodedAssetData.nestedAssetData.entries()) { - const nestedAmountElement = decodedAssetData.amounts[index]; - const nestedAssetBalance = (await this.getBalanceAsync( - nestedAssetDataElement, - userAddress, - )).dividedToIntegerBy(nestedAmountElement); - if (balance === undefined || nestedAssetBalance.isLessThan(balance)) { - balance = nestedAssetBalance; - } - } - } - return balance as BigNumber; - } - public async getProxyAllowanceAsync(assetData: string, userAddress: string): Promise { - const decodedAssetData = assetDataUtils.decodeAssetDataOrThrow(assetData); - let proxyAllowance: BigNumber | undefined; - if (assetDataUtils.isERC20AssetData(decodedAssetData)) { - proxyAllowance = await this._erc20Token.getProxyAllowanceAsync(decodedAssetData.tokenAddress, userAddress, { - defaultBlock: this._stateLayer, - }); - } else if (assetDataUtils.isERC721AssetData(decodedAssetData)) { - const isApprovedForAll = await this._erc721Token.isProxyApprovedForAllAsync( - decodedAssetData.tokenAddress, - userAddress, - { - defaultBlock: this._stateLayer, - }, - ); - if (isApprovedForAll) { - return new BigNumber(this._erc20Token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS); - } else { - const isApproved = await this._erc721Token.isProxyApprovedAsync( - decodedAssetData.tokenAddress, - decodedAssetData.tokenId, - { - defaultBlock: this._stateLayer, - }, - ); - proxyAllowance = isApproved ? new BigNumber(1) : new BigNumber(0); - } - } else if (assetDataUtils.isMultiAssetData(decodedAssetData)) { - // The `proxyAllowance` for MultiAssetData is the total units of the entire `assetData` that the proxies have been approved to spend by the `userAddress`. - for (const [index, nestedAssetDataElement] of decodedAssetData.nestedAssetData.entries()) { - const nestedAmountElement = decodedAssetData.amounts[index]; - const nestedAssetAllowance = (await this.getProxyAllowanceAsync( - nestedAssetDataElement, - userAddress, - )).dividedToIntegerBy(nestedAmountElement); - if (proxyAllowance === undefined || nestedAssetAllowance.isLessThan(proxyAllowance)) { - proxyAllowance = nestedAssetAllowance; - } - } - } - return proxyAllowance as BigNumber; - } -} diff --git a/packages/contract-wrappers/src/fetchers/order_filled_cancelled_fetcher.ts b/packages/contract-wrappers/src/fetchers/order_filled_cancelled_fetcher.ts deleted file mode 100644 index 5d350916cf..0000000000 --- a/packages/contract-wrappers/src/fetchers/order_filled_cancelled_fetcher.ts +++ /dev/null @@ -1,39 +0,0 @@ -// tslint:disable:no-unnecessary-type-assertion -import { AbstractOrderFilledCancelledFetcher, orderHashUtils } from '@0x/order-utils'; -import { SignedOrder } from '@0x/types'; -import { BigNumber } from '@0x/utils'; -import { BlockParamLiteral } from 'ethereum-types'; - -import { ExchangeWrapper } from '../contract_wrappers/exchange_wrapper'; - -export class OrderFilledCancelledFetcher implements AbstractOrderFilledCancelledFetcher { - private readonly _exchange: ExchangeWrapper; - private readonly _stateLayer: BlockParamLiteral; - constructor(exchange: ExchangeWrapper, stateLayer: BlockParamLiteral) { - this._exchange = exchange; - this._stateLayer = stateLayer; - } - public async getFilledTakerAmountAsync(orderHash: string): Promise { - const filledTakerAmount = this._exchange.getFilledTakerAssetAmountAsync(orderHash, { - defaultBlock: this._stateLayer, - }); - return filledTakerAmount; - } - public async isOrderCancelledAsync(signedOrder: SignedOrder): Promise { - const orderHash = orderHashUtils.getOrderHashHex(signedOrder); - const isCancelled = await this._exchange.isCancelledAsync(orderHash); - const orderEpoch = await this._exchange.getOrderEpochAsync( - signedOrder.makerAddress, - signedOrder.senderAddress, - { - defaultBlock: this._stateLayer, - }, - ); - const isCancelledByOrderEpoch = orderEpoch > signedOrder.salt; - return isCancelled || isCancelledByOrderEpoch; - } - public getZRXAssetData(): string { - const zrxAssetData = this._exchange.getZRXAssetData(); - return zrxAssetData; - } -} diff --git a/packages/contract-wrappers/src/generated-wrappers/asset_proxy_owner.ts b/packages/contract-wrappers/src/generated-wrappers/asset_proxy_owner.ts new file mode 100644 index 0000000000..4255ed3678 --- /dev/null +++ b/packages/contract-wrappers/src/generated-wrappers/asset_proxy_owner.ts @@ -0,0 +1,3984 @@ +// tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma +// tslint:disable:whitespace no-unbound-method no-trailing-whitespace +// tslint:disable:no-unused-variable +import { + BaseContract, + BlockRange, + EventCallback, + IndexedFilterValues, + SubscriptionManager, + PromiseWithTransactionHash, +} from '@0x/base-contract'; +import { schemas } from '@0x/json-schemas'; +import { + BlockParam, + BlockParamLiteral, + CallData, + ContractAbi, + ContractArtifact, + DecodedLogArgs, + LogWithDecodedArgs, + MethodAbi, + TransactionReceiptWithDecodedLogs, + TxData, + TxDataPayable, + SupportedProvider, +} from 'ethereum-types'; +import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; +import { 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 AssetProxyOwnerEventArgs = + | AssetProxyOwnerAssetProxyRegistrationEventArgs + | AssetProxyOwnerConfirmationTimeSetEventArgs + | AssetProxyOwnerTimeLockChangeEventArgs + | AssetProxyOwnerConfirmationEventArgs + | AssetProxyOwnerRevocationEventArgs + | AssetProxyOwnerSubmissionEventArgs + | AssetProxyOwnerExecutionEventArgs + | AssetProxyOwnerExecutionFailureEventArgs + | AssetProxyOwnerDepositEventArgs + | AssetProxyOwnerOwnerAdditionEventArgs + | AssetProxyOwnerOwnerRemovalEventArgs + | AssetProxyOwnerRequirementChangeEventArgs; + +export enum AssetProxyOwnerEvents { + AssetProxyRegistration = 'AssetProxyRegistration', + ConfirmationTimeSet = 'ConfirmationTimeSet', + TimeLockChange = 'TimeLockChange', + Confirmation = 'Confirmation', + Revocation = 'Revocation', + Submission = 'Submission', + Execution = 'Execution', + ExecutionFailure = 'ExecutionFailure', + Deposit = 'Deposit', + OwnerAddition = 'OwnerAddition', + OwnerRemoval = 'OwnerRemoval', + RequirementChange = 'RequirementChange', +} + +export interface AssetProxyOwnerAssetProxyRegistrationEventArgs extends DecodedLogArgs { + assetProxyContract: string; + isRegistered: boolean; +} + +export interface AssetProxyOwnerConfirmationTimeSetEventArgs extends DecodedLogArgs { + transactionId: BigNumber; + confirmationTime: BigNumber; +} + +export interface AssetProxyOwnerTimeLockChangeEventArgs extends DecodedLogArgs { + secondsTimeLocked: BigNumber; +} + +export interface AssetProxyOwnerConfirmationEventArgs extends DecodedLogArgs { + sender: string; + transactionId: BigNumber; +} + +export interface AssetProxyOwnerRevocationEventArgs extends DecodedLogArgs { + sender: string; + transactionId: BigNumber; +} + +export interface AssetProxyOwnerSubmissionEventArgs extends DecodedLogArgs { + transactionId: BigNumber; +} + +export interface AssetProxyOwnerExecutionEventArgs extends DecodedLogArgs { + transactionId: BigNumber; +} + +export interface AssetProxyOwnerExecutionFailureEventArgs extends DecodedLogArgs { + transactionId: BigNumber; +} + +export interface AssetProxyOwnerDepositEventArgs extends DecodedLogArgs { + sender: string; + value: BigNumber; +} + +export interface AssetProxyOwnerOwnerAdditionEventArgs extends DecodedLogArgs { + owner: string; +} + +export interface AssetProxyOwnerOwnerRemovalEventArgs extends DecodedLogArgs { + owner: string; +} + +export interface AssetProxyOwnerRequirementChangeEventArgs extends DecodedLogArgs { + required: BigNumber; +} + +/* istanbul ignore next */ +// tslint:disable:no-parameter-reassignment +// tslint:disable-next-line:class-name +export class AssetProxyOwnerContract extends BaseContract { + public owners = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + index_0: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isBigNumber('index_0', index_0); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('owners(uint256)', [index_0]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('owners(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(index_0: BigNumber): string { + assert.isBigNumber('index_0', index_0); + const self = (this as any) as AssetProxyOwnerContract; + const abiEncodedTransactionData = self._strictEncodeArguments('owners(uint256)', [index_0]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('owners(uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('owners(uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Allows to remove an owner. Transaction has to be sent by wallet. + */ + public removeOwner = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param owner Address of owner. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(owner: string, txData?: Partial | undefined): Promise { + assert.isString('owner', owner); + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('removeOwner(address)', [owner.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.removeOwner.estimateGasAsync.bind(self, owner.toLowerCase()), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param owner Address of owner. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + owner: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('owner', owner); + const self = (this as any) as AssetProxyOwnerContract; + const txHashPromise = self.removeOwner.sendTransactionAsync(owner.toLowerCase(), txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param owner Address of owner. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(owner: string, txData?: Partial | undefined): Promise { + assert.isString('owner', owner); + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('removeOwner(address)', [owner.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param owner Address of owner. + */ + async callAsync(owner: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.isString('owner', owner); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('removeOwner(address)', [owner.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('removeOwner(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param owner Address of owner. + */ + getABIEncodedTransactionData(owner: string): string { + assert.isString('owner', owner); + const self = (this as any) as AssetProxyOwnerContract; + const abiEncodedTransactionData = self._strictEncodeArguments('removeOwner(address)', [ + owner.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('removeOwner(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('removeOwner(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Allows an owner to revoke a confirmation for a transaction. + */ + public revokeConfirmation = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param transactionId Transaction ID. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(transactionId: BigNumber, txData?: Partial | undefined): Promise { + assert.isBigNumber('transactionId', transactionId); + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('revokeConfirmation(uint256)', [transactionId]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.revokeConfirmation.estimateGasAsync.bind(self, transactionId), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param transactionId Transaction ID. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + transactionId: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isBigNumber('transactionId', transactionId); + const self = (this as any) as AssetProxyOwnerContract; + const txHashPromise = self.revokeConfirmation.sendTransactionAsync(transactionId, txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param transactionId Transaction ID. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(transactionId: BigNumber, txData?: Partial | undefined): Promise { + assert.isBigNumber('transactionId', transactionId); + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('revokeConfirmation(uint256)', [transactionId]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param transactionId Transaction ID. + */ + async callAsync( + transactionId: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isBigNumber('transactionId', transactionId); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('revokeConfirmation(uint256)', [transactionId]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('revokeConfirmation(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param transactionId Transaction ID. + */ + getABIEncodedTransactionData(transactionId: BigNumber): string { + assert.isBigNumber('transactionId', transactionId); + const self = (this as any) as AssetProxyOwnerContract; + const abiEncodedTransactionData = self._strictEncodeArguments('revokeConfirmation(uint256)', [ + transactionId, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('revokeConfirmation(uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('revokeConfirmation(uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public isOwner = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + index_0: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('index_0', index_0); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('isOwner(address)', [index_0.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('isOwner(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(index_0: string): string { + assert.isString('index_0', index_0); + const self = (this as any) as AssetProxyOwnerContract; + const abiEncodedTransactionData = self._strictEncodeArguments('isOwner(address)', [index_0.toLowerCase()]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): boolean { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('isOwner(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): boolean { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('isOwner(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public confirmations = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + index_0: BigNumber, + index_1: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isBigNumber('index_0', index_0); + assert.isString('index_1', index_1); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('confirmations(uint256,address)', [ + index_0, + index_1.toLowerCase(), + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('confirmations(uint256,address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(index_0: BigNumber, index_1: string): string { + assert.isBigNumber('index_0', index_0); + assert.isString('index_1', index_1); + const self = (this as any) as AssetProxyOwnerContract; + const abiEncodedTransactionData = self._strictEncodeArguments('confirmations(uint256,address)', [ + index_0, + index_1.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): boolean { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('confirmations(uint256,address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): boolean { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('confirmations(uint256,address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Allows execution of `removeAuthorizedAddressAtIndex` without time lock. + */ + public executeRemoveAuthorizedAddressAtIndex = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param transactionId Transaction ID. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(transactionId: BigNumber, txData?: Partial | undefined): Promise { + assert.isBigNumber('transactionId', transactionId); + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('executeRemoveAuthorizedAddressAtIndex(uint256)', [ + transactionId, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.executeRemoveAuthorizedAddressAtIndex.estimateGasAsync.bind(self, transactionId), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param transactionId Transaction ID. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + transactionId: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isBigNumber('transactionId', transactionId); + const self = (this as any) as AssetProxyOwnerContract; + const txHashPromise = self.executeRemoveAuthorizedAddressAtIndex.sendTransactionAsync( + transactionId, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param transactionId Transaction ID. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(transactionId: BigNumber, txData?: Partial | undefined): Promise { + assert.isBigNumber('transactionId', transactionId); + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('executeRemoveAuthorizedAddressAtIndex(uint256)', [ + transactionId, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param transactionId Transaction ID. + */ + async callAsync( + transactionId: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isBigNumber('transactionId', transactionId); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('executeRemoveAuthorizedAddressAtIndex(uint256)', [ + transactionId, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('executeRemoveAuthorizedAddressAtIndex(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param transactionId Transaction ID. + */ + getABIEncodedTransactionData(transactionId: BigNumber): string { + assert.isBigNumber('transactionId', transactionId); + const self = (this as any) as AssetProxyOwnerContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'executeRemoveAuthorizedAddressAtIndex(uint256)', + [transactionId], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('executeRemoveAuthorizedAddressAtIndex(uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('executeRemoveAuthorizedAddressAtIndex(uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public secondsTimeLocked = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('secondsTimeLocked()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('secondsTimeLocked()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncodedTransactionData = self._strictEncodeArguments('secondsTimeLocked()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): BigNumber { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('secondsTimeLocked()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): BigNumber { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('secondsTimeLocked()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Returns total number of transactions after filers are applied. + */ + public getTransactionCount = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param pending Include pending transactions. + * @param executed Include executed transactions. + * @returns Total number of transactions after filters are applied. + */ + async callAsync( + pending: boolean, + executed: boolean, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isBoolean('pending', pending); + assert.isBoolean('executed', executed); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('getTransactionCount(bool,bool)', [pending, executed]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getTransactionCount(bool,bool)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param pending Include pending transactions. + * @param executed Include executed transactions. + */ + getABIEncodedTransactionData(pending: boolean, executed: boolean): string { + assert.isBoolean('pending', pending); + assert.isBoolean('executed', executed); + const self = (this as any) as AssetProxyOwnerContract; + const abiEncodedTransactionData = self._strictEncodeArguments('getTransactionCount(bool,bool)', [ + pending, + executed, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): BigNumber { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('getTransactionCount(bool,bool)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): BigNumber { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('getTransactionCount(bool,bool)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Registers or deregisters an AssetProxy to be able to execute + * `removeAuthorizedAddressAtIndex` without a timelock. + */ + public registerAssetProxy = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param assetProxyContract Address of AssetProxy contract. + * @param isRegistered Status of approval for AssetProxy contract. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + assetProxyContract: string, + isRegistered: boolean, + txData?: Partial | undefined, + ): Promise { + assert.isString('assetProxyContract', assetProxyContract); + assert.isBoolean('isRegistered', isRegistered); + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('registerAssetProxy(address,bool)', [ + assetProxyContract.toLowerCase(), + isRegistered, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.registerAssetProxy.estimateGasAsync.bind(self, assetProxyContract.toLowerCase(), isRegistered), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param assetProxyContract Address of AssetProxy contract. + * @param isRegistered Status of approval for AssetProxy contract. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + assetProxyContract: string, + isRegistered: boolean, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('assetProxyContract', assetProxyContract); + assert.isBoolean('isRegistered', isRegistered); + const self = (this as any) as AssetProxyOwnerContract; + const txHashPromise = self.registerAssetProxy.sendTransactionAsync( + assetProxyContract.toLowerCase(), + isRegistered, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param assetProxyContract Address of AssetProxy contract. + * @param isRegistered Status of approval for AssetProxy contract. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + assetProxyContract: string, + isRegistered: boolean, + txData?: Partial | undefined, + ): Promise { + assert.isString('assetProxyContract', assetProxyContract); + assert.isBoolean('isRegistered', isRegistered); + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('registerAssetProxy(address,bool)', [ + assetProxyContract.toLowerCase(), + isRegistered, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param assetProxyContract Address of AssetProxy contract. + * @param isRegistered Status of approval for AssetProxy contract. + */ + async callAsync( + assetProxyContract: string, + isRegistered: boolean, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('assetProxyContract', assetProxyContract); + assert.isBoolean('isRegistered', isRegistered); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('registerAssetProxy(address,bool)', [ + assetProxyContract.toLowerCase(), + isRegistered, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('registerAssetProxy(address,bool)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param assetProxyContract Address of AssetProxy contract. + * @param isRegistered Status of approval for AssetProxy contract. + */ + getABIEncodedTransactionData(assetProxyContract: string, isRegistered: boolean): string { + assert.isString('assetProxyContract', assetProxyContract); + assert.isBoolean('isRegistered', isRegistered); + const self = (this as any) as AssetProxyOwnerContract; + const abiEncodedTransactionData = self._strictEncodeArguments('registerAssetProxy(address,bool)', [ + assetProxyContract.toLowerCase(), + isRegistered, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('registerAssetProxy(address,bool)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('registerAssetProxy(address,bool)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Allows to add a new owner. Transaction has to be sent by wallet. + */ + public addOwner = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param owner Address of new owner. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(owner: string, txData?: Partial | undefined): Promise { + assert.isString('owner', owner); + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('addOwner(address)', [owner.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.addOwner.estimateGasAsync.bind(self, owner.toLowerCase()), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param owner Address of new owner. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + owner: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('owner', owner); + const self = (this as any) as AssetProxyOwnerContract; + const txHashPromise = self.addOwner.sendTransactionAsync(owner.toLowerCase(), txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param owner Address of new owner. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(owner: string, txData?: Partial | undefined): Promise { + assert.isString('owner', owner); + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('addOwner(address)', [owner.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param owner Address of new owner. + */ + async callAsync(owner: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.isString('owner', owner); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('addOwner(address)', [owner.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('addOwner(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param owner Address of new owner. + */ + getABIEncodedTransactionData(owner: string): string { + assert.isString('owner', owner); + const self = (this as any) as AssetProxyOwnerContract; + const abiEncodedTransactionData = self._strictEncodeArguments('addOwner(address)', [owner.toLowerCase()]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('addOwner(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('addOwner(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Returns the confirmation status of a transaction. + */ + public isConfirmed = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param transactionId Transaction ID. + * @returns Confirmation status. + */ + async callAsync( + transactionId: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isBigNumber('transactionId', transactionId); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('isConfirmed(uint256)', [transactionId]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('isConfirmed(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param transactionId Transaction ID. + */ + getABIEncodedTransactionData(transactionId: BigNumber): string { + assert.isBigNumber('transactionId', transactionId); + const self = (this as any) as AssetProxyOwnerContract; + const abiEncodedTransactionData = self._strictEncodeArguments('isConfirmed(uint256)', [transactionId]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): boolean { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('isConfirmed(uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): boolean { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('isConfirmed(uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Changes the duration of the time lock for transactions. + */ + public changeTimeLock = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param _secondsTimeLocked Duration needed after a transaction is confirmed + * and before it becomes executable, in seconds. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + _secondsTimeLocked: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isBigNumber('_secondsTimeLocked', _secondsTimeLocked); + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('changeTimeLock(uint256)', [_secondsTimeLocked]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.changeTimeLock.estimateGasAsync.bind(self, _secondsTimeLocked), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param _secondsTimeLocked Duration needed after a transaction is confirmed + * and before it becomes executable, in seconds. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + _secondsTimeLocked: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isBigNumber('_secondsTimeLocked', _secondsTimeLocked); + const self = (this as any) as AssetProxyOwnerContract; + const txHashPromise = self.changeTimeLock.sendTransactionAsync(_secondsTimeLocked, txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param _secondsTimeLocked Duration needed after a transaction is confirmed + * and before it becomes executable, in seconds. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(_secondsTimeLocked: BigNumber, txData?: Partial | undefined): Promise { + assert.isBigNumber('_secondsTimeLocked', _secondsTimeLocked); + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('changeTimeLock(uint256)', [_secondsTimeLocked]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _secondsTimeLocked Duration needed after a transaction is confirmed + * and before it becomes executable, in seconds. + */ + async callAsync( + _secondsTimeLocked: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isBigNumber('_secondsTimeLocked', _secondsTimeLocked); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('changeTimeLock(uint256)', [_secondsTimeLocked]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('changeTimeLock(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _secondsTimeLocked Duration needed after a transaction is confirmed + * and before it becomes executable, in seconds. + */ + getABIEncodedTransactionData(_secondsTimeLocked: BigNumber): string { + assert.isBigNumber('_secondsTimeLocked', _secondsTimeLocked); + const self = (this as any) as AssetProxyOwnerContract; + const abiEncodedTransactionData = self._strictEncodeArguments('changeTimeLock(uint256)', [ + _secondsTimeLocked, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('changeTimeLock(uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('changeTimeLock(uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public isAssetProxyRegistered = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + index_0: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('index_0', index_0); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('isAssetProxyRegistered(address)', [index_0.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('isAssetProxyRegistered(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(index_0: string): string { + assert.isString('index_0', index_0); + const self = (this as any) as AssetProxyOwnerContract; + const abiEncodedTransactionData = self._strictEncodeArguments('isAssetProxyRegistered(address)', [ + index_0.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): boolean { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('isAssetProxyRegistered(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): boolean { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('isAssetProxyRegistered(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Returns number of confirmations of a transaction. + */ + public getConfirmationCount = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param transactionId Transaction ID. + * @returns Number of confirmations. + */ + async callAsync( + transactionId: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isBigNumber('transactionId', transactionId); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('getConfirmationCount(uint256)', [transactionId]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getConfirmationCount(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param transactionId Transaction ID. + */ + getABIEncodedTransactionData(transactionId: BigNumber): string { + assert.isBigNumber('transactionId', transactionId); + const self = (this as any) as AssetProxyOwnerContract; + const abiEncodedTransactionData = self._strictEncodeArguments('getConfirmationCount(uint256)', [ + transactionId, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): BigNumber { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('getConfirmationCount(uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): BigNumber { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('getConfirmationCount(uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public transactions = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + index_0: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<[string, BigNumber, string, boolean]> { + assert.isBigNumber('index_0', index_0); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('transactions(uint256)', [index_0]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transactions(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[string, BigNumber, string, boolean]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(index_0: BigNumber): string { + assert.isBigNumber('index_0', index_0); + const self = (this as any) as AssetProxyOwnerContract; + const abiEncodedTransactionData = self._strictEncodeArguments('transactions(uint256)', [index_0]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): [string, BigNumber, string, boolean] { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('transactions(uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode<[string, BigNumber, string, boolean]>(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): [string, BigNumber, string, boolean] { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('transactions(uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue<[string, BigNumber, string, boolean]>( + returnData, + ); + return abiDecodedReturnData; + }, + }; + /** + * Returns list of owners. + */ + public getOwners = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @returns List of owner addresses. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('getOwners()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getOwners()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncodedTransactionData = self._strictEncodeArguments('getOwners()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string[] { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('getOwners()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string[] { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('getOwners()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Returns list of transaction IDs in defined range. + */ + public getTransactionIds = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param from Index start position of transaction array. + * @param to Index end position of transaction array. + * @param pending Include pending transactions. + * @param executed Include executed transactions. + * @returns Returns array of transaction IDs. + */ + async callAsync( + from: BigNumber, + to: BigNumber, + pending: boolean, + executed: boolean, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isBigNumber('from', from); + assert.isBigNumber('to', to); + assert.isBoolean('pending', pending); + assert.isBoolean('executed', executed); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('getTransactionIds(uint256,uint256,bool,bool)', [ + from, + to, + pending, + executed, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getTransactionIds(uint256,uint256,bool,bool)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param from Index start position of transaction array. + * @param to Index end position of transaction array. + * @param pending Include pending transactions. + * @param executed Include executed transactions. + */ + getABIEncodedTransactionData(from: BigNumber, to: BigNumber, pending: boolean, executed: boolean): string { + assert.isBigNumber('from', from); + assert.isBigNumber('to', to); + assert.isBoolean('pending', pending); + assert.isBoolean('executed', executed); + const self = (this as any) as AssetProxyOwnerContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'getTransactionIds(uint256,uint256,bool,bool)', + [from, to, pending, executed], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): BigNumber[] { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('getTransactionIds(uint256,uint256,bool,bool)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): BigNumber[] { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('getTransactionIds(uint256,uint256,bool,bool)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Returns array with owner addresses, which confirmed transaction. + */ + public getConfirmations = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param transactionId Transaction ID. + * @returns Returns array of owner addresses. + */ + async callAsync( + transactionId: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isBigNumber('transactionId', transactionId); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('getConfirmations(uint256)', [transactionId]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getConfirmations(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param transactionId Transaction ID. + */ + getABIEncodedTransactionData(transactionId: BigNumber): string { + assert.isBigNumber('transactionId', transactionId); + const self = (this as any) as AssetProxyOwnerContract; + const abiEncodedTransactionData = self._strictEncodeArguments('getConfirmations(uint256)', [transactionId]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string[] { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('getConfirmations(uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string[] { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('getConfirmations(uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public transactionCount = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('transactionCount()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transactionCount()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncodedTransactionData = self._strictEncodeArguments('transactionCount()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): BigNumber { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('transactionCount()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): BigNumber { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('transactionCount()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Allows to change the number of required confirmations. Transaction has to be sent by wallet. + */ + public changeRequirement = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param _required Number of required confirmations. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(_required: BigNumber, txData?: Partial | undefined): Promise { + assert.isBigNumber('_required', _required); + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('changeRequirement(uint256)', [_required]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.changeRequirement.estimateGasAsync.bind(self, _required), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param _required Number of required confirmations. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + _required: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isBigNumber('_required', _required); + const self = (this as any) as AssetProxyOwnerContract; + const txHashPromise = self.changeRequirement.sendTransactionAsync(_required, txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param _required Number of required confirmations. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(_required: BigNumber, txData?: Partial | undefined): Promise { + assert.isBigNumber('_required', _required); + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('changeRequirement(uint256)', [_required]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _required Number of required confirmations. + */ + async callAsync( + _required: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isBigNumber('_required', _required); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('changeRequirement(uint256)', [_required]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('changeRequirement(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _required Number of required confirmations. + */ + getABIEncodedTransactionData(_required: BigNumber): string { + assert.isBigNumber('_required', _required); + const self = (this as any) as AssetProxyOwnerContract; + const abiEncodedTransactionData = self._strictEncodeArguments('changeRequirement(uint256)', [_required]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('changeRequirement(uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('changeRequirement(uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Allows an owner to confirm a transaction. + */ + public confirmTransaction = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param transactionId Transaction ID. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(transactionId: BigNumber, txData?: Partial | undefined): Promise { + assert.isBigNumber('transactionId', transactionId); + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('confirmTransaction(uint256)', [transactionId]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.confirmTransaction.estimateGasAsync.bind(self, transactionId), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param transactionId Transaction ID. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + transactionId: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isBigNumber('transactionId', transactionId); + const self = (this as any) as AssetProxyOwnerContract; + const txHashPromise = self.confirmTransaction.sendTransactionAsync(transactionId, txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param transactionId Transaction ID. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(transactionId: BigNumber, txData?: Partial | undefined): Promise { + assert.isBigNumber('transactionId', transactionId); + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('confirmTransaction(uint256)', [transactionId]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param transactionId Transaction ID. + */ + async callAsync( + transactionId: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isBigNumber('transactionId', transactionId); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('confirmTransaction(uint256)', [transactionId]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('confirmTransaction(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param transactionId Transaction ID. + */ + getABIEncodedTransactionData(transactionId: BigNumber): string { + assert.isBigNumber('transactionId', transactionId); + const self = (this as any) as AssetProxyOwnerContract; + const abiEncodedTransactionData = self._strictEncodeArguments('confirmTransaction(uint256)', [ + transactionId, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('confirmTransaction(uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('confirmTransaction(uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Allows an owner to submit and confirm a transaction. + */ + public submitTransaction = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param destination Transaction target address. + * @param value Transaction ether value. + * @param data Transaction data payload. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + destination: string, + value: BigNumber, + data: string, + txData?: Partial | undefined, + ): Promise { + assert.isString('destination', destination); + assert.isBigNumber('value', value); + assert.isString('data', data); + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('submitTransaction(address,uint256,bytes)', [ + destination.toLowerCase(), + value, + data, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.submitTransaction.estimateGasAsync.bind(self, destination.toLowerCase(), value, data), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param destination Transaction target address. + * @param value Transaction ether value. + * @param data Transaction data payload. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + destination: string, + value: BigNumber, + data: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('destination', destination); + assert.isBigNumber('value', value); + assert.isString('data', data); + const self = (this as any) as AssetProxyOwnerContract; + const txHashPromise = self.submitTransaction.sendTransactionAsync( + destination.toLowerCase(), + value, + data, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param destination Transaction target address. + * @param value Transaction ether value. + * @param data Transaction data payload. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + destination: string, + value: BigNumber, + data: string, + txData?: Partial | undefined, + ): Promise { + assert.isString('destination', destination); + assert.isBigNumber('value', value); + assert.isString('data', data); + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('submitTransaction(address,uint256,bytes)', [ + destination.toLowerCase(), + value, + data, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param destination Transaction target address. + * @param value Transaction ether value. + * @param data Transaction data payload. + * @returns Returns transaction ID. + */ + async callAsync( + destination: string, + value: BigNumber, + data: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('destination', destination); + assert.isBigNumber('value', value); + assert.isString('data', data); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('submitTransaction(address,uint256,bytes)', [ + destination.toLowerCase(), + value, + data, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('submitTransaction(address,uint256,bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param destination Transaction target address. + * @param value Transaction ether value. + * @param data Transaction data payload. + */ + getABIEncodedTransactionData(destination: string, value: BigNumber, data: string): string { + assert.isString('destination', destination); + assert.isBigNumber('value', value); + assert.isString('data', data); + const self = (this as any) as AssetProxyOwnerContract; + const abiEncodedTransactionData = self._strictEncodeArguments('submitTransaction(address,uint256,bytes)', [ + destination.toLowerCase(), + value, + data, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): BigNumber { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('submitTransaction(address,uint256,bytes)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): BigNumber { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('submitTransaction(address,uint256,bytes)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public confirmationTimes = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + index_0: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isBigNumber('index_0', index_0); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('confirmationTimes(uint256)', [index_0]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('confirmationTimes(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(index_0: BigNumber): string { + assert.isBigNumber('index_0', index_0); + const self = (this as any) as AssetProxyOwnerContract; + const abiEncodedTransactionData = self._strictEncodeArguments('confirmationTimes(uint256)', [index_0]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): BigNumber { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('confirmationTimes(uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): BigNumber { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('confirmationTimes(uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public MAX_OWNER_COUNT = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('MAX_OWNER_COUNT()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('MAX_OWNER_COUNT()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncodedTransactionData = self._strictEncodeArguments('MAX_OWNER_COUNT()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): BigNumber { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('MAX_OWNER_COUNT()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): BigNumber { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('MAX_OWNER_COUNT()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public required = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('required()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('required()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncodedTransactionData = self._strictEncodeArguments('required()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): BigNumber { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('required()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): BigNumber { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('required()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Allows to replace an owner with a new owner. Transaction has to be sent by wallet. + */ + public replaceOwner = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param owner Address of owner to be replaced. + * @param newOwner Address of new owner. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + owner: string, + newOwner: string, + txData?: Partial | undefined, + ): Promise { + assert.isString('owner', owner); + assert.isString('newOwner', newOwner); + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('replaceOwner(address,address)', [ + owner.toLowerCase(), + newOwner.toLowerCase(), + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.replaceOwner.estimateGasAsync.bind(self, owner.toLowerCase(), newOwner.toLowerCase()), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param owner Address of owner to be replaced. + * @param newOwner Address of new owner. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + owner: string, + newOwner: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('owner', owner); + assert.isString('newOwner', newOwner); + const self = (this as any) as AssetProxyOwnerContract; + const txHashPromise = self.replaceOwner.sendTransactionAsync( + owner.toLowerCase(), + newOwner.toLowerCase(), + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param owner Address of owner to be replaced. + * @param newOwner Address of new owner. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(owner: string, newOwner: string, txData?: Partial | undefined): Promise { + assert.isString('owner', owner); + assert.isString('newOwner', newOwner); + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('replaceOwner(address,address)', [ + owner.toLowerCase(), + newOwner.toLowerCase(), + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param owner Address of owner to be replaced. + * @param newOwner Address of new owner. + */ + async callAsync( + owner: string, + newOwner: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('owner', owner); + assert.isString('newOwner', newOwner); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('replaceOwner(address,address)', [ + owner.toLowerCase(), + newOwner.toLowerCase(), + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('replaceOwner(address,address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param owner Address of owner to be replaced. + * @param newOwner Address of new owner. + */ + getABIEncodedTransactionData(owner: string, newOwner: string): string { + assert.isString('owner', owner); + assert.isString('newOwner', newOwner); + const self = (this as any) as AssetProxyOwnerContract; + const abiEncodedTransactionData = self._strictEncodeArguments('replaceOwner(address,address)', [ + owner.toLowerCase(), + newOwner.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('replaceOwner(address,address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('replaceOwner(address,address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Allows anyone to execute a confirmed transaction. + */ + public executeTransaction = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param transactionId Transaction ID. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(transactionId: BigNumber, txData?: Partial | undefined): Promise { + assert.isBigNumber('transactionId', transactionId); + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('executeTransaction(uint256)', [transactionId]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.executeTransaction.estimateGasAsync.bind(self, transactionId), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param transactionId Transaction ID. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + transactionId: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isBigNumber('transactionId', transactionId); + const self = (this as any) as AssetProxyOwnerContract; + const txHashPromise = self.executeTransaction.sendTransactionAsync(transactionId, txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param transactionId Transaction ID. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(transactionId: BigNumber, txData?: Partial | undefined): Promise { + assert.isBigNumber('transactionId', transactionId); + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('executeTransaction(uint256)', [transactionId]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param transactionId Transaction ID. + */ + async callAsync( + transactionId: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isBigNumber('transactionId', transactionId); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as AssetProxyOwnerContract; + const encodedData = self._strictEncodeArguments('executeTransaction(uint256)', [transactionId]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('executeTransaction(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param transactionId Transaction ID. + */ + getABIEncodedTransactionData(transactionId: BigNumber): string { + assert.isBigNumber('transactionId', transactionId); + const self = (this as any) as AssetProxyOwnerContract; + const abiEncodedTransactionData = self._strictEncodeArguments('executeTransaction(uint256)', [ + transactionId, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('executeTransaction(uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as AssetProxyOwnerContract; + const abiEncoder = self._lookupAbiEncoder('executeTransaction(uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + private readonly _subscriptionManager: SubscriptionManager; + public static async deployFrom0xArtifactAsync( + artifact: ContractArtifact | SimpleContractArtifact, + supportedProvider: SupportedProvider, + txDefaults: Partial, + logDecodeDependencies: { [contractName: string]: ContractArtifact | SimpleContractArtifact }, + _owners: string[], + _assetProxyContracts: string[], + _required: BigNumber, + _secondsTimeLocked: BigNumber, + ): 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 AssetProxyOwnerContract.deployAsync( + bytecode, + abi, + provider, + txDefaults, + logDecodeDependenciesAbiOnly, + _owners, + _assetProxyContracts, + _required, + _secondsTimeLocked, + ); + } + public static async deployAsync( + bytecode: string, + abi: ContractAbi, + supportedProvider: SupportedProvider, + txDefaults: Partial, + logDecodeDependencies: { [contractName: string]: ContractAbi }, + _owners: string[], + _assetProxyContracts: string[], + _required: BigNumber, + _secondsTimeLocked: BigNumber, + ): 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); + [_owners, _assetProxyContracts, _required, _secondsTimeLocked] = BaseContract._formatABIDataItemList( + constructorAbi.inputs, + [_owners, _assetProxyContracts, _required, _secondsTimeLocked], + BaseContract._bigNumberToString, + ); + const iface = new ethers.utils.Interface(abi); + const deployInfo = iface.deployFunction; + const txData = deployInfo.encode(bytecode, [_owners, _assetProxyContracts, _required, _secondsTimeLocked]); + const web3Wrapper = new Web3Wrapper(provider); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { 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(`AssetProxyOwner successfully deployed at ${txReceipt.contractAddress}`); + const contractInstance = new AssetProxyOwnerContract( + txReceipt.contractAddress as string, + provider, + txDefaults, + logDecodeDependencies, + ); + contractInstance.constructorArgs = [_owners, _assetProxyContracts, _required, _secondsTimeLocked]; + return contractInstance; + } + + /** + * @returns The contract ABI + */ + public static ABI(): ContractAbi { + const abi = [ + { + constant: true, + inputs: [ + { + name: 'index_0', + type: 'uint256', + }, + ], + name: 'owners', + outputs: [ + { + name: '', + type: 'address', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'owner', + type: 'address', + }, + ], + name: 'removeOwner', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'transactionId', + type: 'uint256', + }, + ], + name: 'revokeConfirmation', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'index_0', + type: 'address', + }, + ], + name: 'isOwner', + outputs: [ + { + name: '', + type: 'bool', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'index_0', + type: 'uint256', + }, + { + name: 'index_1', + type: 'address', + }, + ], + name: 'confirmations', + outputs: [ + { + name: '', + type: 'bool', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'transactionId', + type: 'uint256', + }, + ], + name: 'executeRemoveAuthorizedAddressAtIndex', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'secondsTimeLocked', + outputs: [ + { + name: '', + type: 'uint256', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'pending', + type: 'bool', + }, + { + name: 'executed', + type: 'bool', + }, + ], + name: 'getTransactionCount', + outputs: [ + { + name: 'count', + type: 'uint256', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'assetProxyContract', + type: 'address', + }, + { + name: 'isRegistered', + type: 'bool', + }, + ], + name: 'registerAssetProxy', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'owner', + type: 'address', + }, + ], + name: 'addOwner', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'transactionId', + type: 'uint256', + }, + ], + name: 'isConfirmed', + outputs: [ + { + name: '', + type: 'bool', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: '_secondsTimeLocked', + type: 'uint256', + }, + ], + name: 'changeTimeLock', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'index_0', + type: 'address', + }, + ], + name: 'isAssetProxyRegistered', + outputs: [ + { + name: '', + type: 'bool', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'transactionId', + type: 'uint256', + }, + ], + name: 'getConfirmationCount', + outputs: [ + { + name: 'count', + type: 'uint256', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'index_0', + type: 'uint256', + }, + ], + name: 'transactions', + outputs: [ + { + name: 'destination', + type: 'address', + }, + { + name: 'value', + type: 'uint256', + }, + { + name: 'data', + type: 'bytes', + }, + { + name: 'executed', + type: 'bool', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'getOwners', + outputs: [ + { + name: '', + type: 'address[]', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'from', + type: 'uint256', + }, + { + name: 'to', + type: 'uint256', + }, + { + name: 'pending', + type: 'bool', + }, + { + name: 'executed', + type: 'bool', + }, + ], + name: 'getTransactionIds', + outputs: [ + { + name: '_transactionIds', + type: 'uint256[]', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'transactionId', + type: 'uint256', + }, + ], + name: 'getConfirmations', + outputs: [ + { + name: '_confirmations', + type: 'address[]', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'transactionCount', + outputs: [ + { + name: '', + type: 'uint256', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: '_required', + type: 'uint256', + }, + ], + name: 'changeRequirement', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'transactionId', + type: 'uint256', + }, + ], + name: 'confirmTransaction', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'destination', + type: 'address', + }, + { + name: 'value', + type: 'uint256', + }, + { + name: 'data', + type: 'bytes', + }, + ], + name: 'submitTransaction', + outputs: [ + { + name: 'transactionId', + type: 'uint256', + }, + ], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'index_0', + type: 'uint256', + }, + ], + name: 'confirmationTimes', + outputs: [ + { + name: '', + type: 'uint256', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'MAX_OWNER_COUNT', + outputs: [ + { + name: '', + type: 'uint256', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'required', + outputs: [ + { + name: '', + type: 'uint256', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'owner', + type: 'address', + }, + { + name: 'newOwner', + type: 'address', + }, + ], + name: 'replaceOwner', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'transactionId', + type: 'uint256', + }, + ], + name: 'executeTransaction', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + inputs: [ + { + name: '_owners', + type: 'address[]', + }, + { + name: '_assetProxyContracts', + type: 'address[]', + }, + { + name: '_required', + type: 'uint256', + }, + { + name: '_secondsTimeLocked', + type: 'uint256', + }, + ], + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'constructor', + }, + { + inputs: [], + outputs: [], + payable: true, + stateMutability: 'payable', + type: 'fallback', + }, + { + anonymous: false, + inputs: [ + { + name: 'assetProxyContract', + type: 'address', + indexed: false, + }, + { + name: 'isRegistered', + type: 'bool', + indexed: false, + }, + ], + name: 'AssetProxyRegistration', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: 'transactionId', + type: 'uint256', + indexed: true, + }, + { + name: 'confirmationTime', + type: 'uint256', + indexed: false, + }, + ], + name: 'ConfirmationTimeSet', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: 'secondsTimeLocked', + type: 'uint256', + indexed: false, + }, + ], + name: 'TimeLockChange', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: 'sender', + type: 'address', + indexed: true, + }, + { + name: 'transactionId', + type: 'uint256', + indexed: true, + }, + ], + name: 'Confirmation', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: 'sender', + type: 'address', + indexed: true, + }, + { + name: 'transactionId', + type: 'uint256', + indexed: true, + }, + ], + name: 'Revocation', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: 'transactionId', + type: 'uint256', + indexed: true, + }, + ], + name: 'Submission', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: 'transactionId', + type: 'uint256', + indexed: true, + }, + ], + name: 'Execution', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: 'transactionId', + type: 'uint256', + indexed: true, + }, + ], + name: 'ExecutionFailure', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: 'sender', + type: 'address', + indexed: true, + }, + { + name: 'value', + type: 'uint256', + indexed: false, + }, + ], + name: 'Deposit', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: 'owner', + type: 'address', + indexed: true, + }, + ], + name: 'OwnerAddition', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: 'owner', + type: 'address', + indexed: true, + }, + ], + name: 'OwnerRemoval', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: 'required', + type: 'uint256', + indexed: false, + }, + ], + name: 'RequirementChange', + outputs: [], + type: 'event', + }, + ] as ContractAbi; + return abi; + } + /** + * Subscribe to an event type emitted by the AssetProxyOwner contract. + * @param eventName The AssetProxyOwner 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: AssetProxyOwnerEvents, + indexFilterValues: IndexedFilterValues, + callback: EventCallback, + isVerbose: boolean = false, + blockPollingIntervalMs?: number, + ): string { + assert.doesBelongToStringEnum('eventName', eventName, AssetProxyOwnerEvents); + assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); + assert.isFunction('callback', callback); + const subscriptionToken = this._subscriptionManager.subscribe( + this.address, + eventName, + indexFilterValues, + AssetProxyOwnerContract.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 AssetProxyOwner 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: AssetProxyOwnerEvents, + blockRange: BlockRange, + indexFilterValues: IndexedFilterValues, + ): Promise>> { + assert.doesBelongToStringEnum('eventName', eventName, AssetProxyOwnerEvents); + assert.doesConformToSchema('blockRange', blockRange, schemas.blockRangeSchema); + assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); + const logs = await this._subscriptionManager.getLogsAsync( + this.address, + eventName, + blockRange, + indexFilterValues, + AssetProxyOwnerContract.ABI(), + ); + return logs; + } + constructor( + address: string, + supportedProvider: SupportedProvider, + txDefaults?: Partial, + logDecodeDependencies?: { [contractName: string]: ContractAbi }, + ) { + super( + 'AssetProxyOwner', + AssetProxyOwnerContract.ABI(), + address, + supportedProvider, + txDefaults, + logDecodeDependencies, + ); + classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + this._subscriptionManager = new SubscriptionManager( + AssetProxyOwnerContract.ABI(), + this._web3Wrapper, + ); + } +} + +// 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/contract-wrappers/src/generated-wrappers/coordinator.ts b/packages/contract-wrappers/src/generated-wrappers/coordinator.ts new file mode 100644 index 0000000000..13d6bcff1d --- /dev/null +++ b/packages/contract-wrappers/src/generated-wrappers/coordinator.ts @@ -0,0 +1,1377 @@ +// tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma +// tslint:disable:whitespace no-unbound-method no-trailing-whitespace +// tslint:disable:no-unused-variable +import { BaseContract, PromiseWithTransactionHash } from '@0x/base-contract'; +import { schemas } from '@0x/json-schemas'; +import { + BlockParam, + BlockParamLiteral, + CallData, + ContractAbi, + ContractArtifact, + DecodedLogArgs, + MethodAbi, + TransactionReceiptWithDecodedLogs, + TxData, + TxDataPayable, + SupportedProvider, +} from 'ethereum-types'; +import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; +import { 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:no-parameter-reassignment +// tslint:disable-next-line:class-name +export class CoordinatorContract extends BaseContract { + /** + * Recovers the address of a signer given a hash and signature. + */ + public getSignerAddress = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param hash Any 32 byte hash. + * @param signature Proof that the hash has been signed by signer. + */ + async callAsync( + hash: string, + signature: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('hash', hash); + assert.isString('signature', signature); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as CoordinatorContract; + const encodedData = self._strictEncodeArguments('getSignerAddress(bytes32,bytes)', [hash, signature]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getSignerAddress(bytes32,bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param hash Any 32 byte hash. + * @param signature Proof that the hash has been signed by signer. + */ + getABIEncodedTransactionData(hash: string, signature: string): string { + assert.isString('hash', hash); + assert.isString('signature', signature); + const self = (this as any) as CoordinatorContract; + const abiEncodedTransactionData = self._strictEncodeArguments('getSignerAddress(bytes32,bytes)', [ + hash, + signature, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as CoordinatorContract; + const abiEncoder = self._lookupAbiEncoder('getSignerAddress(bytes32,bytes)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as CoordinatorContract; + const abiEncoder = self._lookupAbiEncoder('getSignerAddress(bytes32,bytes)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Calculates the EIP712 hash of a 0x transaction using the domain separator of the Exchange contract. + */ + public getTransactionHash = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param transaction 0x transaction containing salt, signerAddress, and data. + * @returns EIP712 hash of the transaction with the domain separator of this contract. + */ + async callAsync( + transaction: { salt: BigNumber; signerAddress: string; data: string }, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as CoordinatorContract; + const encodedData = self._strictEncodeArguments('getTransactionHash((uint256,address,bytes))', [ + transaction, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getTransactionHash((uint256,address,bytes))'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param transaction 0x transaction containing salt, signerAddress, and data. + */ + getABIEncodedTransactionData(transaction: { salt: BigNumber; signerAddress: string; data: string }): string { + const self = (this as any) as CoordinatorContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'getTransactionHash((uint256,address,bytes))', + [transaction], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as CoordinatorContract; + const abiEncoder = self._lookupAbiEncoder('getTransactionHash((uint256,address,bytes))'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as CoordinatorContract; + const abiEncoder = self._lookupAbiEncoder('getTransactionHash((uint256,address,bytes))'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Calculated the EIP712 hash of the Coordinator approval mesasage using the domain separator of this contract. + */ + public getCoordinatorApprovalHash = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param approval Coordinator approval message containing the transaction + * hash, transaction signature, and expiration of the approval. + * @returns EIP712 hash of the Coordinator approval message with the domain separator of this contract. + */ + async callAsync( + approval: { + txOrigin: string; + transactionHash: string; + transactionSignature: string; + approvalExpirationTimeSeconds: BigNumber; + }, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as CoordinatorContract; + const encodedData = self._strictEncodeArguments( + 'getCoordinatorApprovalHash((address,bytes32,bytes,uint256))', + [approval], + ); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getCoordinatorApprovalHash((address,bytes32,bytes,uint256))'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param approval Coordinator approval message containing the transaction + * hash, transaction signature, and expiration of the approval. + */ + getABIEncodedTransactionData(approval: { + txOrigin: string; + transactionHash: string; + transactionSignature: string; + approvalExpirationTimeSeconds: BigNumber; + }): string { + const self = (this as any) as CoordinatorContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'getCoordinatorApprovalHash((address,bytes32,bytes,uint256))', + [approval], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as CoordinatorContract; + const abiEncoder = self._lookupAbiEncoder('getCoordinatorApprovalHash((address,bytes32,bytes,uint256))'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as CoordinatorContract; + const abiEncoder = self._lookupAbiEncoder('getCoordinatorApprovalHash((address,bytes32,bytes,uint256))'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Executes a 0x transaction that has been signed by the feeRecipients that correspond to each order in the transaction's Exchange calldata. + */ + public executeTransaction = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param transaction 0x transaction containing salt, signerAddress, and data. + * @param txOrigin Required signer of Ethereum transaction calling this + * function. + * @param transactionSignature Proof that the transaction has been signed by + * the signer. + * @param approvalExpirationTimeSeconds Array of expiration times in seconds + * for which each corresponding approval signature expires. + * @param approvalSignatures Array of signatures that correspond to the + * feeRecipients of each order in the transaction's Exchange calldata. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + transaction: { salt: BigNumber; signerAddress: string; data: string }, + txOrigin: string, + transactionSignature: string, + approvalExpirationTimeSeconds: BigNumber[], + approvalSignatures: string[], + txData?: Partial | undefined, + ): Promise { + assert.isString('txOrigin', txOrigin); + assert.isString('transactionSignature', transactionSignature); + assert.isArray('approvalExpirationTimeSeconds', approvalExpirationTimeSeconds); + assert.isArray('approvalSignatures', approvalSignatures); + const self = (this as any) as CoordinatorContract; + const encodedData = self._strictEncodeArguments( + 'executeTransaction((uint256,address,bytes),address,bytes,uint256[],bytes[])', + [ + transaction, + txOrigin.toLowerCase(), + transactionSignature, + approvalExpirationTimeSeconds, + approvalSignatures, + ], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.executeTransaction.estimateGasAsync.bind( + self, + transaction, + txOrigin.toLowerCase(), + transactionSignature, + approvalExpirationTimeSeconds, + approvalSignatures, + ), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param transaction 0x transaction containing salt, signerAddress, and data. + * @param txOrigin Required signer of Ethereum transaction calling this + * function. + * @param transactionSignature Proof that the transaction has been signed by + * the signer. + * @param approvalExpirationTimeSeconds Array of expiration times in seconds + * for which each corresponding approval signature expires. + * @param approvalSignatures Array of signatures that correspond to the + * feeRecipients of each order in the transaction's Exchange calldata. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + transaction: { salt: BigNumber; signerAddress: string; data: string }, + txOrigin: string, + transactionSignature: string, + approvalExpirationTimeSeconds: BigNumber[], + approvalSignatures: string[], + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('txOrigin', txOrigin); + assert.isString('transactionSignature', transactionSignature); + assert.isArray('approvalExpirationTimeSeconds', approvalExpirationTimeSeconds); + assert.isArray('approvalSignatures', approvalSignatures); + const self = (this as any) as CoordinatorContract; + const txHashPromise = self.executeTransaction.sendTransactionAsync( + transaction, + txOrigin.toLowerCase(), + transactionSignature, + approvalExpirationTimeSeconds, + approvalSignatures, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param transaction 0x transaction containing salt, signerAddress, and data. + * @param txOrigin Required signer of Ethereum transaction calling this + * function. + * @param transactionSignature Proof that the transaction has been signed by + * the signer. + * @param approvalExpirationTimeSeconds Array of expiration times in seconds + * for which each corresponding approval signature expires. + * @param approvalSignatures Array of signatures that correspond to the + * feeRecipients of each order in the transaction's Exchange calldata. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + transaction: { salt: BigNumber; signerAddress: string; data: string }, + txOrigin: string, + transactionSignature: string, + approvalExpirationTimeSeconds: BigNumber[], + approvalSignatures: string[], + txData?: Partial | undefined, + ): Promise { + assert.isString('txOrigin', txOrigin); + assert.isString('transactionSignature', transactionSignature); + assert.isArray('approvalExpirationTimeSeconds', approvalExpirationTimeSeconds); + assert.isArray('approvalSignatures', approvalSignatures); + const self = (this as any) as CoordinatorContract; + const encodedData = self._strictEncodeArguments( + 'executeTransaction((uint256,address,bytes),address,bytes,uint256[],bytes[])', + [ + transaction, + txOrigin.toLowerCase(), + transactionSignature, + approvalExpirationTimeSeconds, + approvalSignatures, + ], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param transaction 0x transaction containing salt, signerAddress, and data. + * @param txOrigin Required signer of Ethereum transaction calling this + * function. + * @param transactionSignature Proof that the transaction has been signed by + * the signer. + * @param approvalExpirationTimeSeconds Array of expiration times in seconds + * for which each corresponding approval signature expires. + * @param approvalSignatures Array of signatures that correspond to the + * feeRecipients of each order in the transaction's Exchange calldata. + */ + async callAsync( + transaction: { salt: BigNumber; signerAddress: string; data: string }, + txOrigin: string, + transactionSignature: string, + approvalExpirationTimeSeconds: BigNumber[], + approvalSignatures: string[], + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('txOrigin', txOrigin); + assert.isString('transactionSignature', transactionSignature); + assert.isArray('approvalExpirationTimeSeconds', approvalExpirationTimeSeconds); + assert.isArray('approvalSignatures', approvalSignatures); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as CoordinatorContract; + const encodedData = self._strictEncodeArguments( + 'executeTransaction((uint256,address,bytes),address,bytes,uint256[],bytes[])', + [ + transaction, + txOrigin.toLowerCase(), + transactionSignature, + approvalExpirationTimeSeconds, + approvalSignatures, + ], + ); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'executeTransaction((uint256,address,bytes),address,bytes,uint256[],bytes[])', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param transaction 0x transaction containing salt, signerAddress, and data. + * @param txOrigin Required signer of Ethereum transaction calling this + * function. + * @param transactionSignature Proof that the transaction has been signed by + * the signer. + * @param approvalExpirationTimeSeconds Array of expiration times in seconds + * for which each corresponding approval signature expires. + * @param approvalSignatures Array of signatures that correspond to the + * feeRecipients of each order in the transaction's Exchange calldata. + */ + getABIEncodedTransactionData( + transaction: { salt: BigNumber; signerAddress: string; data: string }, + txOrigin: string, + transactionSignature: string, + approvalExpirationTimeSeconds: BigNumber[], + approvalSignatures: string[], + ): string { + assert.isString('txOrigin', txOrigin); + assert.isString('transactionSignature', transactionSignature); + assert.isArray('approvalExpirationTimeSeconds', approvalExpirationTimeSeconds); + assert.isArray('approvalSignatures', approvalSignatures); + const self = (this as any) as CoordinatorContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'executeTransaction((uint256,address,bytes),address,bytes,uint256[],bytes[])', + [ + transaction, + txOrigin.toLowerCase(), + transactionSignature, + approvalExpirationTimeSeconds, + approvalSignatures, + ], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as CoordinatorContract; + const abiEncoder = self._lookupAbiEncoder( + 'executeTransaction((uint256,address,bytes),address,bytes,uint256[],bytes[])', + ); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as CoordinatorContract; + const abiEncoder = self._lookupAbiEncoder( + 'executeTransaction((uint256,address,bytes),address,bytes,uint256[],bytes[])', + ); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public EIP712_EXCHANGE_DOMAIN_HASH = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as CoordinatorContract; + const encodedData = self._strictEncodeArguments('EIP712_EXCHANGE_DOMAIN_HASH()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('EIP712_EXCHANGE_DOMAIN_HASH()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as CoordinatorContract; + const abiEncodedTransactionData = self._strictEncodeArguments('EIP712_EXCHANGE_DOMAIN_HASH()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as CoordinatorContract; + const abiEncoder = self._lookupAbiEncoder('EIP712_EXCHANGE_DOMAIN_HASH()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as CoordinatorContract; + const abiEncoder = self._lookupAbiEncoder('EIP712_EXCHANGE_DOMAIN_HASH()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Validates that the 0x transaction has been approved by all of the feeRecipients + * that correspond to each order in the transaction's Exchange calldata. + */ + public assertValidCoordinatorApprovals = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param transaction 0x transaction containing salt, signerAddress, and data. + * @param txOrigin Required signer of Ethereum transaction calling this + * function. + * @param transactionSignature Proof that the transaction has been signed by + * the signer. + * @param approvalExpirationTimeSeconds Array of expiration times in seconds + * for which each corresponding approval signature expires. + * @param approvalSignatures Array of signatures that correspond to the + * feeRecipients of each order in the transaction's Exchange calldata. + */ + async callAsync( + transaction: { salt: BigNumber; signerAddress: string; data: string }, + txOrigin: string, + transactionSignature: string, + approvalExpirationTimeSeconds: BigNumber[], + approvalSignatures: string[], + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('txOrigin', txOrigin); + assert.isString('transactionSignature', transactionSignature); + assert.isArray('approvalExpirationTimeSeconds', approvalExpirationTimeSeconds); + assert.isArray('approvalSignatures', approvalSignatures); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as CoordinatorContract; + const encodedData = self._strictEncodeArguments( + 'assertValidCoordinatorApprovals((uint256,address,bytes),address,bytes,uint256[],bytes[])', + [ + transaction, + txOrigin.toLowerCase(), + transactionSignature, + approvalExpirationTimeSeconds, + approvalSignatures, + ], + ); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'assertValidCoordinatorApprovals((uint256,address,bytes),address,bytes,uint256[],bytes[])', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param transaction 0x transaction containing salt, signerAddress, and data. + * @param txOrigin Required signer of Ethereum transaction calling this + * function. + * @param transactionSignature Proof that the transaction has been signed by + * the signer. + * @param approvalExpirationTimeSeconds Array of expiration times in seconds + * for which each corresponding approval signature expires. + * @param approvalSignatures Array of signatures that correspond to the + * feeRecipients of each order in the transaction's Exchange calldata. + */ + getABIEncodedTransactionData( + transaction: { salt: BigNumber; signerAddress: string; data: string }, + txOrigin: string, + transactionSignature: string, + approvalExpirationTimeSeconds: BigNumber[], + approvalSignatures: string[], + ): string { + assert.isString('txOrigin', txOrigin); + assert.isString('transactionSignature', transactionSignature); + assert.isArray('approvalExpirationTimeSeconds', approvalExpirationTimeSeconds); + assert.isArray('approvalSignatures', approvalSignatures); + const self = (this as any) as CoordinatorContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'assertValidCoordinatorApprovals((uint256,address,bytes),address,bytes,uint256[],bytes[])', + [ + transaction, + txOrigin.toLowerCase(), + transactionSignature, + approvalExpirationTimeSeconds, + approvalSignatures, + ], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as CoordinatorContract; + const abiEncoder = self._lookupAbiEncoder( + 'assertValidCoordinatorApprovals((uint256,address,bytes),address,bytes,uint256[],bytes[])', + ); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as CoordinatorContract; + const abiEncoder = self._lookupAbiEncoder( + 'assertValidCoordinatorApprovals((uint256,address,bytes),address,bytes,uint256[],bytes[])', + ); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Decodes the orders from Exchange calldata representing any fill method. + */ + public decodeOrdersFromFillData = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param data Exchange calldata representing a fill method. + * @returns The orders from the Exchange calldata. + */ + async callAsync( + data: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise< + Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }> + > { + assert.isString('data', data); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as CoordinatorContract; + const encodedData = self._strictEncodeArguments('decodeOrdersFromFillData(bytes)', [data]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decodeOrdersFromFillData(bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue< + Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }> + >(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param data Exchange calldata representing a fill method. + */ + getABIEncodedTransactionData(data: string): string { + assert.isString('data', data); + const self = (this as any) as CoordinatorContract; + const abiEncodedTransactionData = self._strictEncodeArguments('decodeOrdersFromFillData(bytes)', [data]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData( + callData: string, + ): Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }> { + const self = (this as any) as CoordinatorContract; + const abiEncoder = self._lookupAbiEncoder('decodeOrdersFromFillData(bytes)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode< + Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }> + >(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData( + returnData: string, + ): Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }> { + const self = (this as any) as CoordinatorContract; + const abiEncoder = self._lookupAbiEncoder('decodeOrdersFromFillData(bytes)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue< + Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }> + >(returnData); + return abiDecodedReturnData; + }, + }; + public EIP712_COORDINATOR_DOMAIN_HASH = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as CoordinatorContract; + const encodedData = self._strictEncodeArguments('EIP712_COORDINATOR_DOMAIN_HASH()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('EIP712_COORDINATOR_DOMAIN_HASH()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as CoordinatorContract; + const abiEncodedTransactionData = self._strictEncodeArguments('EIP712_COORDINATOR_DOMAIN_HASH()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as CoordinatorContract; + const abiEncoder = self._lookupAbiEncoder('EIP712_COORDINATOR_DOMAIN_HASH()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as CoordinatorContract; + const abiEncoder = self._lookupAbiEncoder('EIP712_COORDINATOR_DOMAIN_HASH()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public static async deployFrom0xArtifactAsync( + artifact: ContractArtifact | SimpleContractArtifact, + supportedProvider: SupportedProvider, + txDefaults: Partial, + logDecodeDependencies: { [contractName: string]: ContractArtifact | SimpleContractArtifact }, + _exchange: string, + ): 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 CoordinatorContract.deployAsync( + bytecode, + abi, + provider, + txDefaults, + logDecodeDependenciesAbiOnly, + _exchange, + ); + } + public static async deployAsync( + bytecode: string, + abi: ContractAbi, + supportedProvider: SupportedProvider, + txDefaults: Partial, + logDecodeDependencies: { [contractName: string]: ContractAbi }, + _exchange: string, + ): 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); + [_exchange] = BaseContract._formatABIDataItemList( + constructorAbi.inputs, + [_exchange], + BaseContract._bigNumberToString, + ); + const iface = new ethers.utils.Interface(abi); + const deployInfo = iface.deployFunction; + const txData = deployInfo.encode(bytecode, [_exchange]); + const web3Wrapper = new Web3Wrapper(provider); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { 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(`Coordinator successfully deployed at ${txReceipt.contractAddress}`); + const contractInstance = new CoordinatorContract( + txReceipt.contractAddress as string, + provider, + txDefaults, + logDecodeDependencies, + ); + contractInstance.constructorArgs = [_exchange]; + return contractInstance; + } + + /** + * @returns The contract ABI + */ + public static ABI(): ContractAbi { + const abi = [ + { + constant: true, + inputs: [ + { + name: 'hash', + type: 'bytes32', + }, + { + name: 'signature', + type: 'bytes', + }, + ], + name: 'getSignerAddress', + outputs: [ + { + name: 'signerAddress', + type: 'address', + }, + ], + payable: false, + stateMutability: 'pure', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'transaction', + type: 'tuple', + components: [ + { + name: 'salt', + type: 'uint256', + }, + { + name: 'signerAddress', + type: 'address', + }, + { + name: 'data', + type: 'bytes', + }, + ], + }, + ], + name: 'getTransactionHash', + outputs: [ + { + name: 'transactionHash', + type: 'bytes32', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'approval', + type: 'tuple', + components: [ + { + name: 'txOrigin', + type: 'address', + }, + { + name: 'transactionHash', + type: 'bytes32', + }, + { + name: 'transactionSignature', + type: 'bytes', + }, + { + name: 'approvalExpirationTimeSeconds', + type: 'uint256', + }, + ], + }, + ], + name: 'getCoordinatorApprovalHash', + outputs: [ + { + name: 'approvalHash', + type: 'bytes32', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'transaction', + type: 'tuple', + components: [ + { + name: 'salt', + type: 'uint256', + }, + { + name: 'signerAddress', + type: 'address', + }, + { + name: 'data', + type: 'bytes', + }, + ], + }, + { + name: 'txOrigin', + type: 'address', + }, + { + name: 'transactionSignature', + type: 'bytes', + }, + { + name: 'approvalExpirationTimeSeconds', + type: 'uint256[]', + }, + { + name: 'approvalSignatures', + type: 'bytes[]', + }, + ], + name: 'executeTransaction', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'EIP712_EXCHANGE_DOMAIN_HASH', + outputs: [ + { + name: '', + type: 'bytes32', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'transaction', + type: 'tuple', + components: [ + { + name: 'salt', + type: 'uint256', + }, + { + name: 'signerAddress', + type: 'address', + }, + { + name: 'data', + type: 'bytes', + }, + ], + }, + { + name: 'txOrigin', + type: 'address', + }, + { + name: 'transactionSignature', + type: 'bytes', + }, + { + name: 'approvalExpirationTimeSeconds', + type: 'uint256[]', + }, + { + name: 'approvalSignatures', + type: 'bytes[]', + }, + ], + name: 'assertValidCoordinatorApprovals', + outputs: [], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'data', + type: 'bytes', + }, + ], + name: 'decodeOrdersFromFillData', + outputs: [ + { + name: 'orders', + type: 'tuple[]', + 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', + }, + ], + }, + ], + payable: false, + stateMutability: 'pure', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'EIP712_COORDINATOR_DOMAIN_HASH', + outputs: [ + { + name: '', + type: 'bytes32', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + name: '_exchange', + type: 'address', + }, + ], + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'constructor', + }, + ] as ContractAbi; + return abi; + } + constructor( + address: string, + supportedProvider: SupportedProvider, + txDefaults?: Partial, + logDecodeDependencies?: { [contractName: string]: ContractAbi }, + ) { + super('Coordinator', CoordinatorContract.ABI(), address, supportedProvider, txDefaults, logDecodeDependencies); + classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + } +} + +// 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/contract-wrappers/src/generated-wrappers/coordinator_registry.ts b/packages/contract-wrappers/src/generated-wrappers/coordinator_registry.ts new file mode 100644 index 0000000000..373136ce51 --- /dev/null +++ b/packages/contract-wrappers/src/generated-wrappers/coordinator_registry.ts @@ -0,0 +1,511 @@ +// tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma +// tslint:disable:whitespace no-unbound-method no-trailing-whitespace +// tslint:disable:no-unused-variable +import { + BaseContract, + BlockRange, + EventCallback, + IndexedFilterValues, + SubscriptionManager, + PromiseWithTransactionHash, +} from '@0x/base-contract'; +import { schemas } from '@0x/json-schemas'; +import { + BlockParam, + BlockParamLiteral, + CallData, + ContractAbi, + ContractArtifact, + DecodedLogArgs, + LogWithDecodedArgs, + MethodAbi, + TransactionReceiptWithDecodedLogs, + TxData, + TxDataPayable, + SupportedProvider, +} from 'ethereum-types'; +import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; +import { 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 CoordinatorRegistryEventArgs = CoordinatorRegistryCoordinatorEndpointSetEventArgs; + +export enum CoordinatorRegistryEvents { + CoordinatorEndpointSet = 'CoordinatorEndpointSet', +} + +export interface CoordinatorRegistryCoordinatorEndpointSetEventArgs extends DecodedLogArgs { + coordinatorOperator: string; + coordinatorEndpoint: string; +} + +/* istanbul ignore next */ +// tslint:disable:no-parameter-reassignment +// tslint:disable-next-line:class-name +export class CoordinatorRegistryContract extends BaseContract { + /** + * Called by a Coordinator operator to set the endpoint of their Coordinator. + */ + public setCoordinatorEndpoint = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param coordinatorEndpoint endpoint of the Coordinator. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(coordinatorEndpoint: string, txData?: Partial | undefined): Promise { + assert.isString('coordinatorEndpoint', coordinatorEndpoint); + const self = (this as any) as CoordinatorRegistryContract; + const encodedData = self._strictEncodeArguments('setCoordinatorEndpoint(string)', [coordinatorEndpoint]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.setCoordinatorEndpoint.estimateGasAsync.bind(self, coordinatorEndpoint), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param coordinatorEndpoint endpoint of the Coordinator. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + coordinatorEndpoint: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('coordinatorEndpoint', coordinatorEndpoint); + const self = (this as any) as CoordinatorRegistryContract; + const txHashPromise = self.setCoordinatorEndpoint.sendTransactionAsync(coordinatorEndpoint, txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param coordinatorEndpoint endpoint of the Coordinator. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(coordinatorEndpoint: string, txData?: Partial | undefined): Promise { + assert.isString('coordinatorEndpoint', coordinatorEndpoint); + const self = (this as any) as CoordinatorRegistryContract; + const encodedData = self._strictEncodeArguments('setCoordinatorEndpoint(string)', [coordinatorEndpoint]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param coordinatorEndpoint endpoint of the Coordinator. + */ + async callAsync( + coordinatorEndpoint: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('coordinatorEndpoint', coordinatorEndpoint); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as CoordinatorRegistryContract; + const encodedData = self._strictEncodeArguments('setCoordinatorEndpoint(string)', [coordinatorEndpoint]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('setCoordinatorEndpoint(string)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param coordinatorEndpoint endpoint of the Coordinator. + */ + getABIEncodedTransactionData(coordinatorEndpoint: string): string { + assert.isString('coordinatorEndpoint', coordinatorEndpoint); + const self = (this as any) as CoordinatorRegistryContract; + const abiEncodedTransactionData = self._strictEncodeArguments('setCoordinatorEndpoint(string)', [ + coordinatorEndpoint, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as CoordinatorRegistryContract; + const abiEncoder = self._lookupAbiEncoder('setCoordinatorEndpoint(string)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as CoordinatorRegistryContract; + const abiEncoder = self._lookupAbiEncoder('setCoordinatorEndpoint(string)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Gets the endpoint for a Coordinator. + */ + public getCoordinatorEndpoint = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param coordinatorOperator operator of the Coordinator endpoint. + */ + async callAsync( + coordinatorOperator: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('coordinatorOperator', coordinatorOperator); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as CoordinatorRegistryContract; + const encodedData = self._strictEncodeArguments('getCoordinatorEndpoint(address)', [ + coordinatorOperator.toLowerCase(), + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getCoordinatorEndpoint(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param coordinatorOperator operator of the Coordinator endpoint. + */ + getABIEncodedTransactionData(coordinatorOperator: string): string { + assert.isString('coordinatorOperator', coordinatorOperator); + const self = (this as any) as CoordinatorRegistryContract; + const abiEncodedTransactionData = self._strictEncodeArguments('getCoordinatorEndpoint(address)', [ + coordinatorOperator.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as CoordinatorRegistryContract; + const abiEncoder = self._lookupAbiEncoder('getCoordinatorEndpoint(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as CoordinatorRegistryContract; + const abiEncoder = self._lookupAbiEncoder('getCoordinatorEndpoint(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + 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 CoordinatorRegistryContract.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._applyDefaultsToTxDataAsync( + { 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(`CoordinatorRegistry successfully deployed at ${txReceipt.contractAddress}`); + const contractInstance = new CoordinatorRegistryContract( + txReceipt.contractAddress as string, + provider, + txDefaults, + logDecodeDependencies, + ); + contractInstance.constructorArgs = []; + return contractInstance; + } + + /** + * @returns The contract ABI + */ + public static ABI(): ContractAbi { + const abi = [ + { + constant: false, + inputs: [ + { + name: 'coordinatorEndpoint', + type: 'string', + }, + ], + name: 'setCoordinatorEndpoint', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'coordinatorOperator', + type: 'address', + }, + ], + name: 'getCoordinatorEndpoint', + outputs: [ + { + name: 'coordinatorEndpoint', + type: 'string', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + inputs: [], + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'constructor', + }, + { + anonymous: false, + inputs: [ + { + name: 'coordinatorOperator', + type: 'address', + indexed: false, + }, + { + name: 'coordinatorEndpoint', + type: 'string', + indexed: false, + }, + ], + name: 'CoordinatorEndpointSet', + outputs: [], + type: 'event', + }, + ] as ContractAbi; + return abi; + } + /** + * Subscribe to an event type emitted by the CoordinatorRegistry contract. + * @param eventName The CoordinatorRegistry 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: CoordinatorRegistryEvents, + indexFilterValues: IndexedFilterValues, + callback: EventCallback, + isVerbose: boolean = false, + blockPollingIntervalMs?: number, + ): string { + assert.doesBelongToStringEnum('eventName', eventName, CoordinatorRegistryEvents); + assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); + assert.isFunction('callback', callback); + const subscriptionToken = this._subscriptionManager.subscribe( + this.address, + eventName, + indexFilterValues, + CoordinatorRegistryContract.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 CoordinatorRegistry 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: CoordinatorRegistryEvents, + blockRange: BlockRange, + indexFilterValues: IndexedFilterValues, + ): Promise>> { + assert.doesBelongToStringEnum('eventName', eventName, CoordinatorRegistryEvents); + assert.doesConformToSchema('blockRange', blockRange, schemas.blockRangeSchema); + assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); + const logs = await this._subscriptionManager.getLogsAsync( + this.address, + eventName, + blockRange, + indexFilterValues, + CoordinatorRegistryContract.ABI(), + ); + return logs; + } + constructor( + address: string, + supportedProvider: SupportedProvider, + txDefaults?: Partial, + logDecodeDependencies?: { [contractName: string]: ContractAbi }, + ) { + super( + 'CoordinatorRegistry', + CoordinatorRegistryContract.ABI(), + address, + supportedProvider, + txDefaults, + logDecodeDependencies, + ); + classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + this._subscriptionManager = new SubscriptionManager( + CoordinatorRegistryContract.ABI(), + this._web3Wrapper, + ); + } +} + +// 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/contract-wrappers/src/generated-wrappers/dummy_erc20_token.ts b/packages/contract-wrappers/src/generated-wrappers/dummy_erc20_token.ts new file mode 100644 index 0000000000..6dbf9f4b02 --- /dev/null +++ b/packages/contract-wrappers/src/generated-wrappers/dummy_erc20_token.ts @@ -0,0 +1,2142 @@ +// tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma +// tslint:disable:whitespace no-unbound-method no-trailing-whitespace +// tslint:disable:no-unused-variable +import { + BaseContract, + BlockRange, + EventCallback, + IndexedFilterValues, + SubscriptionManager, + PromiseWithTransactionHash, +} from '@0x/base-contract'; +import { schemas } from '@0x/json-schemas'; +import { + BlockParam, + BlockParamLiteral, + CallData, + ContractAbi, + ContractArtifact, + DecodedLogArgs, + LogWithDecodedArgs, + MethodAbi, + TransactionReceiptWithDecodedLogs, + TxData, + TxDataPayable, + SupportedProvider, +} from 'ethereum-types'; +import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; +import { 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 DummyERC20TokenEventArgs = DummyERC20TokenTransferEventArgs | DummyERC20TokenApprovalEventArgs; + +export enum DummyERC20TokenEvents { + Transfer = 'Transfer', + Approval = 'Approval', +} + +export interface DummyERC20TokenTransferEventArgs extends DecodedLogArgs { + _from: string; + _to: string; + _value: BigNumber; +} + +export interface DummyERC20TokenApprovalEventArgs extends DecodedLogArgs { + _owner: string; + _spender: string; + _value: BigNumber; +} + +/* istanbul ignore next */ +// tslint:disable:no-parameter-reassignment +// tslint:disable-next-line:class-name +export class DummyERC20TokenContract extends BaseContract { + public name = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC20TokenContract; + const encodedData = self._strictEncodeArguments('name()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('name()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as DummyERC20TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('name()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('name()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('name()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * `msg.sender` approves `_spender` to spend `_value` tokens + */ + public approve = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param _spender The address of the account able to transfer the tokens + * @param _value The amount of wei to be approved for transfer + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + _spender: string, + _value: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_spender', _spender); + assert.isBigNumber('_value', _value); + const self = (this as any) as DummyERC20TokenContract; + const encodedData = self._strictEncodeArguments('approve(address,uint256)', [ + _spender.toLowerCase(), + _value, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.approve.estimateGasAsync.bind(self, _spender.toLowerCase(), _value), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param _spender The address of the account able to transfer the tokens + * @param _value The amount of wei to be approved for transfer + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + _spender: string, + _value: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('_spender', _spender); + assert.isBigNumber('_value', _value); + const self = (this as any) as DummyERC20TokenContract; + const txHashPromise = self.approve.sendTransactionAsync(_spender.toLowerCase(), _value, txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param _spender The address of the account able to transfer the tokens + * @param _value The amount of wei to be approved for transfer + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + _spender: string, + _value: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_spender', _spender); + assert.isBigNumber('_value', _value); + const self = (this as any) as DummyERC20TokenContract; + const encodedData = self._strictEncodeArguments('approve(address,uint256)', [ + _spender.toLowerCase(), + _value, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _spender The address of the account able to transfer the tokens + * @param _value The amount of wei to be approved for transfer + * @returns Always true if the call has enough gas to complete execution + */ + async callAsync( + _spender: string, + _value: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_spender', _spender); + assert.isBigNumber('_value', _value); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC20TokenContract; + const encodedData = self._strictEncodeArguments('approve(address,uint256)', [ + _spender.toLowerCase(), + _value, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('approve(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _spender The address of the account able to transfer the tokens + * @param _value The amount of wei to be approved for transfer + */ + getABIEncodedTransactionData(_spender: string, _value: BigNumber): string { + assert.isString('_spender', _spender); + assert.isBigNumber('_value', _value); + const self = (this as any) as DummyERC20TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('approve(address,uint256)', [ + _spender.toLowerCase(), + _value, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): boolean { + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('approve(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): boolean { + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('approve(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Query total supply of token + */ + public totalSupply = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @returns Total supply of token + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC20TokenContract; + const encodedData = self._strictEncodeArguments('totalSupply()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('totalSupply()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as DummyERC20TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('totalSupply()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): BigNumber { + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('totalSupply()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): BigNumber { + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('totalSupply()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * ERC20 transferFrom, modified such that an allowance of MAX_UINT represents an unlimited allowance. See https://github.com/ethereum/EIPs/issues/717 + */ + public transferFrom = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param _from Address to transfer from. + * @param _to Address to transfer to. + * @param _value Amount to transfer. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + _from: string, + _to: string, + _value: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + const self = (this as any) as DummyERC20TokenContract; + const encodedData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _value, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.transferFrom.estimateGasAsync.bind(self, _from.toLowerCase(), _to.toLowerCase(), _value), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param _from Address to transfer from. + * @param _to Address to transfer to. + * @param _value Amount to transfer. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + _from: string, + _to: string, + _value: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + const self = (this as any) as DummyERC20TokenContract; + const txHashPromise = self.transferFrom.sendTransactionAsync( + _from.toLowerCase(), + _to.toLowerCase(), + _value, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param _from Address to transfer from. + * @param _to Address to transfer to. + * @param _value Amount to transfer. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + _from: string, + _to: string, + _value: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + const self = (this as any) as DummyERC20TokenContract; + const encodedData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _value, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _from Address to transfer from. + * @param _to Address to transfer to. + * @param _value Amount to transfer. + * @returns Success of transfer. + */ + async callAsync( + _from: string, + _to: string, + _value: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC20TokenContract; + const encodedData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _value, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _from Address to transfer from. + * @param _to Address to transfer to. + * @param _value Amount to transfer. + */ + getABIEncodedTransactionData(_from: string, _to: string, _value: BigNumber): string { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + const self = (this as any) as DummyERC20TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _value, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): boolean { + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('transferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): boolean { + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('transferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public decimals = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC20TokenContract; + const encodedData = self._strictEncodeArguments('decimals()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decimals()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as DummyERC20TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('decimals()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): BigNumber { + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('decimals()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): BigNumber { + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('decimals()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Query the balance of owner + */ + public balanceOf = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _owner The address from which the balance will be retrieved + * @returns Balance of owner + */ + async callAsync( + _owner: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_owner', _owner); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC20TokenContract; + const encodedData = self._strictEncodeArguments('balanceOf(address)', [_owner.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('balanceOf(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _owner The address from which the balance will be retrieved + */ + getABIEncodedTransactionData(_owner: string): string { + assert.isString('_owner', _owner); + const self = (this as any) as DummyERC20TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('balanceOf(address)', [_owner.toLowerCase()]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): BigNumber { + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('balanceOf(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): BigNumber { + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('balanceOf(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public owner = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC20TokenContract; + const encodedData = self._strictEncodeArguments('owner()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('owner()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as DummyERC20TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('owner()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('owner()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('owner()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public symbol = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC20TokenContract; + const encodedData = self._strictEncodeArguments('symbol()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('symbol()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as DummyERC20TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('symbol()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('symbol()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('symbol()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Mints new tokens for sender + */ + public mint = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param _value Amount of tokens to mint + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(_value: BigNumber, txData?: Partial | undefined): Promise { + assert.isBigNumber('_value', _value); + const self = (this as any) as DummyERC20TokenContract; + const encodedData = self._strictEncodeArguments('mint(uint256)', [_value]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.mint.estimateGasAsync.bind(self, _value), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param _value Amount of tokens to mint + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + _value: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isBigNumber('_value', _value); + const self = (this as any) as DummyERC20TokenContract; + const txHashPromise = self.mint.sendTransactionAsync(_value, txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param _value Amount of tokens to mint + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(_value: BigNumber, txData?: Partial | undefined): Promise { + assert.isBigNumber('_value', _value); + const self = (this as any) as DummyERC20TokenContract; + const encodedData = self._strictEncodeArguments('mint(uint256)', [_value]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _value Amount of tokens to mint + */ + async callAsync(_value: BigNumber, callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.isBigNumber('_value', _value); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC20TokenContract; + const encodedData = self._strictEncodeArguments('mint(uint256)', [_value]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('mint(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _value Amount of tokens to mint + */ + getABIEncodedTransactionData(_value: BigNumber): string { + assert.isBigNumber('_value', _value); + const self = (this as any) as DummyERC20TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('mint(uint256)', [_value]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('mint(uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('mint(uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * send `value` token to `to` from `msg.sender` + */ + public transfer = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param _to The address of the recipient + * @param _value The amount of token to be transferred + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + _to: string, + _value: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + const self = (this as any) as DummyERC20TokenContract; + const encodedData = self._strictEncodeArguments('transfer(address,uint256)', [_to.toLowerCase(), _value]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.transfer.estimateGasAsync.bind(self, _to.toLowerCase(), _value), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param _to The address of the recipient + * @param _value The amount of token to be transferred + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + _to: string, + _value: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + const self = (this as any) as DummyERC20TokenContract; + const txHashPromise = self.transfer.sendTransactionAsync(_to.toLowerCase(), _value, txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param _to The address of the recipient + * @param _value The amount of token to be transferred + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(_to: string, _value: BigNumber, txData?: Partial | undefined): Promise { + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + const self = (this as any) as DummyERC20TokenContract; + const encodedData = self._strictEncodeArguments('transfer(address,uint256)', [_to.toLowerCase(), _value]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _to The address of the recipient + * @param _value The amount of token to be transferred + * @returns True if transfer was successful + */ + async callAsync( + _to: string, + _value: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC20TokenContract; + const encodedData = self._strictEncodeArguments('transfer(address,uint256)', [_to.toLowerCase(), _value]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transfer(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _to The address of the recipient + * @param _value The amount of token to be transferred + */ + getABIEncodedTransactionData(_to: string, _value: BigNumber): string { + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + const self = (this as any) as DummyERC20TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('transfer(address,uint256)', [ + _to.toLowerCase(), + _value, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): boolean { + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('transfer(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): boolean { + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('transfer(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public allowance = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _owner The address of the account owning tokens + * @param _spender The address of the account able to transfer the tokens + * @returns Amount of remaining tokens allowed to spent + */ + async callAsync( + _owner: string, + _spender: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_owner', _owner); + assert.isString('_spender', _spender); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC20TokenContract; + const encodedData = self._strictEncodeArguments('allowance(address,address)', [ + _owner.toLowerCase(), + _spender.toLowerCase(), + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('allowance(address,address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _owner The address of the account owning tokens + * @param _spender The address of the account able to transfer the tokens + */ + getABIEncodedTransactionData(_owner: string, _spender: string): string { + assert.isString('_owner', _owner); + assert.isString('_spender', _spender); + const self = (this as any) as DummyERC20TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('allowance(address,address)', [ + _owner.toLowerCase(), + _spender.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): BigNumber { + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('allowance(address,address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): BigNumber { + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('allowance(address,address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Sets the balance of target address + */ + public setBalance = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param _target Address or which balance will be updated + * @param _value New balance of target address + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + _target: string, + _value: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_target', _target); + assert.isBigNumber('_value', _value); + const self = (this as any) as DummyERC20TokenContract; + const encodedData = self._strictEncodeArguments('setBalance(address,uint256)', [ + _target.toLowerCase(), + _value, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.setBalance.estimateGasAsync.bind(self, _target.toLowerCase(), _value), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param _target Address or which balance will be updated + * @param _value New balance of target address + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + _target: string, + _value: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('_target', _target); + assert.isBigNumber('_value', _value); + const self = (this as any) as DummyERC20TokenContract; + const txHashPromise = self.setBalance.sendTransactionAsync(_target.toLowerCase(), _value, txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param _target Address or which balance will be updated + * @param _value New balance of target address + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + _target: string, + _value: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_target', _target); + assert.isBigNumber('_value', _value); + const self = (this as any) as DummyERC20TokenContract; + const encodedData = self._strictEncodeArguments('setBalance(address,uint256)', [ + _target.toLowerCase(), + _value, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _target Address or which balance will be updated + * @param _value New balance of target address + */ + async callAsync( + _target: string, + _value: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_target', _target); + assert.isBigNumber('_value', _value); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC20TokenContract; + const encodedData = self._strictEncodeArguments('setBalance(address,uint256)', [ + _target.toLowerCase(), + _value, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('setBalance(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _target Address or which balance will be updated + * @param _value New balance of target address + */ + getABIEncodedTransactionData(_target: string, _value: BigNumber): string { + assert.isString('_target', _target); + assert.isBigNumber('_value', _value); + const self = (this as any) as DummyERC20TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('setBalance(address,uint256)', [ + _target.toLowerCase(), + _value, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('setBalance(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('setBalance(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public transferOwnership = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(newOwner: string, txData?: Partial | undefined): Promise { + assert.isString('newOwner', newOwner); + const self = (this as any) as DummyERC20TokenContract; + const encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.transferOwnership.estimateGasAsync.bind(self, newOwner.toLowerCase()), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + newOwner: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('newOwner', newOwner); + const self = (this as any) as DummyERC20TokenContract; + const txHashPromise = self.transferOwnership.sendTransactionAsync(newOwner.toLowerCase(), txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(newOwner: string, txData?: Partial | undefined): Promise { + assert.isString('newOwner', newOwner); + const self = (this as any) as DummyERC20TokenContract; + const encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(newOwner: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.isString('newOwner', newOwner); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC20TokenContract; + const encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(newOwner: string): string { + assert.isString('newOwner', newOwner); + const self = (this as any) as DummyERC20TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('transferOwnership(address)', [ + newOwner.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public MAX_MINT_AMOUNT = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC20TokenContract; + const encodedData = self._strictEncodeArguments('MAX_MINT_AMOUNT()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('MAX_MINT_AMOUNT()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as DummyERC20TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('MAX_MINT_AMOUNT()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): BigNumber { + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('MAX_MINT_AMOUNT()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): BigNumber { + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('MAX_MINT_AMOUNT()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + private readonly _subscriptionManager: SubscriptionManager; + public static async deployFrom0xArtifactAsync( + artifact: ContractArtifact | SimpleContractArtifact, + supportedProvider: SupportedProvider, + txDefaults: Partial, + logDecodeDependencies: { [contractName: string]: ContractArtifact | SimpleContractArtifact }, + _name: string, + _symbol: string, + _decimals: BigNumber, + _totalSupply: BigNumber, + ): 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 DummyERC20TokenContract.deployAsync( + bytecode, + abi, + provider, + txDefaults, + logDecodeDependenciesAbiOnly, + _name, + _symbol, + _decimals, + _totalSupply, + ); + } + public static async deployAsync( + bytecode: string, + abi: ContractAbi, + supportedProvider: SupportedProvider, + txDefaults: Partial, + logDecodeDependencies: { [contractName: string]: ContractAbi }, + _name: string, + _symbol: string, + _decimals: BigNumber, + _totalSupply: BigNumber, + ): 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); + [_name, _symbol, _decimals, _totalSupply] = BaseContract._formatABIDataItemList( + constructorAbi.inputs, + [_name, _symbol, _decimals, _totalSupply], + BaseContract._bigNumberToString, + ); + const iface = new ethers.utils.Interface(abi); + const deployInfo = iface.deployFunction; + const txData = deployInfo.encode(bytecode, [_name, _symbol, _decimals, _totalSupply]); + const web3Wrapper = new Web3Wrapper(provider); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { 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(`DummyERC20Token successfully deployed at ${txReceipt.contractAddress}`); + const contractInstance = new DummyERC20TokenContract( + txReceipt.contractAddress as string, + provider, + txDefaults, + logDecodeDependencies, + ); + contractInstance.constructorArgs = [_name, _symbol, _decimals, _totalSupply]; + return contractInstance; + } + + /** + * @returns The contract ABI + */ + public static ABI(): ContractAbi { + const abi = [ + { + constant: true, + inputs: [], + name: 'name', + outputs: [ + { + name: '', + type: 'string', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: '_spender', + type: 'address', + }, + { + name: '_value', + type: 'uint256', + }, + ], + name: 'approve', + outputs: [ + { + name: '', + type: 'bool', + }, + ], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'totalSupply', + outputs: [ + { + name: '', + type: 'uint256', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: '_from', + type: 'address', + }, + { + name: '_to', + type: 'address', + }, + { + name: '_value', + type: 'uint256', + }, + ], + name: 'transferFrom', + outputs: [ + { + name: '', + type: 'bool', + }, + ], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'decimals', + outputs: [ + { + name: '', + type: 'uint256', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: '_owner', + type: 'address', + }, + ], + name: 'balanceOf', + outputs: [ + { + name: '', + type: 'uint256', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'owner', + outputs: [ + { + name: '', + type: 'address', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'symbol', + outputs: [ + { + name: '', + type: 'string', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: '_value', + type: 'uint256', + }, + ], + name: 'mint', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: '_to', + type: 'address', + }, + { + name: '_value', + type: 'uint256', + }, + ], + name: 'transfer', + outputs: [ + { + name: '', + type: 'bool', + }, + ], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: '_owner', + type: 'address', + }, + { + name: '_spender', + type: 'address', + }, + ], + name: 'allowance', + outputs: [ + { + name: '', + type: 'uint256', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: '_target', + type: 'address', + }, + { + name: '_value', + type: 'uint256', + }, + ], + name: 'setBalance', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'newOwner', + type: 'address', + }, + ], + name: 'transferOwnership', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'MAX_MINT_AMOUNT', + outputs: [ + { + name: '', + type: 'uint256', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + name: '_name', + type: 'string', + }, + { + name: '_symbol', + type: 'string', + }, + { + name: '_decimals', + type: 'uint256', + }, + { + name: '_totalSupply', + type: 'uint256', + }, + ], + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'constructor', + }, + { + anonymous: false, + inputs: [ + { + name: '_from', + type: 'address', + indexed: true, + }, + { + name: '_to', + type: 'address', + indexed: true, + }, + { + name: '_value', + type: 'uint256', + indexed: false, + }, + ], + name: 'Transfer', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: '_owner', + type: 'address', + indexed: true, + }, + { + name: '_spender', + type: 'address', + indexed: true, + }, + { + name: '_value', + type: 'uint256', + indexed: false, + }, + ], + name: 'Approval', + outputs: [], + type: 'event', + }, + ] as ContractAbi; + return abi; + } + /** + * Subscribe to an event type emitted by the DummyERC20Token contract. + * @param eventName The DummyERC20Token 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: DummyERC20TokenEvents, + indexFilterValues: IndexedFilterValues, + callback: EventCallback, + isVerbose: boolean = false, + blockPollingIntervalMs?: number, + ): string { + assert.doesBelongToStringEnum('eventName', eventName, DummyERC20TokenEvents); + assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); + assert.isFunction('callback', callback); + const subscriptionToken = this._subscriptionManager.subscribe( + this.address, + eventName, + indexFilterValues, + DummyERC20TokenContract.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 DummyERC20Token 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: DummyERC20TokenEvents, + blockRange: BlockRange, + indexFilterValues: IndexedFilterValues, + ): Promise>> { + assert.doesBelongToStringEnum('eventName', eventName, DummyERC20TokenEvents); + assert.doesConformToSchema('blockRange', blockRange, schemas.blockRangeSchema); + assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); + const logs = await this._subscriptionManager.getLogsAsync( + this.address, + eventName, + blockRange, + indexFilterValues, + DummyERC20TokenContract.ABI(), + ); + return logs; + } + constructor( + address: string, + supportedProvider: SupportedProvider, + txDefaults?: Partial, + logDecodeDependencies?: { [contractName: string]: ContractAbi }, + ) { + super( + 'DummyERC20Token', + DummyERC20TokenContract.ABI(), + address, + supportedProvider, + txDefaults, + logDecodeDependencies, + ); + classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + this._subscriptionManager = new SubscriptionManager( + DummyERC20TokenContract.ABI(), + this._web3Wrapper, + ); + } +} + +// 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/contract-wrappers/src/generated-wrappers/dummy_erc721_token.ts b/packages/contract-wrappers/src/generated-wrappers/dummy_erc721_token.ts new file mode 100644 index 0000000000..0d5780f909 --- /dev/null +++ b/packages/contract-wrappers/src/generated-wrappers/dummy_erc721_token.ts @@ -0,0 +1,2642 @@ +// tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma +// tslint:disable:whitespace no-unbound-method no-trailing-whitespace +// tslint:disable:no-unused-variable +import { + BaseContract, + BlockRange, + EventCallback, + IndexedFilterValues, + SubscriptionManager, + PromiseWithTransactionHash, +} from '@0x/base-contract'; +import { schemas } from '@0x/json-schemas'; +import { + BlockParam, + BlockParamLiteral, + CallData, + ContractAbi, + ContractArtifact, + DecodedLogArgs, + LogWithDecodedArgs, + MethodAbi, + TransactionReceiptWithDecodedLogs, + TxData, + TxDataPayable, + SupportedProvider, +} from 'ethereum-types'; +import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; +import { 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 DummyERC721TokenEventArgs = + | DummyERC721TokenTransferEventArgs + | DummyERC721TokenApprovalEventArgs + | DummyERC721TokenApprovalForAllEventArgs; + +export enum DummyERC721TokenEvents { + Transfer = 'Transfer', + Approval = 'Approval', + ApprovalForAll = 'ApprovalForAll', +} + +export interface DummyERC721TokenTransferEventArgs extends DecodedLogArgs { + _from: string; + _to: string; + _tokenId: BigNumber; +} + +export interface DummyERC721TokenApprovalEventArgs extends DecodedLogArgs { + _owner: string; + _approved: string; + _tokenId: BigNumber; +} + +export interface DummyERC721TokenApprovalForAllEventArgs extends DecodedLogArgs { + _owner: string; + _operator: string; + _approved: boolean; +} + +/* istanbul ignore next */ +// tslint:disable:no-parameter-reassignment +// tslint:disable-next-line:class-name +export class DummyERC721TokenContract extends BaseContract { + public name = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('name()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('name()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as DummyERC721TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('name()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('name()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('name()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Throws if `_tokenId` is not a valid NFT. + */ + public getApproved = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _tokenId The NFT to find the approved address for + * @returns The approved address for this NFT, or the zero address if there is none + */ + async callAsync( + _tokenId: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isBigNumber('_tokenId', _tokenId); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('getApproved(uint256)', [_tokenId]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getApproved(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _tokenId The NFT to find the approved address for + */ + getABIEncodedTransactionData(_tokenId: BigNumber): string { + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as DummyERC721TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('getApproved(uint256)', [_tokenId]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('getApproved(uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('getApproved(uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * 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. + */ + public approve = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param _approved The new approved NFT controller + * @param _tokenId The NFT to approve + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + _approved: string, + _tokenId: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_approved', _approved); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('approve(address,uint256)', [ + _approved.toLowerCase(), + _tokenId, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.approve.estimateGasAsync.bind(self, _approved.toLowerCase(), _tokenId), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param _approved The new approved NFT controller + * @param _tokenId The NFT to approve + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + _approved: string, + _tokenId: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('_approved', _approved); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as DummyERC721TokenContract; + const txHashPromise = self.approve.sendTransactionAsync(_approved.toLowerCase(), _tokenId, txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param _approved The new approved NFT controller + * @param _tokenId The NFT to approve + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + _approved: string, + _tokenId: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_approved', _approved); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('approve(address,uint256)', [ + _approved.toLowerCase(), + _tokenId, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _approved The new approved NFT controller + * @param _tokenId The NFT to approve + */ + async callAsync( + _approved: string, + _tokenId: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_approved', _approved); + assert.isBigNumber('_tokenId', _tokenId); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('approve(address,uint256)', [ + _approved.toLowerCase(), + _tokenId, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('approve(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _approved The new approved NFT controller + * @param _tokenId The NFT to approve + */ + getABIEncodedTransactionData(_approved: string, _tokenId: BigNumber): string { + assert.isString('_approved', _approved); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as DummyERC721TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('approve(address,uint256)', [ + _approved.toLowerCase(), + _tokenId, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('approve(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('approve(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * 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. + */ + public transferFrom = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + _from: string, + _to: string, + _tokenId: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.transferFrom.estimateGasAsync.bind(self, _from.toLowerCase(), _to.toLowerCase(), _tokenId), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + _from: string, + _to: string, + _tokenId: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as DummyERC721TokenContract; + const txHashPromise = self.transferFrom.sendTransactionAsync( + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + _from: string, + _to: string, + _tokenId: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + */ + async callAsync( + _from: string, + _to: string, + _tokenId: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + */ + getABIEncodedTransactionData(_from: string, _to: string, _tokenId: BigNumber): string { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as DummyERC721TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('transferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('transferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Function to mint a new token + * Reverts if the given token ID already exists + */ + public mint = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param _to Address of the beneficiary that will own the minted token + * @param _tokenId ID of the token to be minted by the msg.sender + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + _to: string, + _tokenId: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('mint(address,uint256)', [_to.toLowerCase(), _tokenId]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.mint.estimateGasAsync.bind(self, _to.toLowerCase(), _tokenId), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param _to Address of the beneficiary that will own the minted token + * @param _tokenId ID of the token to be minted by the msg.sender + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + _to: string, + _tokenId: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as DummyERC721TokenContract; + const txHashPromise = self.mint.sendTransactionAsync(_to.toLowerCase(), _tokenId, txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param _to Address of the beneficiary that will own the minted token + * @param _tokenId ID of the token to be minted by the msg.sender + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + _to: string, + _tokenId: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('mint(address,uint256)', [_to.toLowerCase(), _tokenId]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _to Address of the beneficiary that will own the minted token + * @param _tokenId ID of the token to be minted by the msg.sender + */ + async callAsync( + _to: string, + _tokenId: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('mint(address,uint256)', [_to.toLowerCase(), _tokenId]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('mint(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _to Address of the beneficiary that will own the minted token + * @param _tokenId ID of the token to be minted by the msg.sender + */ + getABIEncodedTransactionData(_to: string, _tokenId: BigNumber): string { + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as DummyERC721TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('mint(address,uint256)', [ + _to.toLowerCase(), + _tokenId, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('mint(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('mint(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * This works identically to the other function with an extra data parameter, + * except this function just sets data to "". + */ + public safeTransferFrom1 = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + _from: string, + _to: string, + _tokenId: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('safeTransferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.safeTransferFrom1.estimateGasAsync.bind(self, _from.toLowerCase(), _to.toLowerCase(), _tokenId), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + _from: string, + _to: string, + _tokenId: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as DummyERC721TokenContract; + const txHashPromise = self.safeTransferFrom1.sendTransactionAsync( + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + _from: string, + _to: string, + _tokenId: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('safeTransferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + */ + async callAsync( + _from: string, + _to: string, + _tokenId: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('safeTransferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('safeTransferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + */ + getABIEncodedTransactionData(_from: string, _to: string, _tokenId: BigNumber): string { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as DummyERC721TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('safeTransferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('safeTransferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('safeTransferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * NFTs assigned to zero address are considered invalid, and queries + * about them do throw. + */ + public ownerOf = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _tokenId The identifier for an NFT + * @returns The address of the owner of the NFT + */ + async callAsync( + _tokenId: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isBigNumber('_tokenId', _tokenId); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('ownerOf(uint256)', [_tokenId]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('ownerOf(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _tokenId The identifier for an NFT + */ + getABIEncodedTransactionData(_tokenId: BigNumber): string { + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as DummyERC721TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('ownerOf(uint256)', [_tokenId]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('ownerOf(uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('ownerOf(uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * NFTs assigned to the zero address are considered invalid, and this + * function throws for queries about the zero address. + */ + public balanceOf = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _owner An address for whom to query the balance + * @returns The number of NFTs owned by `_owner`, possibly zero + */ + async callAsync( + _owner: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_owner', _owner); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('balanceOf(address)', [_owner.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('balanceOf(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _owner An address for whom to query the balance + */ + getABIEncodedTransactionData(_owner: string): string { + assert.isString('_owner', _owner); + const self = (this as any) as DummyERC721TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('balanceOf(address)', [_owner.toLowerCase()]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): BigNumber { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('balanceOf(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): BigNumber { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('balanceOf(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public owner = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('owner()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('owner()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as DummyERC721TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('owner()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('owner()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('owner()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public symbol = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('symbol()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('symbol()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as DummyERC721TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('symbol()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('symbol()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('symbol()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Function to burn a token + * Reverts if the given token ID doesn't exist or not called by contract owner + */ + public burn = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param _owner Owner of token with given token ID + * @param _tokenId ID of the token to be burned by the msg.sender + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + _owner: string, + _tokenId: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_owner', _owner); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('burn(address,uint256)', [_owner.toLowerCase(), _tokenId]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.burn.estimateGasAsync.bind(self, _owner.toLowerCase(), _tokenId), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param _owner Owner of token with given token ID + * @param _tokenId ID of the token to be burned by the msg.sender + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + _owner: string, + _tokenId: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('_owner', _owner); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as DummyERC721TokenContract; + const txHashPromise = self.burn.sendTransactionAsync(_owner.toLowerCase(), _tokenId, txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param _owner Owner of token with given token ID + * @param _tokenId ID of the token to be burned by the msg.sender + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + _owner: string, + _tokenId: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_owner', _owner); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('burn(address,uint256)', [_owner.toLowerCase(), _tokenId]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _owner Owner of token with given token ID + * @param _tokenId ID of the token to be burned by the msg.sender + */ + async callAsync( + _owner: string, + _tokenId: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_owner', _owner); + assert.isBigNumber('_tokenId', _tokenId); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('burn(address,uint256)', [_owner.toLowerCase(), _tokenId]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('burn(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _owner Owner of token with given token ID + * @param _tokenId ID of the token to be burned by the msg.sender + */ + getABIEncodedTransactionData(_owner: string, _tokenId: BigNumber): string { + assert.isString('_owner', _owner); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as DummyERC721TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('burn(address,uint256)', [ + _owner.toLowerCase(), + _tokenId, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('burn(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('burn(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Emits the ApprovalForAll event. The contract MUST allow + * multiple operators per owner. + */ + public setApprovalForAll = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param _operator Address to add to the set of authorized operators + * @param _approved True if the operator is approved, false to revoke approval + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + _operator: string, + _approved: boolean, + txData?: Partial | undefined, + ): Promise { + assert.isString('_operator', _operator); + assert.isBoolean('_approved', _approved); + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('setApprovalForAll(address,bool)', [ + _operator.toLowerCase(), + _approved, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.setApprovalForAll.estimateGasAsync.bind(self, _operator.toLowerCase(), _approved), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param _operator Address to add to the set of authorized operators + * @param _approved True if the operator is approved, false to revoke approval + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + _operator: string, + _approved: boolean, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('_operator', _operator); + assert.isBoolean('_approved', _approved); + const self = (this as any) as DummyERC721TokenContract; + const txHashPromise = self.setApprovalForAll.sendTransactionAsync( + _operator.toLowerCase(), + _approved, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param _operator Address to add to the set of authorized operators + * @param _approved True if the operator is approved, false to revoke approval + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + _operator: string, + _approved: boolean, + txData?: Partial | undefined, + ): Promise { + assert.isString('_operator', _operator); + assert.isBoolean('_approved', _approved); + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('setApprovalForAll(address,bool)', [ + _operator.toLowerCase(), + _approved, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _operator Address to add to the set of authorized operators + * @param _approved True if the operator is approved, false to revoke approval + */ + async callAsync( + _operator: string, + _approved: boolean, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_operator', _operator); + assert.isBoolean('_approved', _approved); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('setApprovalForAll(address,bool)', [ + _operator.toLowerCase(), + _approved, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('setApprovalForAll(address,bool)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _operator Address to add to the set of authorized operators + * @param _approved True if the operator is approved, false to revoke approval + */ + getABIEncodedTransactionData(_operator: string, _approved: boolean): string { + assert.isString('_operator', _operator); + assert.isBoolean('_approved', _approved); + const self = (this as any) as DummyERC721TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('setApprovalForAll(address,bool)', [ + _operator.toLowerCase(), + _approved, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('setApprovalForAll(address,bool)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('setApprovalForAll(address,bool)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * 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)"))`. + */ + public safeTransferFrom2 = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + * @param _data Additional data with no specified format, sent in call to `_to` + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + _from: string, + _to: string, + _tokenId: BigNumber, + _data: string, + txData?: Partial | undefined, + ): Promise { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + assert.isString('_data', _data); + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('safeTransferFrom(address,address,uint256,bytes)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + _data, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.safeTransferFrom2.estimateGasAsync.bind( + self, + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + _data, + ), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + * @param _data Additional data with no specified format, sent in call to `_to` + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + _from: string, + _to: string, + _tokenId: BigNumber, + _data: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + assert.isString('_data', _data); + const self = (this as any) as DummyERC721TokenContract; + const txHashPromise = self.safeTransferFrom2.sendTransactionAsync( + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + _data, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + * @param _data Additional data with no specified format, sent in call to `_to` + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + _from: string, + _to: string, + _tokenId: BigNumber, + _data: string, + txData?: Partial | undefined, + ): Promise { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + assert.isString('_data', _data); + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('safeTransferFrom(address,address,uint256,bytes)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + _data, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + * @param _data Additional data with no specified format, sent in call to `_to` + */ + async callAsync( + _from: string, + _to: string, + _tokenId: BigNumber, + _data: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + assert.isString('_data', _data); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('safeTransferFrom(address,address,uint256,bytes)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + _data, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('safeTransferFrom(address,address,uint256,bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + * @param _data Additional data with no specified format, sent in call to `_to` + */ + getABIEncodedTransactionData(_from: string, _to: string, _tokenId: BigNumber, _data: string): string { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + assert.isString('_data', _data); + const self = (this as any) as DummyERC721TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'safeTransferFrom(address,address,uint256,bytes)', + [_from.toLowerCase(), _to.toLowerCase(), _tokenId, _data], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('safeTransferFrom(address,address,uint256,bytes)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('safeTransferFrom(address,address,uint256,bytes)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public isApprovedForAll = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _owner The address that owns the NFTs + * @param _operator The address that acts on behalf of the owner + * @returns True if `_operator` is an approved operator for `_owner`, false otherwise + */ + async callAsync( + _owner: string, + _operator: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_owner', _owner); + assert.isString('_operator', _operator); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('isApprovedForAll(address,address)', [ + _owner.toLowerCase(), + _operator.toLowerCase(), + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('isApprovedForAll(address,address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _owner The address that owns the NFTs + * @param _operator The address that acts on behalf of the owner + */ + getABIEncodedTransactionData(_owner: string, _operator: string): string { + assert.isString('_owner', _owner); + assert.isString('_operator', _operator); + const self = (this as any) as DummyERC721TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('isApprovedForAll(address,address)', [ + _owner.toLowerCase(), + _operator.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): boolean { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('isApprovedForAll(address,address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): boolean { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('isApprovedForAll(address,address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public transferOwnership = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(newOwner: string, txData?: Partial | undefined): Promise { + assert.isString('newOwner', newOwner); + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.transferOwnership.estimateGasAsync.bind(self, newOwner.toLowerCase()), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + newOwner: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('newOwner', newOwner); + const self = (this as any) as DummyERC721TokenContract; + const txHashPromise = self.transferOwnership.sendTransactionAsync(newOwner.toLowerCase(), txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(newOwner: string, txData?: Partial | undefined): Promise { + assert.isString('newOwner', newOwner); + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(newOwner: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.isString('newOwner', newOwner); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DummyERC721TokenContract; + const encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(newOwner: string): string { + assert.isString('newOwner', newOwner); + const self = (this as any) as DummyERC721TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('transferOwnership(address)', [ + newOwner.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + private readonly _subscriptionManager: SubscriptionManager; + public static async deployFrom0xArtifactAsync( + artifact: ContractArtifact | SimpleContractArtifact, + supportedProvider: SupportedProvider, + txDefaults: Partial, + logDecodeDependencies: { [contractName: string]: ContractArtifact | SimpleContractArtifact }, + _name: string, + _symbol: string, + ): 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 DummyERC721TokenContract.deployAsync( + bytecode, + abi, + provider, + txDefaults, + logDecodeDependenciesAbiOnly, + _name, + _symbol, + ); + } + public static async deployAsync( + bytecode: string, + abi: ContractAbi, + supportedProvider: SupportedProvider, + txDefaults: Partial, + logDecodeDependencies: { [contractName: string]: ContractAbi }, + _name: string, + _symbol: string, + ): 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); + [_name, _symbol] = BaseContract._formatABIDataItemList( + constructorAbi.inputs, + [_name, _symbol], + BaseContract._bigNumberToString, + ); + const iface = new ethers.utils.Interface(abi); + const deployInfo = iface.deployFunction; + const txData = deployInfo.encode(bytecode, [_name, _symbol]); + const web3Wrapper = new Web3Wrapper(provider); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { 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(`DummyERC721Token successfully deployed at ${txReceipt.contractAddress}`); + const contractInstance = new DummyERC721TokenContract( + txReceipt.contractAddress as string, + provider, + txDefaults, + logDecodeDependencies, + ); + contractInstance.constructorArgs = [_name, _symbol]; + return contractInstance; + } + + /** + * @returns The contract ABI + */ + public static ABI(): ContractAbi { + const abi = [ + { + constant: true, + inputs: [], + name: 'name', + outputs: [ + { + name: '', + type: 'string', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: '_tokenId', + type: 'uint256', + }, + ], + name: 'getApproved', + outputs: [ + { + name: '', + type: 'address', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: '_approved', + type: 'address', + }, + { + name: '_tokenId', + type: 'uint256', + }, + ], + name: 'approve', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: '_from', + type: 'address', + }, + { + name: '_to', + type: 'address', + }, + { + name: '_tokenId', + type: 'uint256', + }, + ], + name: 'transferFrom', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: '_to', + type: 'address', + }, + { + name: '_tokenId', + type: 'uint256', + }, + ], + name: 'mint', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: '_from', + type: 'address', + }, + { + name: '_to', + type: 'address', + }, + { + name: '_tokenId', + type: 'uint256', + }, + ], + name: 'safeTransferFrom', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: '_tokenId', + type: 'uint256', + }, + ], + name: 'ownerOf', + outputs: [ + { + name: '', + type: 'address', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: '_owner', + type: 'address', + }, + ], + name: 'balanceOf', + outputs: [ + { + name: '', + type: 'uint256', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'owner', + outputs: [ + { + name: '', + type: 'address', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'symbol', + outputs: [ + { + name: '', + type: 'string', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: '_owner', + type: 'address', + }, + { + name: '_tokenId', + type: 'uint256', + }, + ], + name: 'burn', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: '_operator', + type: 'address', + }, + { + name: '_approved', + type: 'bool', + }, + ], + name: 'setApprovalForAll', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: '_from', + type: 'address', + }, + { + name: '_to', + type: 'address', + }, + { + name: '_tokenId', + type: 'uint256', + }, + { + name: '_data', + type: 'bytes', + }, + ], + name: 'safeTransferFrom', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: '_owner', + type: 'address', + }, + { + name: '_operator', + type: 'address', + }, + ], + name: 'isApprovedForAll', + outputs: [ + { + name: '', + type: 'bool', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'newOwner', + type: 'address', + }, + ], + name: 'transferOwnership', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + inputs: [ + { + name: '_name', + type: 'string', + }, + { + name: '_symbol', + type: 'string', + }, + ], + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'constructor', + }, + { + anonymous: false, + inputs: [ + { + name: '_from', + type: 'address', + indexed: true, + }, + { + name: '_to', + type: 'address', + indexed: true, + }, + { + name: '_tokenId', + type: 'uint256', + indexed: true, + }, + ], + name: 'Transfer', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: '_owner', + type: 'address', + indexed: true, + }, + { + name: '_approved', + type: 'address', + indexed: true, + }, + { + name: '_tokenId', + type: 'uint256', + indexed: true, + }, + ], + name: 'Approval', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: '_owner', + type: 'address', + indexed: true, + }, + { + name: '_operator', + type: 'address', + indexed: true, + }, + { + name: '_approved', + type: 'bool', + indexed: false, + }, + ], + name: 'ApprovalForAll', + outputs: [], + type: 'event', + }, + ] as ContractAbi; + return abi; + } + /** + * Subscribe to an event type emitted by the DummyERC721Token contract. + * @param eventName The DummyERC721Token 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: DummyERC721TokenEvents, + indexFilterValues: IndexedFilterValues, + callback: EventCallback, + isVerbose: boolean = false, + blockPollingIntervalMs?: number, + ): string { + assert.doesBelongToStringEnum('eventName', eventName, DummyERC721TokenEvents); + assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); + assert.isFunction('callback', callback); + const subscriptionToken = this._subscriptionManager.subscribe( + this.address, + eventName, + indexFilterValues, + DummyERC721TokenContract.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 DummyERC721Token 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: DummyERC721TokenEvents, + blockRange: BlockRange, + indexFilterValues: IndexedFilterValues, + ): Promise>> { + assert.doesBelongToStringEnum('eventName', eventName, DummyERC721TokenEvents); + assert.doesConformToSchema('blockRange', blockRange, schemas.blockRangeSchema); + assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); + const logs = await this._subscriptionManager.getLogsAsync( + this.address, + eventName, + blockRange, + indexFilterValues, + DummyERC721TokenContract.ABI(), + ); + return logs; + } + constructor( + address: string, + supportedProvider: SupportedProvider, + txDefaults?: Partial, + logDecodeDependencies?: { [contractName: string]: ContractAbi }, + ) { + super( + 'DummyERC721Token', + DummyERC721TokenContract.ABI(), + address, + supportedProvider, + txDefaults, + logDecodeDependencies, + ); + classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + this._subscriptionManager = new SubscriptionManager( + DummyERC721TokenContract.ABI(), + this._web3Wrapper, + ); + } +} + +// 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/contract-wrappers/src/generated-wrappers/dutch_auction.ts b/packages/contract-wrappers/src/generated-wrappers/dutch_auction.ts new file mode 100644 index 0000000000..b4ab61b8de --- /dev/null +++ b/packages/contract-wrappers/src/generated-wrappers/dutch_auction.ts @@ -0,0 +1,1172 @@ +// tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma +// tslint:disable:whitespace no-unbound-method no-trailing-whitespace +// tslint:disable:no-unused-variable +import { BaseContract, PromiseWithTransactionHash } from '@0x/base-contract'; +import { schemas } from '@0x/json-schemas'; +import { + BlockParam, + BlockParamLiteral, + CallData, + ContractAbi, + ContractArtifact, + DecodedLogArgs, + MethodAbi, + TransactionReceiptWithDecodedLogs, + TxData, + TxDataPayable, + SupportedProvider, +} from 'ethereum-types'; +import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; +import { 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:no-parameter-reassignment +// tslint:disable-next-line:class-name +export class DutchAuctionContract extends BaseContract { + /** + * Calculates the Auction Details for the given order + */ + public getAuctionDetails = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param order The sell order + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + txData?: Partial | undefined, + ): Promise { + const self = (this as any) as DutchAuctionContract; + const encodedData = self._strictEncodeArguments( + 'getAuctionDetails((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes))', + [order], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.getAuctionDetails.estimateGasAsync.bind(self, order), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param order The sell order + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + const self = (this as any) as DutchAuctionContract; + const txHashPromise = self.getAuctionDetails.sendTransactionAsync(order, txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param order The sell order + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + txData?: Partial | undefined, + ): Promise { + const self = (this as any) as DutchAuctionContract; + const encodedData = self._strictEncodeArguments( + 'getAuctionDetails((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes))', + [order], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param order The sell order + * @returns AuctionDetails + */ + async callAsync( + order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ + beginTimeSeconds: BigNumber; + endTimeSeconds: BigNumber; + beginAmount: BigNumber; + endAmount: BigNumber; + currentAmount: BigNumber; + currentTimeSeconds: BigNumber; + }> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DutchAuctionContract; + const encodedData = self._strictEncodeArguments( + 'getAuctionDetails((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes))', + [order], + ); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'getAuctionDetails((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes))', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + beginTimeSeconds: BigNumber; + endTimeSeconds: BigNumber; + beginAmount: BigNumber; + endAmount: BigNumber; + currentAmount: BigNumber; + currentTimeSeconds: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param order The sell order + */ + getABIEncodedTransactionData(order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }): string { + const self = (this as any) as DutchAuctionContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'getAuctionDetails((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes))', + [order], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData( + callData: string, + ): { + beginTimeSeconds: BigNumber; + endTimeSeconds: BigNumber; + beginAmount: BigNumber; + endAmount: BigNumber; + currentAmount: BigNumber; + currentTimeSeconds: BigNumber; + } { + const self = (this as any) as DutchAuctionContract; + const abiEncoder = self._lookupAbiEncoder( + 'getAuctionDetails((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes))', + ); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode<{ + beginTimeSeconds: BigNumber; + endTimeSeconds: BigNumber; + beginAmount: BigNumber; + endAmount: BigNumber; + currentAmount: BigNumber; + currentTimeSeconds: BigNumber; + }>(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData( + returnData: string, + ): { + beginTimeSeconds: BigNumber; + endTimeSeconds: BigNumber; + beginAmount: BigNumber; + endAmount: BigNumber; + currentAmount: BigNumber; + currentTimeSeconds: BigNumber; + } { + const self = (this as any) as DutchAuctionContract; + const abiEncoder = self._lookupAbiEncoder( + 'getAuctionDetails((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes))', + ); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue<{ + beginTimeSeconds: BigNumber; + endTimeSeconds: BigNumber; + beginAmount: BigNumber; + endAmount: BigNumber; + currentAmount: BigNumber; + currentTimeSeconds: BigNumber; + }>(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Matches the buy and sell orders at an amount given the following: the current block time, the auction + * start time and the auction begin amount. The sell order is a an order at the lowest amount + * at the end of the auction. Excess from the match is transferred to the seller. + * Over time the price moves from beginAmount to endAmount given the current block.timestamp. + * sellOrder.expiryTimeSeconds is the end time of the auction. + * sellOrder.takerAssetAmount is the end amount of the auction (lowest possible amount). + * sellOrder.makerAssetData is the ABI encoded Asset Proxy data with the following data appended + * buyOrder.makerAssetData is the buyers bid on the auction, must meet the amount for the current block timestamp + * (uint256 beginTimeSeconds, uint256 beginAmount). + * This function reverts in the following scenarios: + * * Auction has not started (auctionDetails.currentTimeSeconds < auctionDetails.beginTimeSeconds) + * * Auction has expired (auctionDetails.endTimeSeconds < auctionDetails.currentTimeSeconds) + * * Amount is invalid: Buy order amount is too low (buyOrder.makerAssetAmount < auctionDetails.currentAmount) + * * Amount is invalid: Invalid begin amount (auctionDetails.beginAmount > auctionDetails.endAmount) + * * Any failure in the 0x Match Orders + */ + public matchOrders = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param buyOrder The Buyer's order. This order is for the current expected + * price of the auction. + * @param sellOrder The Seller's order. This order is for the lowest amount (at + * the end of the auction). + * @param buySignature Proof that order was created by the buyer. + * @param sellSignature Proof that order was created by the seller. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + buyOrder: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + sellOrder: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + buySignature: string, + sellSignature: string, + txData?: Partial | undefined, + ): Promise { + assert.isString('buySignature', buySignature); + assert.isString('sellSignature', sellSignature); + const self = (this as any) as DutchAuctionContract; + const encodedData = self._strictEncodeArguments( + 'matchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),bytes,bytes)', + [buyOrder, sellOrder, buySignature, sellSignature], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.matchOrders.estimateGasAsync.bind(self, buyOrder, sellOrder, buySignature, sellSignature), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param buyOrder The Buyer's order. This order is for the current expected + * price of the auction. + * @param sellOrder The Seller's order. This order is for the lowest amount (at + * the end of the auction). + * @param buySignature Proof that order was created by the buyer. + * @param sellSignature Proof that order was created by the seller. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + buyOrder: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + sellOrder: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + buySignature: string, + sellSignature: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('buySignature', buySignature); + assert.isString('sellSignature', sellSignature); + const self = (this as any) as DutchAuctionContract; + const txHashPromise = self.matchOrders.sendTransactionAsync( + buyOrder, + sellOrder, + buySignature, + sellSignature, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param buyOrder The Buyer's order. This order is for the current expected + * price of the auction. + * @param sellOrder The Seller's order. This order is for the lowest amount (at + * the end of the auction). + * @param buySignature Proof that order was created by the buyer. + * @param sellSignature Proof that order was created by the seller. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + buyOrder: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + sellOrder: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + buySignature: string, + sellSignature: string, + txData?: Partial | undefined, + ): Promise { + assert.isString('buySignature', buySignature); + assert.isString('sellSignature', sellSignature); + const self = (this as any) as DutchAuctionContract; + const encodedData = self._strictEncodeArguments( + 'matchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),bytes,bytes)', + [buyOrder, sellOrder, buySignature, sellSignature], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param buyOrder The Buyer's order. This order is for the current expected + * price of the auction. + * @param sellOrder The Seller's order. This order is for the lowest amount (at + * the end of the auction). + * @param buySignature Proof that order was created by the buyer. + * @param sellSignature Proof that order was created by the seller. + * @returns matchedFillResults amounts filled and fees paid by maker and taker of matched orders. + */ + async callAsync( + buyOrder: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + sellOrder: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + buySignature: string, + sellSignature: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ + left: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }; + right: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }; + leftMakerAssetSpreadAmount: BigNumber; + }> { + assert.isString('buySignature', buySignature); + assert.isString('sellSignature', sellSignature); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as DutchAuctionContract; + const encodedData = self._strictEncodeArguments( + 'matchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),bytes,bytes)', + [buyOrder, sellOrder, buySignature, sellSignature], + ); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'matchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),bytes,bytes)', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + left: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }; + right: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }; + leftMakerAssetSpreadAmount: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param buyOrder The Buyer's order. This order is for the current expected + * price of the auction. + * @param sellOrder The Seller's order. This order is for the lowest amount (at + * the end of the auction). + * @param buySignature Proof that order was created by the buyer. + * @param sellSignature Proof that order was created by the seller. + */ + getABIEncodedTransactionData( + buyOrder: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + sellOrder: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + buySignature: string, + sellSignature: string, + ): string { + assert.isString('buySignature', buySignature); + assert.isString('sellSignature', sellSignature); + const self = (this as any) as DutchAuctionContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'matchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),bytes,bytes)', + [buyOrder, sellOrder, buySignature, sellSignature], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData( + callData: string, + ): { + left: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }; + right: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }; + leftMakerAssetSpreadAmount: BigNumber; + } { + const self = (this as any) as DutchAuctionContract; + const abiEncoder = self._lookupAbiEncoder( + 'matchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),bytes,bytes)', + ); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode<{ + left: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }; + right: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }; + leftMakerAssetSpreadAmount: BigNumber; + }>(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData( + returnData: string, + ): { + left: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }; + right: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }; + leftMakerAssetSpreadAmount: BigNumber; + } { + const self = (this as any) as DutchAuctionContract; + const abiEncoder = self._lookupAbiEncoder( + 'matchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),bytes,bytes)', + ); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue<{ + left: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }; + right: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }; + leftMakerAssetSpreadAmount: BigNumber; + }>(returnData); + return abiDecodedReturnData; + }, + }; + public static async deployFrom0xArtifactAsync( + artifact: ContractArtifact | SimpleContractArtifact, + supportedProvider: SupportedProvider, + txDefaults: Partial, + logDecodeDependencies: { [contractName: string]: ContractArtifact | SimpleContractArtifact }, + _exchange: string, + ): 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 DutchAuctionContract.deployAsync( + bytecode, + abi, + provider, + txDefaults, + logDecodeDependenciesAbiOnly, + _exchange, + ); + } + public static async deployAsync( + bytecode: string, + abi: ContractAbi, + supportedProvider: SupportedProvider, + txDefaults: Partial, + logDecodeDependencies: { [contractName: string]: ContractAbi }, + _exchange: string, + ): 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); + [_exchange] = BaseContract._formatABIDataItemList( + constructorAbi.inputs, + [_exchange], + BaseContract._bigNumberToString, + ); + const iface = new ethers.utils.Interface(abi); + const deployInfo = iface.deployFunction; + const txData = deployInfo.encode(bytecode, [_exchange]); + const web3Wrapper = new Web3Wrapper(provider); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { 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(`DutchAuction successfully deployed at ${txReceipt.contractAddress}`); + const contractInstance = new DutchAuctionContract( + txReceipt.contractAddress as string, + provider, + txDefaults, + logDecodeDependencies, + ); + contractInstance.constructorArgs = [_exchange]; + return contractInstance; + } + + /** + * @returns The contract ABI + */ + public static ABI(): ContractAbi { + const abi = [ + { + constant: false, + inputs: [ + { + name: 'order', + type: 'tuple', + 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: 'getAuctionDetails', + outputs: [ + { + name: 'auctionDetails', + type: 'tuple', + components: [ + { + name: 'beginTimeSeconds', + type: 'uint256', + }, + { + name: 'endTimeSeconds', + type: 'uint256', + }, + { + name: 'beginAmount', + type: 'uint256', + }, + { + name: 'endAmount', + type: 'uint256', + }, + { + name: 'currentAmount', + type: 'uint256', + }, + { + name: 'currentTimeSeconds', + type: 'uint256', + }, + ], + }, + ], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'buyOrder', + type: 'tuple', + 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: 'sellOrder', + type: 'tuple', + 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: 'buySignature', + type: 'bytes', + }, + { + name: 'sellSignature', + type: 'bytes', + }, + ], + name: 'matchOrders', + outputs: [ + { + name: 'matchedFillResults', + type: 'tuple', + components: [ + { + name: 'left', + type: 'tuple', + components: [ + { + name: 'makerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'takerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'makerFeePaid', + type: 'uint256', + }, + { + name: 'takerFeePaid', + type: 'uint256', + }, + ], + }, + { + name: 'right', + type: 'tuple', + components: [ + { + name: 'makerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'takerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'makerFeePaid', + type: 'uint256', + }, + { + name: 'takerFeePaid', + type: 'uint256', + }, + ], + }, + { + name: 'leftMakerAssetSpreadAmount', + type: 'uint256', + }, + ], + }, + ], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + inputs: [ + { + name: '_exchange', + type: 'address', + }, + ], + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'constructor', + }, + ] as ContractAbi; + return abi; + } + constructor( + address: string, + supportedProvider: SupportedProvider, + txDefaults?: Partial, + logDecodeDependencies?: { [contractName: string]: ContractAbi }, + ) { + super( + 'DutchAuction', + DutchAuctionContract.ABI(), + address, + supportedProvider, + txDefaults, + logDecodeDependencies, + ); + classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + } +} + +// 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/contract-wrappers/src/generated-wrappers/erc20_proxy.ts b/packages/contract-wrappers/src/generated-wrappers/erc20_proxy.ts new file mode 100644 index 0000000000..0b9f9752cd --- /dev/null +++ b/packages/contract-wrappers/src/generated-wrappers/erc20_proxy.ts @@ -0,0 +1,1368 @@ +// tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma +// tslint:disable:whitespace no-unbound-method no-trailing-whitespace +// tslint:disable:no-unused-variable +import { + BaseContract, + BlockRange, + EventCallback, + IndexedFilterValues, + SubscriptionManager, + PromiseWithTransactionHash, +} from '@0x/base-contract'; +import { schemas } from '@0x/json-schemas'; +import { + BlockParam, + BlockParamLiteral, + CallData, + ContractAbi, + ContractArtifact, + DecodedLogArgs, + LogWithDecodedArgs, + MethodAbi, + TransactionReceiptWithDecodedLogs, + TxData, + TxDataPayable, + SupportedProvider, +} from 'ethereum-types'; +import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; +import { 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 ERC20ProxyEventArgs = + | ERC20ProxyAuthorizedAddressAddedEventArgs + | ERC20ProxyAuthorizedAddressRemovedEventArgs; + +export enum ERC20ProxyEvents { + AuthorizedAddressAdded = 'AuthorizedAddressAdded', + AuthorizedAddressRemoved = 'AuthorizedAddressRemoved', +} + +export interface ERC20ProxyAuthorizedAddressAddedEventArgs extends DecodedLogArgs { + target: string; + caller: string; +} + +export interface ERC20ProxyAuthorizedAddressRemovedEventArgs extends DecodedLogArgs { + target: string; + caller: string; +} + +/* istanbul ignore next */ +// tslint:disable:no-parameter-reassignment +// tslint:disable-next-line:class-name +export class ERC20ProxyContract extends BaseContract { + /** + * Authorizes an address. + */ + public addAuthorizedAddress = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param target Address to authorize. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(target: string, txData?: Partial | undefined): Promise { + assert.isString('target', target); + const self = (this as any) as ERC20ProxyContract; + const encodedData = self._strictEncodeArguments('addAuthorizedAddress(address)', [target.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.addAuthorizedAddress.estimateGasAsync.bind(self, target.toLowerCase()), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param target Address to authorize. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + target: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('target', target); + const self = (this as any) as ERC20ProxyContract; + const txHashPromise = self.addAuthorizedAddress.sendTransactionAsync(target.toLowerCase(), txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param target Address to authorize. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(target: string, txData?: Partial | undefined): Promise { + assert.isString('target', target); + const self = (this as any) as ERC20ProxyContract; + const encodedData = self._strictEncodeArguments('addAuthorizedAddress(address)', [target.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param target Address to authorize. + */ + async callAsync(target: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.isString('target', target); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC20ProxyContract; + const encodedData = self._strictEncodeArguments('addAuthorizedAddress(address)', [target.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('addAuthorizedAddress(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param target Address to authorize. + */ + getABIEncodedTransactionData(target: string): string { + assert.isString('target', target); + const self = (this as any) as ERC20ProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('addAuthorizedAddress(address)', [ + target.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as ERC20ProxyContract; + const abiEncoder = self._lookupAbiEncoder('addAuthorizedAddress(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as ERC20ProxyContract; + const abiEncoder = self._lookupAbiEncoder('addAuthorizedAddress(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public authorities = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + index_0: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isBigNumber('index_0', index_0); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC20ProxyContract; + const encodedData = self._strictEncodeArguments('authorities(uint256)', [index_0]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('authorities(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(index_0: BigNumber): string { + assert.isBigNumber('index_0', index_0); + const self = (this as any) as ERC20ProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('authorities(uint256)', [index_0]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as ERC20ProxyContract; + const abiEncoder = self._lookupAbiEncoder('authorities(uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as ERC20ProxyContract; + const abiEncoder = self._lookupAbiEncoder('authorities(uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Removes authorizion of an address. + */ + public removeAuthorizedAddress = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param target Address to remove authorization from. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(target: string, txData?: Partial | undefined): Promise { + assert.isString('target', target); + const self = (this as any) as ERC20ProxyContract; + const encodedData = self._strictEncodeArguments('removeAuthorizedAddress(address)', [target.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.removeAuthorizedAddress.estimateGasAsync.bind(self, target.toLowerCase()), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param target Address to remove authorization from. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + target: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('target', target); + const self = (this as any) as ERC20ProxyContract; + const txHashPromise = self.removeAuthorizedAddress.sendTransactionAsync(target.toLowerCase(), txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param target Address to remove authorization from. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(target: string, txData?: Partial | undefined): Promise { + assert.isString('target', target); + const self = (this as any) as ERC20ProxyContract; + const encodedData = self._strictEncodeArguments('removeAuthorizedAddress(address)', [target.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param target Address to remove authorization from. + */ + async callAsync(target: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.isString('target', target); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC20ProxyContract; + const encodedData = self._strictEncodeArguments('removeAuthorizedAddress(address)', [target.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddress(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param target Address to remove authorization from. + */ + getABIEncodedTransactionData(target: string): string { + assert.isString('target', target); + const self = (this as any) as ERC20ProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('removeAuthorizedAddress(address)', [ + target.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as ERC20ProxyContract; + const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddress(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as ERC20ProxyContract; + const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddress(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public owner = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC20ProxyContract; + const encodedData = self._strictEncodeArguments('owner()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('owner()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as ERC20ProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('owner()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as ERC20ProxyContract; + const abiEncoder = self._lookupAbiEncoder('owner()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as ERC20ProxyContract; + const abiEncoder = self._lookupAbiEncoder('owner()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Removes authorizion of an address. + */ + public removeAuthorizedAddressAtIndex = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param target Address to remove authorization from. + * @param index Index of target in authorities array. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + target: string, + index: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('target', target); + assert.isBigNumber('index', index); + const self = (this as any) as ERC20ProxyContract; + const encodedData = self._strictEncodeArguments('removeAuthorizedAddressAtIndex(address,uint256)', [ + target.toLowerCase(), + index, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.removeAuthorizedAddressAtIndex.estimateGasAsync.bind(self, target.toLowerCase(), index), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param target Address to remove authorization from. + * @param index Index of target in authorities array. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + target: string, + index: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('target', target); + assert.isBigNumber('index', index); + const self = (this as any) as ERC20ProxyContract; + const txHashPromise = self.removeAuthorizedAddressAtIndex.sendTransactionAsync( + target.toLowerCase(), + index, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param target Address to remove authorization from. + * @param index Index of target in authorities array. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + target: string, + index: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('target', target); + assert.isBigNumber('index', index); + const self = (this as any) as ERC20ProxyContract; + const encodedData = self._strictEncodeArguments('removeAuthorizedAddressAtIndex(address,uint256)', [ + target.toLowerCase(), + index, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param target Address to remove authorization from. + * @param index Index of target in authorities array. + */ + async callAsync( + target: string, + index: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('target', target); + assert.isBigNumber('index', index); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC20ProxyContract; + const encodedData = self._strictEncodeArguments('removeAuthorizedAddressAtIndex(address,uint256)', [ + target.toLowerCase(), + index, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddressAtIndex(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param target Address to remove authorization from. + * @param index Index of target in authorities array. + */ + getABIEncodedTransactionData(target: string, index: BigNumber): string { + assert.isString('target', target); + assert.isBigNumber('index', index); + const self = (this as any) as ERC20ProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'removeAuthorizedAddressAtIndex(address,uint256)', + [target.toLowerCase(), index], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as ERC20ProxyContract; + const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddressAtIndex(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as ERC20ProxyContract; + const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddressAtIndex(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Gets the proxy id associated with the proxy address. + */ + public getProxyId = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @returns Proxy id. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC20ProxyContract; + const encodedData = self._strictEncodeArguments('getProxyId()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getProxyId()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as ERC20ProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('getProxyId()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as ERC20ProxyContract; + const abiEncoder = self._lookupAbiEncoder('getProxyId()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as ERC20ProxyContract; + const abiEncoder = self._lookupAbiEncoder('getProxyId()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public authorized = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + index_0: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('index_0', index_0); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC20ProxyContract; + const encodedData = self._strictEncodeArguments('authorized(address)', [index_0.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('authorized(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(index_0: string): string { + assert.isString('index_0', index_0); + const self = (this as any) as ERC20ProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('authorized(address)', [ + index_0.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): boolean { + const self = (this as any) as ERC20ProxyContract; + const abiEncoder = self._lookupAbiEncoder('authorized(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): boolean { + const self = (this as any) as ERC20ProxyContract; + const abiEncoder = self._lookupAbiEncoder('authorized(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Gets all authorized addresses. + */ + public getAuthorizedAddresses = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @returns Array of authorized addresses. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC20ProxyContract; + const encodedData = self._strictEncodeArguments('getAuthorizedAddresses()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getAuthorizedAddresses()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as ERC20ProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('getAuthorizedAddresses()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string[] { + const self = (this as any) as ERC20ProxyContract; + const abiEncoder = self._lookupAbiEncoder('getAuthorizedAddresses()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string[] { + const self = (this as any) as ERC20ProxyContract; + const abiEncoder = self._lookupAbiEncoder('getAuthorizedAddresses()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public transferOwnership = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(newOwner: string, txData?: Partial | undefined): Promise { + assert.isString('newOwner', newOwner); + const self = (this as any) as ERC20ProxyContract; + const encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.transferOwnership.estimateGasAsync.bind(self, newOwner.toLowerCase()), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + newOwner: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('newOwner', newOwner); + const self = (this as any) as ERC20ProxyContract; + const txHashPromise = self.transferOwnership.sendTransactionAsync(newOwner.toLowerCase(), txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(newOwner: string, txData?: Partial | undefined): Promise { + assert.isString('newOwner', newOwner); + const self = (this as any) as ERC20ProxyContract; + const encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(newOwner: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.isString('newOwner', newOwner); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC20ProxyContract; + const encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(newOwner: string): string { + assert.isString('newOwner', newOwner); + const self = (this as any) as ERC20ProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('transferOwnership(address)', [ + newOwner.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as ERC20ProxyContract; + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as ERC20ProxyContract; + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + 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 ERC20ProxyContract.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._applyDefaultsToTxDataAsync( + { 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(`ERC20Proxy successfully deployed at ${txReceipt.contractAddress}`); + const contractInstance = new ERC20ProxyContract( + txReceipt.contractAddress as string, + provider, + txDefaults, + logDecodeDependencies, + ); + contractInstance.constructorArgs = []; + return contractInstance; + } + + /** + * @returns The contract ABI + */ + public static ABI(): ContractAbi { + const abi = [ + { + constant: false, + inputs: [ + { + name: 'target', + type: 'address', + }, + ], + name: 'addAuthorizedAddress', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'index_0', + type: 'uint256', + }, + ], + name: 'authorities', + outputs: [ + { + name: '', + type: 'address', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'target', + type: 'address', + }, + ], + name: 'removeAuthorizedAddress', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'owner', + outputs: [ + { + name: '', + type: 'address', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'target', + type: 'address', + }, + { + name: 'index', + type: 'uint256', + }, + ], + name: 'removeAuthorizedAddressAtIndex', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'getProxyId', + outputs: [ + { + name: '', + type: 'bytes4', + }, + ], + payable: false, + stateMutability: 'pure', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'index_0', + type: 'address', + }, + ], + name: 'authorized', + outputs: [ + { + name: '', + type: 'bool', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'getAuthorizedAddresses', + outputs: [ + { + name: '', + type: 'address[]', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'newOwner', + type: 'address', + }, + ], + name: 'transferOwnership', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + inputs: [], + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'fallback', + }, + { + anonymous: false, + inputs: [ + { + name: 'target', + type: 'address', + indexed: true, + }, + { + name: 'caller', + type: 'address', + indexed: true, + }, + ], + name: 'AuthorizedAddressAdded', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: 'target', + type: 'address', + indexed: true, + }, + { + name: 'caller', + type: 'address', + indexed: true, + }, + ], + name: 'AuthorizedAddressRemoved', + outputs: [], + type: 'event', + }, + ] as ContractAbi; + return abi; + } + /** + * Subscribe to an event type emitted by the ERC20Proxy contract. + * @param eventName The ERC20Proxy 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: ERC20ProxyEvents, + indexFilterValues: IndexedFilterValues, + callback: EventCallback, + isVerbose: boolean = false, + blockPollingIntervalMs?: number, + ): string { + assert.doesBelongToStringEnum('eventName', eventName, ERC20ProxyEvents); + assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); + assert.isFunction('callback', callback); + const subscriptionToken = this._subscriptionManager.subscribe( + this.address, + eventName, + indexFilterValues, + ERC20ProxyContract.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 ERC20Proxy 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: ERC20ProxyEvents, + blockRange: BlockRange, + indexFilterValues: IndexedFilterValues, + ): Promise>> { + assert.doesBelongToStringEnum('eventName', eventName, ERC20ProxyEvents); + assert.doesConformToSchema('blockRange', blockRange, schemas.blockRangeSchema); + assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); + const logs = await this._subscriptionManager.getLogsAsync( + this.address, + eventName, + blockRange, + indexFilterValues, + ERC20ProxyContract.ABI(), + ); + return logs; + } + constructor( + address: string, + supportedProvider: SupportedProvider, + txDefaults?: Partial, + logDecodeDependencies?: { [contractName: string]: ContractAbi }, + ) { + super('ERC20Proxy', ERC20ProxyContract.ABI(), address, supportedProvider, txDefaults, logDecodeDependencies); + classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + this._subscriptionManager = new SubscriptionManager( + ERC20ProxyContract.ABI(), + this._web3Wrapper, + ); + } +} + +// 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/contract-wrappers/src/generated-wrappers/erc20_token.ts b/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts new file mode 100644 index 0000000000..e910137065 --- /dev/null +++ b/packages/contract-wrappers/src/generated-wrappers/erc20_token.ts @@ -0,0 +1,1183 @@ +// tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma +// tslint:disable:whitespace no-unbound-method no-trailing-whitespace +// tslint:disable:no-unused-variable +import { + BaseContract, + BlockRange, + EventCallback, + IndexedFilterValues, + SubscriptionManager, + PromiseWithTransactionHash, +} from '@0x/base-contract'; +import { schemas } from '@0x/json-schemas'; +import { + BlockParam, + BlockParamLiteral, + CallData, + ContractAbi, + ContractArtifact, + DecodedLogArgs, + LogWithDecodedArgs, + MethodAbi, + TransactionReceiptWithDecodedLogs, + TxData, + TxDataPayable, + SupportedProvider, +} from 'ethereum-types'; +import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; +import { 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 ERC20TokenEventArgs = ERC20TokenTransferEventArgs | ERC20TokenApprovalEventArgs; + +export enum ERC20TokenEvents { + Transfer = 'Transfer', + Approval = 'Approval', +} + +export interface ERC20TokenTransferEventArgs extends DecodedLogArgs { + _from: string; + _to: string; + _value: BigNumber; +} + +export interface ERC20TokenApprovalEventArgs extends DecodedLogArgs { + _owner: string; + _spender: string; + _value: BigNumber; +} + +/* istanbul ignore next */ +// tslint:disable:no-parameter-reassignment +// tslint:disable-next-line:class-name +export class ERC20TokenContract extends BaseContract { + /** + * `msg.sender` approves `_spender` to spend `_value` tokens + */ + public approve = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param _spender The address of the account able to transfer the tokens + * @param _value The amount of wei to be approved for transfer + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + _spender: string, + _value: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_spender', _spender); + assert.isBigNumber('_value', _value); + const self = (this as any) as ERC20TokenContract; + const encodedData = self._strictEncodeArguments('approve(address,uint256)', [ + _spender.toLowerCase(), + _value, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.approve.estimateGasAsync.bind(self, _spender.toLowerCase(), _value), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param _spender The address of the account able to transfer the tokens + * @param _value The amount of wei to be approved for transfer + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + _spender: string, + _value: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('_spender', _spender); + assert.isBigNumber('_value', _value); + const self = (this as any) as ERC20TokenContract; + const txHashPromise = self.approve.sendTransactionAsync(_spender.toLowerCase(), _value, txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param _spender The address of the account able to transfer the tokens + * @param _value The amount of wei to be approved for transfer + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + _spender: string, + _value: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_spender', _spender); + assert.isBigNumber('_value', _value); + const self = (this as any) as ERC20TokenContract; + const encodedData = self._strictEncodeArguments('approve(address,uint256)', [ + _spender.toLowerCase(), + _value, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _spender The address of the account able to transfer the tokens + * @param _value The amount of wei to be approved for transfer + * @returns Always true if the call has enough gas to complete execution + */ + async callAsync( + _spender: string, + _value: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_spender', _spender); + assert.isBigNumber('_value', _value); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC20TokenContract; + const encodedData = self._strictEncodeArguments('approve(address,uint256)', [ + _spender.toLowerCase(), + _value, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('approve(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _spender The address of the account able to transfer the tokens + * @param _value The amount of wei to be approved for transfer + */ + getABIEncodedTransactionData(_spender: string, _value: BigNumber): string { + assert.isString('_spender', _spender); + assert.isBigNumber('_value', _value); + const self = (this as any) as ERC20TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('approve(address,uint256)', [ + _spender.toLowerCase(), + _value, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): boolean { + const self = (this as any) as ERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('approve(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): boolean { + const self = (this as any) as ERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('approve(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Query total supply of token + */ + public totalSupply = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @returns Total supply of token + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC20TokenContract; + const encodedData = self._strictEncodeArguments('totalSupply()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('totalSupply()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as ERC20TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('totalSupply()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): BigNumber { + const self = (this as any) as ERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('totalSupply()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): BigNumber { + const self = (this as any) as ERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('totalSupply()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * send `value` token to `to` from `from` on the condition it is approved by `from` + */ + public transferFrom = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param _from The address of the sender + * @param _to The address of the recipient + * @param _value The amount of token to be transferred + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + _from: string, + _to: string, + _value: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + const self = (this as any) as ERC20TokenContract; + const encodedData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _value, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.transferFrom.estimateGasAsync.bind(self, _from.toLowerCase(), _to.toLowerCase(), _value), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param _from The address of the sender + * @param _to The address of the recipient + * @param _value The amount of token to be transferred + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + _from: string, + _to: string, + _value: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + const self = (this as any) as ERC20TokenContract; + const txHashPromise = self.transferFrom.sendTransactionAsync( + _from.toLowerCase(), + _to.toLowerCase(), + _value, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param _from The address of the sender + * @param _to The address of the recipient + * @param _value The amount of token to be transferred + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + _from: string, + _to: string, + _value: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + const self = (this as any) as ERC20TokenContract; + const encodedData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _value, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _from The address of the sender + * @param _to The address of the recipient + * @param _value The amount of token to be transferred + * @returns True if transfer was successful + */ + async callAsync( + _from: string, + _to: string, + _value: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC20TokenContract; + const encodedData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _value, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _from The address of the sender + * @param _to The address of the recipient + * @param _value The amount of token to be transferred + */ + getABIEncodedTransactionData(_from: string, _to: string, _value: BigNumber): string { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + const self = (this as any) as ERC20TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _value, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): boolean { + const self = (this as any) as ERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('transferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): boolean { + const self = (this as any) as ERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('transferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Query the balance of owner + */ + public balanceOf = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _owner The address from which the balance will be retrieved + * @returns Balance of owner + */ + async callAsync( + _owner: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_owner', _owner); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC20TokenContract; + const encodedData = self._strictEncodeArguments('balanceOf(address)', [_owner.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('balanceOf(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _owner The address from which the balance will be retrieved + */ + getABIEncodedTransactionData(_owner: string): string { + assert.isString('_owner', _owner); + const self = (this as any) as ERC20TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('balanceOf(address)', [_owner.toLowerCase()]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): BigNumber { + const self = (this as any) as ERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('balanceOf(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): BigNumber { + const self = (this as any) as ERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('balanceOf(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * send `value` token to `to` from `msg.sender` + */ + public transfer = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param _to The address of the recipient + * @param _value The amount of token to be transferred + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + _to: string, + _value: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + const self = (this as any) as ERC20TokenContract; + const encodedData = self._strictEncodeArguments('transfer(address,uint256)', [_to.toLowerCase(), _value]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.transfer.estimateGasAsync.bind(self, _to.toLowerCase(), _value), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param _to The address of the recipient + * @param _value The amount of token to be transferred + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + _to: string, + _value: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + const self = (this as any) as ERC20TokenContract; + const txHashPromise = self.transfer.sendTransactionAsync(_to.toLowerCase(), _value, txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param _to The address of the recipient + * @param _value The amount of token to be transferred + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(_to: string, _value: BigNumber, txData?: Partial | undefined): Promise { + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + const self = (this as any) as ERC20TokenContract; + const encodedData = self._strictEncodeArguments('transfer(address,uint256)', [_to.toLowerCase(), _value]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _to The address of the recipient + * @param _value The amount of token to be transferred + * @returns True if transfer was successful + */ + async callAsync( + _to: string, + _value: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC20TokenContract; + const encodedData = self._strictEncodeArguments('transfer(address,uint256)', [_to.toLowerCase(), _value]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transfer(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _to The address of the recipient + * @param _value The amount of token to be transferred + */ + getABIEncodedTransactionData(_to: string, _value: BigNumber): string { + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + const self = (this as any) as ERC20TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('transfer(address,uint256)', [ + _to.toLowerCase(), + _value, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): boolean { + const self = (this as any) as ERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('transfer(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): boolean { + const self = (this as any) as ERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('transfer(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public allowance = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _owner The address of the account owning tokens + * @param _spender The address of the account able to transfer the tokens + * @returns Amount of remaining tokens allowed to spent + */ + async callAsync( + _owner: string, + _spender: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_owner', _owner); + assert.isString('_spender', _spender); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC20TokenContract; + const encodedData = self._strictEncodeArguments('allowance(address,address)', [ + _owner.toLowerCase(), + _spender.toLowerCase(), + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('allowance(address,address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _owner The address of the account owning tokens + * @param _spender The address of the account able to transfer the tokens + */ + getABIEncodedTransactionData(_owner: string, _spender: string): string { + assert.isString('_owner', _owner); + assert.isString('_spender', _spender); + const self = (this as any) as ERC20TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('allowance(address,address)', [ + _owner.toLowerCase(), + _spender.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): BigNumber { + const self = (this as any) as ERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('allowance(address,address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): BigNumber { + const self = (this as any) as ERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder('allowance(address,address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + 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 ERC20TokenContract.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._applyDefaultsToTxDataAsync( + { 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(`ERC20Token successfully deployed at ${txReceipt.contractAddress}`); + const contractInstance = new ERC20TokenContract( + txReceipt.contractAddress as string, + provider, + txDefaults, + logDecodeDependencies, + ); + contractInstance.constructorArgs = []; + return contractInstance; + } + + /** + * @returns The contract ABI + */ + public static ABI(): ContractAbi { + const abi = [ + { + constant: false, + inputs: [ + { + name: '_spender', + type: 'address', + }, + { + name: '_value', + type: 'uint256', + }, + ], + name: 'approve', + outputs: [ + { + name: '', + type: 'bool', + }, + ], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'totalSupply', + outputs: [ + { + name: '', + type: 'uint256', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: '_from', + type: 'address', + }, + { + name: '_to', + type: 'address', + }, + { + name: '_value', + type: 'uint256', + }, + ], + name: 'transferFrom', + outputs: [ + { + name: '', + type: 'bool', + }, + ], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: '_owner', + type: 'address', + }, + ], + name: 'balanceOf', + outputs: [ + { + name: '', + type: 'uint256', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: '_to', + type: 'address', + }, + { + name: '_value', + type: 'uint256', + }, + ], + name: 'transfer', + outputs: [ + { + name: '', + type: 'bool', + }, + ], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: '_owner', + type: 'address', + }, + { + name: '_spender', + type: 'address', + }, + ], + name: 'allowance', + outputs: [ + { + name: '', + type: 'uint256', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + anonymous: false, + inputs: [ + { + name: '_from', + type: 'address', + indexed: true, + }, + { + name: '_to', + type: 'address', + indexed: true, + }, + { + name: '_value', + type: 'uint256', + indexed: false, + }, + ], + name: 'Transfer', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: '_owner', + type: 'address', + indexed: true, + }, + { + name: '_spender', + type: 'address', + indexed: true, + }, + { + name: '_value', + type: 'uint256', + indexed: false, + }, + ], + name: 'Approval', + outputs: [], + type: 'event', + }, + ] as ContractAbi; + return abi; + } + /** + * Subscribe to an event type emitted by the ERC20Token contract. + * @param eventName The ERC20Token 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: ERC20TokenEvents, + indexFilterValues: IndexedFilterValues, + callback: EventCallback, + isVerbose: boolean = false, + blockPollingIntervalMs?: number, + ): string { + assert.doesBelongToStringEnum('eventName', eventName, ERC20TokenEvents); + assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); + assert.isFunction('callback', callback); + const subscriptionToken = this._subscriptionManager.subscribe( + this.address, + eventName, + indexFilterValues, + ERC20TokenContract.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 ERC20Token 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: ERC20TokenEvents, + blockRange: BlockRange, + indexFilterValues: IndexedFilterValues, + ): Promise>> { + assert.doesBelongToStringEnum('eventName', eventName, ERC20TokenEvents); + assert.doesConformToSchema('blockRange', blockRange, schemas.blockRangeSchema); + assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); + const logs = await this._subscriptionManager.getLogsAsync( + this.address, + eventName, + blockRange, + indexFilterValues, + ERC20TokenContract.ABI(), + ); + return logs; + } + constructor( + address: string, + supportedProvider: SupportedProvider, + txDefaults?: Partial, + logDecodeDependencies?: { [contractName: string]: ContractAbi }, + ) { + super('ERC20Token', ERC20TokenContract.ABI(), address, supportedProvider, txDefaults, logDecodeDependencies); + classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + this._subscriptionManager = new SubscriptionManager( + ERC20TokenContract.ABI(), + this._web3Wrapper, + ); + } +} + +// 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/contract-wrappers/src/generated-wrappers/erc721_proxy.ts b/packages/contract-wrappers/src/generated-wrappers/erc721_proxy.ts new file mode 100644 index 0000000000..63af02b710 --- /dev/null +++ b/packages/contract-wrappers/src/generated-wrappers/erc721_proxy.ts @@ -0,0 +1,1368 @@ +// tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma +// tslint:disable:whitespace no-unbound-method no-trailing-whitespace +// tslint:disable:no-unused-variable +import { + BaseContract, + BlockRange, + EventCallback, + IndexedFilterValues, + SubscriptionManager, + PromiseWithTransactionHash, +} from '@0x/base-contract'; +import { schemas } from '@0x/json-schemas'; +import { + BlockParam, + BlockParamLiteral, + CallData, + ContractAbi, + ContractArtifact, + DecodedLogArgs, + LogWithDecodedArgs, + MethodAbi, + TransactionReceiptWithDecodedLogs, + TxData, + TxDataPayable, + SupportedProvider, +} from 'ethereum-types'; +import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; +import { 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 ERC721ProxyEventArgs = + | ERC721ProxyAuthorizedAddressAddedEventArgs + | ERC721ProxyAuthorizedAddressRemovedEventArgs; + +export enum ERC721ProxyEvents { + AuthorizedAddressAdded = 'AuthorizedAddressAdded', + AuthorizedAddressRemoved = 'AuthorizedAddressRemoved', +} + +export interface ERC721ProxyAuthorizedAddressAddedEventArgs extends DecodedLogArgs { + target: string; + caller: string; +} + +export interface ERC721ProxyAuthorizedAddressRemovedEventArgs extends DecodedLogArgs { + target: string; + caller: string; +} + +/* istanbul ignore next */ +// tslint:disable:no-parameter-reassignment +// tslint:disable-next-line:class-name +export class ERC721ProxyContract extends BaseContract { + /** + * Authorizes an address. + */ + public addAuthorizedAddress = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param target Address to authorize. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(target: string, txData?: Partial | undefined): Promise { + assert.isString('target', target); + const self = (this as any) as ERC721ProxyContract; + const encodedData = self._strictEncodeArguments('addAuthorizedAddress(address)', [target.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.addAuthorizedAddress.estimateGasAsync.bind(self, target.toLowerCase()), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param target Address to authorize. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + target: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('target', target); + const self = (this as any) as ERC721ProxyContract; + const txHashPromise = self.addAuthorizedAddress.sendTransactionAsync(target.toLowerCase(), txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param target Address to authorize. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(target: string, txData?: Partial | undefined): Promise { + assert.isString('target', target); + const self = (this as any) as ERC721ProxyContract; + const encodedData = self._strictEncodeArguments('addAuthorizedAddress(address)', [target.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param target Address to authorize. + */ + async callAsync(target: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.isString('target', target); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC721ProxyContract; + const encodedData = self._strictEncodeArguments('addAuthorizedAddress(address)', [target.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('addAuthorizedAddress(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param target Address to authorize. + */ + getABIEncodedTransactionData(target: string): string { + assert.isString('target', target); + const self = (this as any) as ERC721ProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('addAuthorizedAddress(address)', [ + target.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as ERC721ProxyContract; + const abiEncoder = self._lookupAbiEncoder('addAuthorizedAddress(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as ERC721ProxyContract; + const abiEncoder = self._lookupAbiEncoder('addAuthorizedAddress(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public authorities = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + index_0: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isBigNumber('index_0', index_0); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC721ProxyContract; + const encodedData = self._strictEncodeArguments('authorities(uint256)', [index_0]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('authorities(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(index_0: BigNumber): string { + assert.isBigNumber('index_0', index_0); + const self = (this as any) as ERC721ProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('authorities(uint256)', [index_0]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as ERC721ProxyContract; + const abiEncoder = self._lookupAbiEncoder('authorities(uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as ERC721ProxyContract; + const abiEncoder = self._lookupAbiEncoder('authorities(uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Removes authorizion of an address. + */ + public removeAuthorizedAddress = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param target Address to remove authorization from. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(target: string, txData?: Partial | undefined): Promise { + assert.isString('target', target); + const self = (this as any) as ERC721ProxyContract; + const encodedData = self._strictEncodeArguments('removeAuthorizedAddress(address)', [target.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.removeAuthorizedAddress.estimateGasAsync.bind(self, target.toLowerCase()), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param target Address to remove authorization from. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + target: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('target', target); + const self = (this as any) as ERC721ProxyContract; + const txHashPromise = self.removeAuthorizedAddress.sendTransactionAsync(target.toLowerCase(), txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param target Address to remove authorization from. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(target: string, txData?: Partial | undefined): Promise { + assert.isString('target', target); + const self = (this as any) as ERC721ProxyContract; + const encodedData = self._strictEncodeArguments('removeAuthorizedAddress(address)', [target.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param target Address to remove authorization from. + */ + async callAsync(target: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.isString('target', target); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC721ProxyContract; + const encodedData = self._strictEncodeArguments('removeAuthorizedAddress(address)', [target.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddress(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param target Address to remove authorization from. + */ + getABIEncodedTransactionData(target: string): string { + assert.isString('target', target); + const self = (this as any) as ERC721ProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('removeAuthorizedAddress(address)', [ + target.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as ERC721ProxyContract; + const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddress(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as ERC721ProxyContract; + const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddress(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public owner = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC721ProxyContract; + const encodedData = self._strictEncodeArguments('owner()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('owner()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as ERC721ProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('owner()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as ERC721ProxyContract; + const abiEncoder = self._lookupAbiEncoder('owner()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as ERC721ProxyContract; + const abiEncoder = self._lookupAbiEncoder('owner()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Removes authorizion of an address. + */ + public removeAuthorizedAddressAtIndex = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param target Address to remove authorization from. + * @param index Index of target in authorities array. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + target: string, + index: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('target', target); + assert.isBigNumber('index', index); + const self = (this as any) as ERC721ProxyContract; + const encodedData = self._strictEncodeArguments('removeAuthorizedAddressAtIndex(address,uint256)', [ + target.toLowerCase(), + index, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.removeAuthorizedAddressAtIndex.estimateGasAsync.bind(self, target.toLowerCase(), index), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param target Address to remove authorization from. + * @param index Index of target in authorities array. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + target: string, + index: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('target', target); + assert.isBigNumber('index', index); + const self = (this as any) as ERC721ProxyContract; + const txHashPromise = self.removeAuthorizedAddressAtIndex.sendTransactionAsync( + target.toLowerCase(), + index, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param target Address to remove authorization from. + * @param index Index of target in authorities array. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + target: string, + index: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('target', target); + assert.isBigNumber('index', index); + const self = (this as any) as ERC721ProxyContract; + const encodedData = self._strictEncodeArguments('removeAuthorizedAddressAtIndex(address,uint256)', [ + target.toLowerCase(), + index, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param target Address to remove authorization from. + * @param index Index of target in authorities array. + */ + async callAsync( + target: string, + index: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('target', target); + assert.isBigNumber('index', index); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC721ProxyContract; + const encodedData = self._strictEncodeArguments('removeAuthorizedAddressAtIndex(address,uint256)', [ + target.toLowerCase(), + index, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddressAtIndex(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param target Address to remove authorization from. + * @param index Index of target in authorities array. + */ + getABIEncodedTransactionData(target: string, index: BigNumber): string { + assert.isString('target', target); + assert.isBigNumber('index', index); + const self = (this as any) as ERC721ProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'removeAuthorizedAddressAtIndex(address,uint256)', + [target.toLowerCase(), index], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as ERC721ProxyContract; + const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddressAtIndex(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as ERC721ProxyContract; + const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddressAtIndex(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Gets the proxy id associated with the proxy address. + */ + public getProxyId = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @returns Proxy id. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC721ProxyContract; + const encodedData = self._strictEncodeArguments('getProxyId()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getProxyId()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as ERC721ProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('getProxyId()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as ERC721ProxyContract; + const abiEncoder = self._lookupAbiEncoder('getProxyId()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as ERC721ProxyContract; + const abiEncoder = self._lookupAbiEncoder('getProxyId()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public authorized = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + index_0: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('index_0', index_0); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC721ProxyContract; + const encodedData = self._strictEncodeArguments('authorized(address)', [index_0.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('authorized(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(index_0: string): string { + assert.isString('index_0', index_0); + const self = (this as any) as ERC721ProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('authorized(address)', [ + index_0.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): boolean { + const self = (this as any) as ERC721ProxyContract; + const abiEncoder = self._lookupAbiEncoder('authorized(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): boolean { + const self = (this as any) as ERC721ProxyContract; + const abiEncoder = self._lookupAbiEncoder('authorized(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Gets all authorized addresses. + */ + public getAuthorizedAddresses = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @returns Array of authorized addresses. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC721ProxyContract; + const encodedData = self._strictEncodeArguments('getAuthorizedAddresses()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getAuthorizedAddresses()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as ERC721ProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('getAuthorizedAddresses()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string[] { + const self = (this as any) as ERC721ProxyContract; + const abiEncoder = self._lookupAbiEncoder('getAuthorizedAddresses()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string[] { + const self = (this as any) as ERC721ProxyContract; + const abiEncoder = self._lookupAbiEncoder('getAuthorizedAddresses()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public transferOwnership = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(newOwner: string, txData?: Partial | undefined): Promise { + assert.isString('newOwner', newOwner); + const self = (this as any) as ERC721ProxyContract; + const encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.transferOwnership.estimateGasAsync.bind(self, newOwner.toLowerCase()), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + newOwner: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('newOwner', newOwner); + const self = (this as any) as ERC721ProxyContract; + const txHashPromise = self.transferOwnership.sendTransactionAsync(newOwner.toLowerCase(), txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(newOwner: string, txData?: Partial | undefined): Promise { + assert.isString('newOwner', newOwner); + const self = (this as any) as ERC721ProxyContract; + const encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(newOwner: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.isString('newOwner', newOwner); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC721ProxyContract; + const encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(newOwner: string): string { + assert.isString('newOwner', newOwner); + const self = (this as any) as ERC721ProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('transferOwnership(address)', [ + newOwner.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as ERC721ProxyContract; + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as ERC721ProxyContract; + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + 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 ERC721ProxyContract.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._applyDefaultsToTxDataAsync( + { 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(`ERC721Proxy successfully deployed at ${txReceipt.contractAddress}`); + const contractInstance = new ERC721ProxyContract( + txReceipt.contractAddress as string, + provider, + txDefaults, + logDecodeDependencies, + ); + contractInstance.constructorArgs = []; + return contractInstance; + } + + /** + * @returns The contract ABI + */ + public static ABI(): ContractAbi { + const abi = [ + { + constant: false, + inputs: [ + { + name: 'target', + type: 'address', + }, + ], + name: 'addAuthorizedAddress', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'index_0', + type: 'uint256', + }, + ], + name: 'authorities', + outputs: [ + { + name: '', + type: 'address', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'target', + type: 'address', + }, + ], + name: 'removeAuthorizedAddress', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'owner', + outputs: [ + { + name: '', + type: 'address', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'target', + type: 'address', + }, + { + name: 'index', + type: 'uint256', + }, + ], + name: 'removeAuthorizedAddressAtIndex', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'getProxyId', + outputs: [ + { + name: '', + type: 'bytes4', + }, + ], + payable: false, + stateMutability: 'pure', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'index_0', + type: 'address', + }, + ], + name: 'authorized', + outputs: [ + { + name: '', + type: 'bool', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'getAuthorizedAddresses', + outputs: [ + { + name: '', + type: 'address[]', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'newOwner', + type: 'address', + }, + ], + name: 'transferOwnership', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + inputs: [], + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'fallback', + }, + { + anonymous: false, + inputs: [ + { + name: 'target', + type: 'address', + indexed: true, + }, + { + name: 'caller', + type: 'address', + indexed: true, + }, + ], + name: 'AuthorizedAddressAdded', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: 'target', + type: 'address', + indexed: true, + }, + { + name: 'caller', + type: 'address', + indexed: true, + }, + ], + name: 'AuthorizedAddressRemoved', + outputs: [], + type: 'event', + }, + ] as ContractAbi; + return abi; + } + /** + * Subscribe to an event type emitted by the ERC721Proxy contract. + * @param eventName The ERC721Proxy 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: ERC721ProxyEvents, + indexFilterValues: IndexedFilterValues, + callback: EventCallback, + isVerbose: boolean = false, + blockPollingIntervalMs?: number, + ): string { + assert.doesBelongToStringEnum('eventName', eventName, ERC721ProxyEvents); + assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); + assert.isFunction('callback', callback); + const subscriptionToken = this._subscriptionManager.subscribe( + this.address, + eventName, + indexFilterValues, + ERC721ProxyContract.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 ERC721Proxy 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: ERC721ProxyEvents, + blockRange: BlockRange, + indexFilterValues: IndexedFilterValues, + ): Promise>> { + assert.doesBelongToStringEnum('eventName', eventName, ERC721ProxyEvents); + assert.doesConformToSchema('blockRange', blockRange, schemas.blockRangeSchema); + assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); + const logs = await this._subscriptionManager.getLogsAsync( + this.address, + eventName, + blockRange, + indexFilterValues, + ERC721ProxyContract.ABI(), + ); + return logs; + } + constructor( + address: string, + supportedProvider: SupportedProvider, + txDefaults?: Partial, + logDecodeDependencies?: { [contractName: string]: ContractAbi }, + ) { + super('ERC721Proxy', ERC721ProxyContract.ABI(), address, supportedProvider, txDefaults, logDecodeDependencies); + classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + this._subscriptionManager = new SubscriptionManager( + ERC721ProxyContract.ABI(), + this._web3Wrapper, + ); + } +} + +// 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/contract-wrappers/src/generated-wrappers/erc721_token.ts b/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts new file mode 100644 index 0000000000..422f748c94 --- /dev/null +++ b/packages/contract-wrappers/src/generated-wrappers/erc721_token.ts @@ -0,0 +1,1825 @@ +// tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma +// tslint:disable:whitespace no-unbound-method no-trailing-whitespace +// tslint:disable:no-unused-variable +import { + BaseContract, + BlockRange, + EventCallback, + IndexedFilterValues, + SubscriptionManager, + PromiseWithTransactionHash, +} from '@0x/base-contract'; +import { schemas } from '@0x/json-schemas'; +import { + BlockParam, + BlockParamLiteral, + CallData, + ContractAbi, + ContractArtifact, + DecodedLogArgs, + LogWithDecodedArgs, + MethodAbi, + TransactionReceiptWithDecodedLogs, + TxData, + TxDataPayable, + SupportedProvider, +} from 'ethereum-types'; +import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; +import { 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 ERC721TokenEventArgs = + | ERC721TokenTransferEventArgs + | ERC721TokenApprovalEventArgs + | ERC721TokenApprovalForAllEventArgs; + +export enum ERC721TokenEvents { + Transfer = 'Transfer', + Approval = 'Approval', + ApprovalForAll = 'ApprovalForAll', +} + +export interface ERC721TokenTransferEventArgs extends DecodedLogArgs { + _from: string; + _to: string; + _tokenId: BigNumber; +} + +export interface ERC721TokenApprovalEventArgs extends DecodedLogArgs { + _owner: string; + _approved: string; + _tokenId: BigNumber; +} + +export interface ERC721TokenApprovalForAllEventArgs extends DecodedLogArgs { + _owner: string; + _operator: string; + _approved: boolean; +} + +/* istanbul ignore next */ +// tslint:disable:no-parameter-reassignment +// tslint:disable-next-line:class-name +export class ERC721TokenContract extends BaseContract { + /** + * Throws if `_tokenId` is not a valid NFT. + */ + public getApproved = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _tokenId The NFT to find the approved address for + * @returns The approved address for this NFT, or the zero address if there is none + */ + async callAsync( + _tokenId: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isBigNumber('_tokenId', _tokenId); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC721TokenContract; + const encodedData = self._strictEncodeArguments('getApproved(uint256)', [_tokenId]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getApproved(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _tokenId The NFT to find the approved address for + */ + getABIEncodedTransactionData(_tokenId: BigNumber): string { + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as ERC721TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('getApproved(uint256)', [_tokenId]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as ERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('getApproved(uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as ERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('getApproved(uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * 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. + */ + public approve = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param _approved The new approved NFT controller + * @param _tokenId The NFT to approve + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + _approved: string, + _tokenId: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_approved', _approved); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as ERC721TokenContract; + const encodedData = self._strictEncodeArguments('approve(address,uint256)', [ + _approved.toLowerCase(), + _tokenId, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.approve.estimateGasAsync.bind(self, _approved.toLowerCase(), _tokenId), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param _approved The new approved NFT controller + * @param _tokenId The NFT to approve + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + _approved: string, + _tokenId: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('_approved', _approved); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as ERC721TokenContract; + const txHashPromise = self.approve.sendTransactionAsync(_approved.toLowerCase(), _tokenId, txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param _approved The new approved NFT controller + * @param _tokenId The NFT to approve + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + _approved: string, + _tokenId: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_approved', _approved); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as ERC721TokenContract; + const encodedData = self._strictEncodeArguments('approve(address,uint256)', [ + _approved.toLowerCase(), + _tokenId, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _approved The new approved NFT controller + * @param _tokenId The NFT to approve + */ + async callAsync( + _approved: string, + _tokenId: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_approved', _approved); + assert.isBigNumber('_tokenId', _tokenId); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC721TokenContract; + const encodedData = self._strictEncodeArguments('approve(address,uint256)', [ + _approved.toLowerCase(), + _tokenId, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('approve(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _approved The new approved NFT controller + * @param _tokenId The NFT to approve + */ + getABIEncodedTransactionData(_approved: string, _tokenId: BigNumber): string { + assert.isString('_approved', _approved); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as ERC721TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('approve(address,uint256)', [ + _approved.toLowerCase(), + _tokenId, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as ERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('approve(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as ERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('approve(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * 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. + */ + public transferFrom = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + _from: string, + _to: string, + _tokenId: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as ERC721TokenContract; + const encodedData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.transferFrom.estimateGasAsync.bind(self, _from.toLowerCase(), _to.toLowerCase(), _tokenId), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + _from: string, + _to: string, + _tokenId: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as ERC721TokenContract; + const txHashPromise = self.transferFrom.sendTransactionAsync( + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + _from: string, + _to: string, + _tokenId: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as ERC721TokenContract; + const encodedData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + */ + async callAsync( + _from: string, + _to: string, + _tokenId: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC721TokenContract; + const encodedData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + */ + getABIEncodedTransactionData(_from: string, _to: string, _tokenId: BigNumber): string { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as ERC721TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as ERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('transferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as ERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('transferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * This works identically to the other function with an extra data parameter, + * except this function just sets data to "". + */ + public safeTransferFrom1 = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + _from: string, + _to: string, + _tokenId: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as ERC721TokenContract; + const encodedData = self._strictEncodeArguments('safeTransferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.safeTransferFrom1.estimateGasAsync.bind(self, _from.toLowerCase(), _to.toLowerCase(), _tokenId), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + _from: string, + _to: string, + _tokenId: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as ERC721TokenContract; + const txHashPromise = self.safeTransferFrom1.sendTransactionAsync( + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + _from: string, + _to: string, + _tokenId: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as ERC721TokenContract; + const encodedData = self._strictEncodeArguments('safeTransferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + */ + async callAsync( + _from: string, + _to: string, + _tokenId: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC721TokenContract; + const encodedData = self._strictEncodeArguments('safeTransferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('safeTransferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + */ + getABIEncodedTransactionData(_from: string, _to: string, _tokenId: BigNumber): string { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as ERC721TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('safeTransferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as ERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('safeTransferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as ERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('safeTransferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * NFTs assigned to zero address are considered invalid, and queries + * about them do throw. + */ + public ownerOf = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _tokenId The identifier for an NFT + * @returns The address of the owner of the NFT + */ + async callAsync( + _tokenId: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isBigNumber('_tokenId', _tokenId); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC721TokenContract; + const encodedData = self._strictEncodeArguments('ownerOf(uint256)', [_tokenId]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('ownerOf(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _tokenId The identifier for an NFT + */ + getABIEncodedTransactionData(_tokenId: BigNumber): string { + assert.isBigNumber('_tokenId', _tokenId); + const self = (this as any) as ERC721TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('ownerOf(uint256)', [_tokenId]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as ERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('ownerOf(uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as ERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('ownerOf(uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * NFTs assigned to the zero address are considered invalid, and this + * function throws for queries about the zero address. + */ + public balanceOf = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _owner An address for whom to query the balance + * @returns The number of NFTs owned by `_owner`, possibly zero + */ + async callAsync( + _owner: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_owner', _owner); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC721TokenContract; + const encodedData = self._strictEncodeArguments('balanceOf(address)', [_owner.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('balanceOf(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _owner An address for whom to query the balance + */ + getABIEncodedTransactionData(_owner: string): string { + assert.isString('_owner', _owner); + const self = (this as any) as ERC721TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('balanceOf(address)', [_owner.toLowerCase()]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): BigNumber { + const self = (this as any) as ERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('balanceOf(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): BigNumber { + const self = (this as any) as ERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('balanceOf(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Emits the ApprovalForAll event. The contract MUST allow + * multiple operators per owner. + */ + public setApprovalForAll = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param _operator Address to add to the set of authorized operators + * @param _approved True if the operator is approved, false to revoke approval + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + _operator: string, + _approved: boolean, + txData?: Partial | undefined, + ): Promise { + assert.isString('_operator', _operator); + assert.isBoolean('_approved', _approved); + const self = (this as any) as ERC721TokenContract; + const encodedData = self._strictEncodeArguments('setApprovalForAll(address,bool)', [ + _operator.toLowerCase(), + _approved, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.setApprovalForAll.estimateGasAsync.bind(self, _operator.toLowerCase(), _approved), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param _operator Address to add to the set of authorized operators + * @param _approved True if the operator is approved, false to revoke approval + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + _operator: string, + _approved: boolean, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('_operator', _operator); + assert.isBoolean('_approved', _approved); + const self = (this as any) as ERC721TokenContract; + const txHashPromise = self.setApprovalForAll.sendTransactionAsync( + _operator.toLowerCase(), + _approved, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param _operator Address to add to the set of authorized operators + * @param _approved True if the operator is approved, false to revoke approval + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + _operator: string, + _approved: boolean, + txData?: Partial | undefined, + ): Promise { + assert.isString('_operator', _operator); + assert.isBoolean('_approved', _approved); + const self = (this as any) as ERC721TokenContract; + const encodedData = self._strictEncodeArguments('setApprovalForAll(address,bool)', [ + _operator.toLowerCase(), + _approved, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _operator Address to add to the set of authorized operators + * @param _approved True if the operator is approved, false to revoke approval + */ + async callAsync( + _operator: string, + _approved: boolean, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_operator', _operator); + assert.isBoolean('_approved', _approved); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC721TokenContract; + const encodedData = self._strictEncodeArguments('setApprovalForAll(address,bool)', [ + _operator.toLowerCase(), + _approved, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('setApprovalForAll(address,bool)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _operator Address to add to the set of authorized operators + * @param _approved True if the operator is approved, false to revoke approval + */ + getABIEncodedTransactionData(_operator: string, _approved: boolean): string { + assert.isString('_operator', _operator); + assert.isBoolean('_approved', _approved); + const self = (this as any) as ERC721TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('setApprovalForAll(address,bool)', [ + _operator.toLowerCase(), + _approved, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as ERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('setApprovalForAll(address,bool)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as ERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('setApprovalForAll(address,bool)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * 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)"))`. + */ + public safeTransferFrom2 = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + * @param _data Additional data with no specified format, sent in call to `_to` + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + _from: string, + _to: string, + _tokenId: BigNumber, + _data: string, + txData?: Partial | undefined, + ): Promise { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + assert.isString('_data', _data); + const self = (this as any) as ERC721TokenContract; + const encodedData = self._strictEncodeArguments('safeTransferFrom(address,address,uint256,bytes)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + _data, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.safeTransferFrom2.estimateGasAsync.bind( + self, + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + _data, + ), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + * @param _data Additional data with no specified format, sent in call to `_to` + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + _from: string, + _to: string, + _tokenId: BigNumber, + _data: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + assert.isString('_data', _data); + const self = (this as any) as ERC721TokenContract; + const txHashPromise = self.safeTransferFrom2.sendTransactionAsync( + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + _data, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + * @param _data Additional data with no specified format, sent in call to `_to` + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + _from: string, + _to: string, + _tokenId: BigNumber, + _data: string, + txData?: Partial | undefined, + ): Promise { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + assert.isString('_data', _data); + const self = (this as any) as ERC721TokenContract; + const encodedData = self._strictEncodeArguments('safeTransferFrom(address,address,uint256,bytes)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + _data, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + * @param _data Additional data with no specified format, sent in call to `_to` + */ + async callAsync( + _from: string, + _to: string, + _tokenId: BigNumber, + _data: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + assert.isString('_data', _data); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC721TokenContract; + const encodedData = self._strictEncodeArguments('safeTransferFrom(address,address,uint256,bytes)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + _data, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('safeTransferFrom(address,address,uint256,bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + * @param _data Additional data with no specified format, sent in call to `_to` + */ + getABIEncodedTransactionData(_from: string, _to: string, _tokenId: BigNumber, _data: string): string { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + assert.isString('_data', _data); + const self = (this as any) as ERC721TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'safeTransferFrom(address,address,uint256,bytes)', + [_from.toLowerCase(), _to.toLowerCase(), _tokenId, _data], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as ERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('safeTransferFrom(address,address,uint256,bytes)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as ERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('safeTransferFrom(address,address,uint256,bytes)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public isApprovedForAll = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _owner The address that owns the NFTs + * @param _operator The address that acts on behalf of the owner + * @returns True if `_operator` is an approved operator for `_owner`, false otherwise + */ + async callAsync( + _owner: string, + _operator: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_owner', _owner); + assert.isString('_operator', _operator); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ERC721TokenContract; + const encodedData = self._strictEncodeArguments('isApprovedForAll(address,address)', [ + _owner.toLowerCase(), + _operator.toLowerCase(), + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('isApprovedForAll(address,address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _owner The address that owns the NFTs + * @param _operator The address that acts on behalf of the owner + */ + getABIEncodedTransactionData(_owner: string, _operator: string): string { + assert.isString('_owner', _owner); + assert.isString('_operator', _operator); + const self = (this as any) as ERC721TokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('isApprovedForAll(address,address)', [ + _owner.toLowerCase(), + _operator.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): boolean { + const self = (this as any) as ERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('isApprovedForAll(address,address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): boolean { + const self = (this as any) as ERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder('isApprovedForAll(address,address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + 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 ERC721TokenContract.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._applyDefaultsToTxDataAsync( + { 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(`ERC721Token successfully deployed at ${txReceipt.contractAddress}`); + const contractInstance = new ERC721TokenContract( + 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: '_tokenId', + type: 'uint256', + }, + ], + name: 'getApproved', + outputs: [ + { + name: '', + type: 'address', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: '_approved', + type: 'address', + }, + { + name: '_tokenId', + type: 'uint256', + }, + ], + name: 'approve', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: '_from', + type: 'address', + }, + { + name: '_to', + type: 'address', + }, + { + name: '_tokenId', + type: 'uint256', + }, + ], + name: 'transferFrom', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: '_from', + type: 'address', + }, + { + name: '_to', + type: 'address', + }, + { + name: '_tokenId', + type: 'uint256', + }, + ], + name: 'safeTransferFrom', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: '_tokenId', + type: 'uint256', + }, + ], + name: 'ownerOf', + outputs: [ + { + name: '', + type: 'address', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: '_owner', + type: 'address', + }, + ], + name: 'balanceOf', + outputs: [ + { + name: '', + type: 'uint256', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: '_operator', + type: 'address', + }, + { + name: '_approved', + type: 'bool', + }, + ], + name: 'setApprovalForAll', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: '_from', + type: 'address', + }, + { + name: '_to', + type: 'address', + }, + { + name: '_tokenId', + type: 'uint256', + }, + { + name: '_data', + type: 'bytes', + }, + ], + name: 'safeTransferFrom', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: '_owner', + type: 'address', + }, + { + name: '_operator', + type: 'address', + }, + ], + name: 'isApprovedForAll', + outputs: [ + { + name: '', + type: 'bool', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + anonymous: false, + inputs: [ + { + name: '_from', + type: 'address', + indexed: true, + }, + { + name: '_to', + type: 'address', + indexed: true, + }, + { + name: '_tokenId', + type: 'uint256', + indexed: true, + }, + ], + name: 'Transfer', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: '_owner', + type: 'address', + indexed: true, + }, + { + name: '_approved', + type: 'address', + indexed: true, + }, + { + name: '_tokenId', + type: 'uint256', + indexed: true, + }, + ], + name: 'Approval', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: '_owner', + type: 'address', + indexed: true, + }, + { + name: '_operator', + type: 'address', + indexed: true, + }, + { + name: '_approved', + type: 'bool', + indexed: false, + }, + ], + name: 'ApprovalForAll', + outputs: [], + type: 'event', + }, + ] as ContractAbi; + return abi; + } + /** + * Subscribe to an event type emitted by the ERC721Token contract. + * @param eventName The ERC721Token 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: ERC721TokenEvents, + indexFilterValues: IndexedFilterValues, + callback: EventCallback, + isVerbose: boolean = false, + blockPollingIntervalMs?: number, + ): string { + assert.doesBelongToStringEnum('eventName', eventName, ERC721TokenEvents); + assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); + assert.isFunction('callback', callback); + const subscriptionToken = this._subscriptionManager.subscribe( + this.address, + eventName, + indexFilterValues, + ERC721TokenContract.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 ERC721Token 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: ERC721TokenEvents, + blockRange: BlockRange, + indexFilterValues: IndexedFilterValues, + ): Promise>> { + assert.doesBelongToStringEnum('eventName', eventName, ERC721TokenEvents); + assert.doesConformToSchema('blockRange', blockRange, schemas.blockRangeSchema); + assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); + const logs = await this._subscriptionManager.getLogsAsync( + this.address, + eventName, + blockRange, + indexFilterValues, + ERC721TokenContract.ABI(), + ); + return logs; + } + constructor( + address: string, + supportedProvider: SupportedProvider, + txDefaults?: Partial, + logDecodeDependencies?: { [contractName: string]: ContractAbi }, + ) { + super('ERC721Token', ERC721TokenContract.ABI(), address, supportedProvider, txDefaults, logDecodeDependencies); + classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + this._subscriptionManager = new SubscriptionManager( + ERC721TokenContract.ABI(), + this._web3Wrapper, + ); + } +} + +// 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/contract-wrappers/src/generated-wrappers/eth_balance_checker.ts b/packages/contract-wrappers/src/generated-wrappers/eth_balance_checker.ts new file mode 100644 index 0000000000..1c9193cc33 --- /dev/null +++ b/packages/contract-wrappers/src/generated-wrappers/eth_balance_checker.ts @@ -0,0 +1,215 @@ +// tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma +// tslint:disable:whitespace no-unbound-method no-trailing-whitespace +// tslint:disable:no-unused-variable +import { BaseContract, PromiseWithTransactionHash } from '@0x/base-contract'; +import { schemas } from '@0x/json-schemas'; +import { + BlockParam, + BlockParamLiteral, + CallData, + ContractAbi, + ContractArtifact, + DecodedLogArgs, + MethodAbi, + TransactionReceiptWithDecodedLogs, + TxData, + TxDataPayable, + SupportedProvider, +} from 'ethereum-types'; +import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; +import { 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:no-parameter-reassignment +// tslint:disable-next-line:class-name +export class EthBalanceCheckerContract extends BaseContract { + /** + * Batch fetches ETH balances + */ + public getEthBalances = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param addresses Array of addresses. + * @returns Array of ETH balances. + */ + async callAsync( + addresses: string[], + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isArray('addresses', addresses); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as EthBalanceCheckerContract; + const encodedData = self._strictEncodeArguments('getEthBalances(address[])', [addresses]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getEthBalances(address[])'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param addresses Array of addresses. + */ + getABIEncodedTransactionData(addresses: string[]): string { + assert.isArray('addresses', addresses); + const self = (this as any) as EthBalanceCheckerContract; + const abiEncodedTransactionData = self._strictEncodeArguments('getEthBalances(address[])', [addresses]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): BigNumber[] { + const self = (this as any) as EthBalanceCheckerContract; + const abiEncoder = self._lookupAbiEncoder('getEthBalances(address[])'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): BigNumber[] { + const self = (this as any) as EthBalanceCheckerContract; + const abiEncoder = self._lookupAbiEncoder('getEthBalances(address[])'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + 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 EthBalanceCheckerContract.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._applyDefaultsToTxDataAsync( + { 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(`EthBalanceChecker successfully deployed at ${txReceipt.contractAddress}`); + const contractInstance = new EthBalanceCheckerContract( + 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: 'addresses', + type: 'address[]', + }, + ], + name: 'getEthBalances', + outputs: [ + { + name: '', + type: 'uint256[]', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + ] as ContractAbi; + return abi; + } + constructor( + address: string, + supportedProvider: SupportedProvider, + txDefaults?: Partial, + logDecodeDependencies?: { [contractName: string]: ContractAbi }, + ) { + super( + 'EthBalanceChecker', + EthBalanceCheckerContract.ABI(), + address, + supportedProvider, + txDefaults, + logDecodeDependencies, + ); + classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + } +} + +// 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/contract-wrappers/src/generated-wrappers/exchange.ts b/packages/contract-wrappers/src/generated-wrappers/exchange.ts new file mode 100644 index 0000000000..2df6b7ae3b --- /dev/null +++ b/packages/contract-wrappers/src/generated-wrappers/exchange.ts @@ -0,0 +1,8623 @@ +// tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma +// tslint:disable:whitespace no-unbound-method no-trailing-whitespace +// tslint:disable:no-unused-variable +import { + BaseContract, + BlockRange, + EventCallback, + IndexedFilterValues, + SubscriptionManager, + PromiseWithTransactionHash, +} from '@0x/base-contract'; +import { schemas } from '@0x/json-schemas'; +import { + BlockParam, + BlockParamLiteral, + CallData, + ContractAbi, + ContractArtifact, + DecodedLogArgs, + LogWithDecodedArgs, + MethodAbi, + TransactionReceiptWithDecodedLogs, + TxData, + TxDataPayable, + SupportedProvider, +} from 'ethereum-types'; +import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; +import { 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 ExchangeEventArgs = + | ExchangeSignatureValidatorApprovalEventArgs + | ExchangeFillEventArgs + | ExchangeCancelEventArgs + | ExchangeCancelUpToEventArgs + | ExchangeAssetProxyRegisteredEventArgs; + +export enum ExchangeEvents { + SignatureValidatorApproval = 'SignatureValidatorApproval', + Fill = 'Fill', + Cancel = 'Cancel', + CancelUpTo = 'CancelUpTo', + AssetProxyRegistered = 'AssetProxyRegistered', +} + +export interface ExchangeSignatureValidatorApprovalEventArgs extends DecodedLogArgs { + signerAddress: string; + validatorAddress: string; + approved: boolean; +} + +export interface ExchangeFillEventArgs extends DecodedLogArgs { + makerAddress: string; + feeRecipientAddress: string; + takerAddress: string; + senderAddress: string; + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + orderHash: string; + makerAssetData: string; + takerAssetData: string; +} + +export interface ExchangeCancelEventArgs extends DecodedLogArgs { + makerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + orderHash: string; + makerAssetData: string; + takerAssetData: string; +} + +export interface ExchangeCancelUpToEventArgs extends DecodedLogArgs { + makerAddress: string; + senderAddress: string; + orderEpoch: BigNumber; +} + +export interface ExchangeAssetProxyRegisteredEventArgs extends DecodedLogArgs { + id: string; + assetProxy: string; +} + +/* istanbul ignore next */ +// tslint:disable:no-parameter-reassignment +// tslint:disable-next-line:class-name +export class ExchangeContract extends BaseContract { + public filled = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + index_0: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('index_0', index_0); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('filled(bytes32)', [index_0]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('filled(bytes32)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(index_0: string): string { + assert.isString('index_0', index_0); + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments('filled(bytes32)', [index_0]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): BigNumber { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('filled(bytes32)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): BigNumber { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('filled(bytes32)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Synchronously executes multiple calls of fillOrder. + */ + public batchFillOrders = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param orders Array of order specifications. + * @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell + * in orders. + * @param signatures Proofs that orders have been created by makers. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAssetFillAmounts: BigNumber[], + signatures: string[], + txData?: Partial | undefined, + ): Promise { + assert.isArray('orders', orders); + assert.isArray('takerAssetFillAmounts', takerAssetFillAmounts); + assert.isArray('signatures', signatures); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'batchFillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256[],bytes[])', + [orders, takerAssetFillAmounts, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.batchFillOrders.estimateGasAsync.bind(self, orders, takerAssetFillAmounts, signatures), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param orders Array of order specifications. + * @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell + * in orders. + * @param signatures Proofs that orders have been created by makers. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAssetFillAmounts: BigNumber[], + signatures: string[], + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isArray('orders', orders); + assert.isArray('takerAssetFillAmounts', takerAssetFillAmounts); + assert.isArray('signatures', signatures); + const self = (this as any) as ExchangeContract; + const txHashPromise = self.batchFillOrders.sendTransactionAsync( + orders, + takerAssetFillAmounts, + signatures, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param orders Array of order specifications. + * @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell + * in orders. + * @param signatures Proofs that orders have been created by makers. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAssetFillAmounts: BigNumber[], + signatures: string[], + txData?: Partial | undefined, + ): Promise { + assert.isArray('orders', orders); + assert.isArray('takerAssetFillAmounts', takerAssetFillAmounts); + assert.isArray('signatures', signatures); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'batchFillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256[],bytes[])', + [orders, takerAssetFillAmounts, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param orders Array of order specifications. + * @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell + * in orders. + * @param signatures Proofs that orders have been created by makers. + * @returns Amounts filled and fees paid by makers and taker. NOTE: makerAssetFilledAmount and takerAssetFilledAmount may include amounts filled of different assets. + */ + async callAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAssetFillAmounts: BigNumber[], + signatures: string[], + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }> { + assert.isArray('orders', orders); + assert.isArray('takerAssetFillAmounts', takerAssetFillAmounts); + assert.isArray('signatures', signatures); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'batchFillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256[],bytes[])', + [orders, takerAssetFillAmounts, signatures], + ); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'batchFillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256[],bytes[])', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param orders Array of order specifications. + * @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell + * in orders. + * @param signatures Proofs that orders have been created by makers. + */ + getABIEncodedTransactionData( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAssetFillAmounts: BigNumber[], + signatures: string[], + ): string { + assert.isArray('orders', orders); + assert.isArray('takerAssetFillAmounts', takerAssetFillAmounts); + assert.isArray('signatures', signatures); + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'batchFillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256[],bytes[])', + [orders, takerAssetFillAmounts, signatures], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData( + callData: string, + ): { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'batchFillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256[],bytes[])', + ); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData( + returnData: string, + ): { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'batchFillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256[],bytes[])', + ); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(returnData); + return abiDecodedReturnData; + }, + }; + public cancelled = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + index_0: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('index_0', index_0); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('cancelled(bytes32)', [index_0]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('cancelled(bytes32)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(index_0: string): string { + assert.isString('index_0', index_0); + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments('cancelled(bytes32)', [index_0]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): boolean { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('cancelled(bytes32)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): boolean { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('cancelled(bytes32)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Approves a hash on-chain using any valid signature type. + * After presigning a hash, the preSign signature type will become valid for that hash and signer. + */ + public preSign = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param signerAddress Address that should have signed the given hash. + * @param signature Proof that the hash has been signed by signer. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + hash: string, + signerAddress: string, + signature: string, + txData?: Partial | undefined, + ): Promise { + assert.isString('hash', hash); + assert.isString('signerAddress', signerAddress); + assert.isString('signature', signature); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('preSign(bytes32,address,bytes)', [ + hash, + signerAddress.toLowerCase(), + signature, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.preSign.estimateGasAsync.bind(self, hash, signerAddress.toLowerCase(), signature), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param signerAddress Address that should have signed the given hash. + * @param signature Proof that the hash has been signed by signer. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + hash: string, + signerAddress: string, + signature: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('hash', hash); + assert.isString('signerAddress', signerAddress); + assert.isString('signature', signature); + const self = (this as any) as ExchangeContract; + const txHashPromise = self.preSign.sendTransactionAsync( + hash, + signerAddress.toLowerCase(), + signature, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param signerAddress Address that should have signed the given hash. + * @param signature Proof that the hash has been signed by signer. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + hash: string, + signerAddress: string, + signature: string, + txData?: Partial | undefined, + ): Promise { + assert.isString('hash', hash); + assert.isString('signerAddress', signerAddress); + assert.isString('signature', signature); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('preSign(bytes32,address,bytes)', [ + hash, + signerAddress.toLowerCase(), + signature, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param signerAddress Address that should have signed the given hash. + * @param signature Proof that the hash has been signed by signer. + */ + async callAsync( + hash: string, + signerAddress: string, + signature: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('hash', hash); + assert.isString('signerAddress', signerAddress); + assert.isString('signature', signature); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('preSign(bytes32,address,bytes)', [ + hash, + signerAddress.toLowerCase(), + signature, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('preSign(bytes32,address,bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param signerAddress Address that should have signed the given hash. + * @param signature Proof that the hash has been signed by signer. + */ + getABIEncodedTransactionData(hash: string, signerAddress: string, signature: string): string { + assert.isString('hash', hash); + assert.isString('signerAddress', signerAddress); + assert.isString('signature', signature); + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments('preSign(bytes32,address,bytes)', [ + hash, + signerAddress.toLowerCase(), + signature, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('preSign(bytes32,address,bytes)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('preSign(bytes32,address,bytes)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * 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). + */ + public matchOrders = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param leftOrder First order to match. + * @param rightOrder Second order to match. + * @param leftSignature Proof that order was created by the left maker. + * @param rightSignature Proof that order was created by the right maker. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + leftOrder: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + rightOrder: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + leftSignature: string, + rightSignature: string, + txData?: Partial | undefined, + ): Promise { + assert.isString('leftSignature', leftSignature); + assert.isString('rightSignature', rightSignature); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'matchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),bytes,bytes)', + [leftOrder, rightOrder, leftSignature, rightSignature], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.matchOrders.estimateGasAsync.bind(self, leftOrder, rightOrder, leftSignature, rightSignature), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param leftOrder First order to match. + * @param rightOrder Second order to match. + * @param leftSignature Proof that order was created by the left maker. + * @param rightSignature Proof that order was created by the right maker. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + leftOrder: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + rightOrder: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + leftSignature: string, + rightSignature: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('leftSignature', leftSignature); + assert.isString('rightSignature', rightSignature); + const self = (this as any) as ExchangeContract; + const txHashPromise = self.matchOrders.sendTransactionAsync( + leftOrder, + rightOrder, + leftSignature, + rightSignature, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param leftOrder First order to match. + * @param rightOrder Second order to match. + * @param leftSignature Proof that order was created by the left maker. + * @param rightSignature Proof that order was created by the right maker. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + leftOrder: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + rightOrder: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + leftSignature: string, + rightSignature: string, + txData?: Partial | undefined, + ): Promise { + assert.isString('leftSignature', leftSignature); + assert.isString('rightSignature', rightSignature); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'matchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),bytes,bytes)', + [leftOrder, rightOrder, leftSignature, rightSignature], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param leftOrder First order to match. + * @param rightOrder Second order to match. + * @param leftSignature Proof that order was created by the left maker. + * @param rightSignature Proof that order was created by the right maker. + * @returns matchedFillResults Amounts filled and fees paid by maker and taker of matched orders. + */ + async callAsync( + leftOrder: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + rightOrder: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + leftSignature: string, + rightSignature: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ + left: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }; + right: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }; + leftMakerAssetSpreadAmount: BigNumber; + }> { + assert.isString('leftSignature', leftSignature); + assert.isString('rightSignature', rightSignature); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'matchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),bytes,bytes)', + [leftOrder, rightOrder, leftSignature, rightSignature], + ); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'matchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),bytes,bytes)', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + left: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }; + right: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }; + leftMakerAssetSpreadAmount: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param leftOrder First order to match. + * @param rightOrder Second order to match. + * @param leftSignature Proof that order was created by the left maker. + * @param rightSignature Proof that order was created by the right maker. + */ + getABIEncodedTransactionData( + leftOrder: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + rightOrder: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + leftSignature: string, + rightSignature: string, + ): string { + assert.isString('leftSignature', leftSignature); + assert.isString('rightSignature', rightSignature); + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'matchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),bytes,bytes)', + [leftOrder, rightOrder, leftSignature, rightSignature], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData( + callData: string, + ): { + left: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }; + right: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }; + leftMakerAssetSpreadAmount: BigNumber; + } { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'matchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),bytes,bytes)', + ); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode<{ + left: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }; + right: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }; + leftMakerAssetSpreadAmount: BigNumber; + }>(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData( + returnData: string, + ): { + left: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }; + right: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }; + leftMakerAssetSpreadAmount: BigNumber; + } { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'matchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),bytes,bytes)', + ); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue<{ + left: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }; + right: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }; + leftMakerAssetSpreadAmount: BigNumber; + }>(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Fills the input order. + * Returns false if the transaction would otherwise revert. + */ + public fillOrderNoThrow = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param order Order struct containing order specifications. + * @param takerAssetFillAmount Desired amount of takerAsset to sell. + * @param signature Proof that order has been created by maker. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + takerAssetFillAmount: BigNumber, + signature: string, + txData?: Partial | undefined, + ): Promise { + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isString('signature', signature); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'fillOrderNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)', + [order, takerAssetFillAmount, signature], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.fillOrderNoThrow.estimateGasAsync.bind(self, order, takerAssetFillAmount, signature), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param order Order struct containing order specifications. + * @param takerAssetFillAmount Desired amount of takerAsset to sell. + * @param signature Proof that order has been created by maker. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + takerAssetFillAmount: BigNumber, + signature: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isString('signature', signature); + const self = (this as any) as ExchangeContract; + const txHashPromise = self.fillOrderNoThrow.sendTransactionAsync( + order, + takerAssetFillAmount, + signature, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param order Order struct containing order specifications. + * @param takerAssetFillAmount Desired amount of takerAsset to sell. + * @param signature Proof that order has been created by maker. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + takerAssetFillAmount: BigNumber, + signature: string, + txData?: Partial | undefined, + ): Promise { + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isString('signature', signature); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'fillOrderNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)', + [order, takerAssetFillAmount, signature], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param order Order struct containing order specifications. + * @param takerAssetFillAmount Desired amount of takerAsset to sell. + * @param signature Proof that order has been created by maker. + * @returns Amounts filled and fees paid by maker and taker. + */ + async callAsync( + order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + takerAssetFillAmount: BigNumber, + signature: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }> { + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isString('signature', signature); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'fillOrderNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)', + [order, takerAssetFillAmount, signature], + ); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'fillOrderNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param order Order struct containing order specifications. + * @param takerAssetFillAmount Desired amount of takerAsset to sell. + * @param signature Proof that order has been created by maker. + */ + getABIEncodedTransactionData( + order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + takerAssetFillAmount: BigNumber, + signature: string, + ): string { + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isString('signature', signature); + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'fillOrderNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)', + [order, takerAssetFillAmount, signature], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData( + callData: string, + ): { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'fillOrderNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)', + ); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData( + returnData: string, + ): { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'fillOrderNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)', + ); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(returnData); + return abiDecodedReturnData; + }, + }; + public assetProxies = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(index_0: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.isString('index_0', index_0); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('assetProxies(bytes4)', [index_0]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('assetProxies(bytes4)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(index_0: string): string { + assert.isString('index_0', index_0); + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments('assetProxies(bytes4)', [index_0]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('assetProxies(bytes4)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('assetProxies(bytes4)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Synchronously cancels multiple orders in a single transaction. + */ + public batchCancelOrders = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param orders Array of order specifications. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + txData?: Partial | undefined, + ): Promise { + assert.isArray('orders', orders); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'batchCancelOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[])', + [orders], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.batchCancelOrders.estimateGasAsync.bind(self, orders), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param orders Array of order specifications. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isArray('orders', orders); + const self = (this as any) as ExchangeContract; + const txHashPromise = self.batchCancelOrders.sendTransactionAsync(orders, txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param orders Array of order specifications. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + txData?: Partial | undefined, + ): Promise { + assert.isArray('orders', orders); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'batchCancelOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[])', + [orders], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param orders Array of order specifications. + */ + async callAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isArray('orders', orders); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'batchCancelOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[])', + [orders], + ); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'batchCancelOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[])', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param orders Array of order specifications. + */ + getABIEncodedTransactionData( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + ): string { + assert.isArray('orders', orders); + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'batchCancelOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[])', + [orders], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'batchCancelOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[])', + ); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'batchCancelOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[])', + ); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Synchronously executes multiple calls of fillOrKill. + */ + public batchFillOrKillOrders = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param orders Array of order specifications. + * @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell + * in orders. + * @param signatures Proofs that orders have been created by makers. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAssetFillAmounts: BigNumber[], + signatures: string[], + txData?: Partial | undefined, + ): Promise { + assert.isArray('orders', orders); + assert.isArray('takerAssetFillAmounts', takerAssetFillAmounts); + assert.isArray('signatures', signatures); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'batchFillOrKillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256[],bytes[])', + [orders, takerAssetFillAmounts, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.batchFillOrKillOrders.estimateGasAsync.bind(self, orders, takerAssetFillAmounts, signatures), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param orders Array of order specifications. + * @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell + * in orders. + * @param signatures Proofs that orders have been created by makers. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAssetFillAmounts: BigNumber[], + signatures: string[], + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isArray('orders', orders); + assert.isArray('takerAssetFillAmounts', takerAssetFillAmounts); + assert.isArray('signatures', signatures); + const self = (this as any) as ExchangeContract; + const txHashPromise = self.batchFillOrKillOrders.sendTransactionAsync( + orders, + takerAssetFillAmounts, + signatures, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param orders Array of order specifications. + * @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell + * in orders. + * @param signatures Proofs that orders have been created by makers. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAssetFillAmounts: BigNumber[], + signatures: string[], + txData?: Partial | undefined, + ): Promise { + assert.isArray('orders', orders); + assert.isArray('takerAssetFillAmounts', takerAssetFillAmounts); + assert.isArray('signatures', signatures); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'batchFillOrKillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256[],bytes[])', + [orders, takerAssetFillAmounts, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param orders Array of order specifications. + * @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell + * in orders. + * @param signatures Proofs that orders have been created by makers. + * @returns Amounts filled and fees paid by makers and taker. NOTE: makerAssetFilledAmount and takerAssetFilledAmount may include amounts filled of different assets. + */ + async callAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAssetFillAmounts: BigNumber[], + signatures: string[], + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }> { + assert.isArray('orders', orders); + assert.isArray('takerAssetFillAmounts', takerAssetFillAmounts); + assert.isArray('signatures', signatures); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'batchFillOrKillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256[],bytes[])', + [orders, takerAssetFillAmounts, signatures], + ); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'batchFillOrKillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256[],bytes[])', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param orders Array of order specifications. + * @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell + * in orders. + * @param signatures Proofs that orders have been created by makers. + */ + getABIEncodedTransactionData( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAssetFillAmounts: BigNumber[], + signatures: string[], + ): string { + assert.isArray('orders', orders); + assert.isArray('takerAssetFillAmounts', takerAssetFillAmounts); + assert.isArray('signatures', signatures); + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'batchFillOrKillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256[],bytes[])', + [orders, takerAssetFillAmounts, signatures], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData( + callData: string, + ): { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'batchFillOrKillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256[],bytes[])', + ); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData( + returnData: string, + ): { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'batchFillOrKillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256[],bytes[])', + ); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(returnData); + return abiDecodedReturnData; + }, + }; + /** + * 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). + */ + public cancelOrdersUpTo = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param targetOrderEpoch Orders created with a salt less or equal to this + * value will be cancelled. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(targetOrderEpoch: BigNumber, txData?: Partial | undefined): Promise { + assert.isBigNumber('targetOrderEpoch', targetOrderEpoch); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('cancelOrdersUpTo(uint256)', [targetOrderEpoch]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.cancelOrdersUpTo.estimateGasAsync.bind(self, targetOrderEpoch), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param targetOrderEpoch Orders created with a salt less or equal to this + * value will be cancelled. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + targetOrderEpoch: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isBigNumber('targetOrderEpoch', targetOrderEpoch); + const self = (this as any) as ExchangeContract; + const txHashPromise = self.cancelOrdersUpTo.sendTransactionAsync(targetOrderEpoch, txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param targetOrderEpoch Orders created with a salt less or equal to this + * value will be cancelled. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(targetOrderEpoch: BigNumber, txData?: Partial | undefined): Promise { + assert.isBigNumber('targetOrderEpoch', targetOrderEpoch); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('cancelOrdersUpTo(uint256)', [targetOrderEpoch]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param targetOrderEpoch Orders created with a salt less or equal to this + * value will be cancelled. + */ + async callAsync( + targetOrderEpoch: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isBigNumber('targetOrderEpoch', targetOrderEpoch); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('cancelOrdersUpTo(uint256)', [targetOrderEpoch]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('cancelOrdersUpTo(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param targetOrderEpoch Orders created with a salt less or equal to this + * value will be cancelled. + */ + getABIEncodedTransactionData(targetOrderEpoch: BigNumber): string { + assert.isBigNumber('targetOrderEpoch', targetOrderEpoch); + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments('cancelOrdersUpTo(uint256)', [ + targetOrderEpoch, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('cancelOrdersUpTo(uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('cancelOrdersUpTo(uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Fills an order with specified parameters and ECDSA signature. + * Returns false if the transaction would otherwise revert. + */ + public batchFillOrdersNoThrow = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param orders Array of order specifications. + * @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell + * in orders. + * @param signatures Proofs that orders have been created by makers. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAssetFillAmounts: BigNumber[], + signatures: string[], + txData?: Partial | undefined, + ): Promise { + assert.isArray('orders', orders); + assert.isArray('takerAssetFillAmounts', takerAssetFillAmounts); + assert.isArray('signatures', signatures); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'batchFillOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256[],bytes[])', + [orders, takerAssetFillAmounts, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.batchFillOrdersNoThrow.estimateGasAsync.bind(self, orders, takerAssetFillAmounts, signatures), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param orders Array of order specifications. + * @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell + * in orders. + * @param signatures Proofs that orders have been created by makers. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAssetFillAmounts: BigNumber[], + signatures: string[], + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isArray('orders', orders); + assert.isArray('takerAssetFillAmounts', takerAssetFillAmounts); + assert.isArray('signatures', signatures); + const self = (this as any) as ExchangeContract; + const txHashPromise = self.batchFillOrdersNoThrow.sendTransactionAsync( + orders, + takerAssetFillAmounts, + signatures, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param orders Array of order specifications. + * @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell + * in orders. + * @param signatures Proofs that orders have been created by makers. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAssetFillAmounts: BigNumber[], + signatures: string[], + txData?: Partial | undefined, + ): Promise { + assert.isArray('orders', orders); + assert.isArray('takerAssetFillAmounts', takerAssetFillAmounts); + assert.isArray('signatures', signatures); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'batchFillOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256[],bytes[])', + [orders, takerAssetFillAmounts, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param orders Array of order specifications. + * @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell + * in orders. + * @param signatures Proofs that orders have been created by makers. + * @returns Amounts filled and fees paid by makers and taker. NOTE: makerAssetFilledAmount and takerAssetFilledAmount may include amounts filled of different assets. + */ + async callAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAssetFillAmounts: BigNumber[], + signatures: string[], + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }> { + assert.isArray('orders', orders); + assert.isArray('takerAssetFillAmounts', takerAssetFillAmounts); + assert.isArray('signatures', signatures); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'batchFillOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256[],bytes[])', + [orders, takerAssetFillAmounts, signatures], + ); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'batchFillOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256[],bytes[])', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param orders Array of order specifications. + * @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell + * in orders. + * @param signatures Proofs that orders have been created by makers. + */ + getABIEncodedTransactionData( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAssetFillAmounts: BigNumber[], + signatures: string[], + ): string { + assert.isArray('orders', orders); + assert.isArray('takerAssetFillAmounts', takerAssetFillAmounts); + assert.isArray('signatures', signatures); + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'batchFillOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256[],bytes[])', + [orders, takerAssetFillAmounts, signatures], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData( + callData: string, + ): { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'batchFillOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256[],bytes[])', + ); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData( + returnData: string, + ): { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'batchFillOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256[],bytes[])', + ); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Gets an asset proxy. + */ + public getAssetProxy = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param assetProxyId Id of the asset proxy. + * @returns The asset proxy registered to assetProxyId. Returns 0x0 if no proxy is registered. + */ + async callAsync( + assetProxyId: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('assetProxyId', assetProxyId); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('getAssetProxy(bytes4)', [assetProxyId]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getAssetProxy(bytes4)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param assetProxyId Id of the asset proxy. + */ + getABIEncodedTransactionData(assetProxyId: string): string { + assert.isString('assetProxyId', assetProxyId); + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments('getAssetProxy(bytes4)', [assetProxyId]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('getAssetProxy(bytes4)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('getAssetProxy(bytes4)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public transactions = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + index_0: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('index_0', index_0); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('transactions(bytes32)', [index_0]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transactions(bytes32)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(index_0: string): string { + assert.isString('index_0', index_0); + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments('transactions(bytes32)', [index_0]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): boolean { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('transactions(bytes32)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): boolean { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('transactions(bytes32)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Fills the input order. Reverts if exact takerAssetFillAmount not filled. + */ + public fillOrKillOrder = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param order Order struct containing order specifications. + * @param takerAssetFillAmount Desired amount of takerAsset to sell. + * @param signature Proof that order has been created by maker. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + takerAssetFillAmount: BigNumber, + signature: string, + txData?: Partial | undefined, + ): Promise { + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isString('signature', signature); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'fillOrKillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)', + [order, takerAssetFillAmount, signature], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.fillOrKillOrder.estimateGasAsync.bind(self, order, takerAssetFillAmount, signature), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param order Order struct containing order specifications. + * @param takerAssetFillAmount Desired amount of takerAsset to sell. + * @param signature Proof that order has been created by maker. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + takerAssetFillAmount: BigNumber, + signature: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isString('signature', signature); + const self = (this as any) as ExchangeContract; + const txHashPromise = self.fillOrKillOrder.sendTransactionAsync( + order, + takerAssetFillAmount, + signature, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param order Order struct containing order specifications. + * @param takerAssetFillAmount Desired amount of takerAsset to sell. + * @param signature Proof that order has been created by maker. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + takerAssetFillAmount: BigNumber, + signature: string, + txData?: Partial | undefined, + ): Promise { + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isString('signature', signature); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'fillOrKillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)', + [order, takerAssetFillAmount, signature], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param order Order struct containing order specifications. + * @param takerAssetFillAmount Desired amount of takerAsset to sell. + * @param signature Proof that order has been created by maker. + */ + async callAsync( + order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + takerAssetFillAmount: BigNumber, + signature: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }> { + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isString('signature', signature); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'fillOrKillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)', + [order, takerAssetFillAmount, signature], + ); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'fillOrKillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param order Order struct containing order specifications. + * @param takerAssetFillAmount Desired amount of takerAsset to sell. + * @param signature Proof that order has been created by maker. + */ + getABIEncodedTransactionData( + order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + takerAssetFillAmount: BigNumber, + signature: string, + ): string { + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isString('signature', signature); + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'fillOrKillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)', + [order, takerAssetFillAmount, signature], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData( + callData: string, + ): { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'fillOrKillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)', + ); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData( + returnData: string, + ): { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'fillOrKillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)', + ); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Approves/unnapproves a Validator contract to verify signatures on signer's behalf. + */ + public setSignatureValidatorApproval = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param validatorAddress Address of Validator contract. + * @param approval Approval or disapproval of Validator contract. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + validatorAddress: string, + approval: boolean, + txData?: Partial | undefined, + ): Promise { + assert.isString('validatorAddress', validatorAddress); + assert.isBoolean('approval', approval); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('setSignatureValidatorApproval(address,bool)', [ + validatorAddress.toLowerCase(), + approval, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.setSignatureValidatorApproval.estimateGasAsync.bind( + self, + validatorAddress.toLowerCase(), + approval, + ), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param validatorAddress Address of Validator contract. + * @param approval Approval or disapproval of Validator contract. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + validatorAddress: string, + approval: boolean, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('validatorAddress', validatorAddress); + assert.isBoolean('approval', approval); + const self = (this as any) as ExchangeContract; + const txHashPromise = self.setSignatureValidatorApproval.sendTransactionAsync( + validatorAddress.toLowerCase(), + approval, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param validatorAddress Address of Validator contract. + * @param approval Approval or disapproval of Validator contract. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + validatorAddress: string, + approval: boolean, + txData?: Partial | undefined, + ): Promise { + assert.isString('validatorAddress', validatorAddress); + assert.isBoolean('approval', approval); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('setSignatureValidatorApproval(address,bool)', [ + validatorAddress.toLowerCase(), + approval, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param validatorAddress Address of Validator contract. + * @param approval Approval or disapproval of Validator contract. + */ + async callAsync( + validatorAddress: string, + approval: boolean, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('validatorAddress', validatorAddress); + assert.isBoolean('approval', approval); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('setSignatureValidatorApproval(address,bool)', [ + validatorAddress.toLowerCase(), + approval, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('setSignatureValidatorApproval(address,bool)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param validatorAddress Address of Validator contract. + * @param approval Approval or disapproval of Validator contract. + */ + getABIEncodedTransactionData(validatorAddress: string, approval: boolean): string { + assert.isString('validatorAddress', validatorAddress); + assert.isBoolean('approval', approval); + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'setSignatureValidatorApproval(address,bool)', + [validatorAddress.toLowerCase(), approval], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('setSignatureValidatorApproval(address,bool)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('setSignatureValidatorApproval(address,bool)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public allowedValidators = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + index_0: string, + index_1: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('index_0', index_0); + assert.isString('index_1', index_1); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('allowedValidators(address,address)', [ + index_0.toLowerCase(), + index_1.toLowerCase(), + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('allowedValidators(address,address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(index_0: string, index_1: string): string { + assert.isString('index_0', index_0); + assert.isString('index_1', index_1); + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments('allowedValidators(address,address)', [ + index_0.toLowerCase(), + index_1.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): boolean { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('allowedValidators(address,address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): boolean { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('allowedValidators(address,address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Synchronously executes multiple calls of fillOrder until total amount of takerAsset is sold by taker. + */ + public marketSellOrders = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param orders Array of order specifications. + * @param takerAssetFillAmount Desired amount of takerAsset to sell. + * @param signatures Proofs that orders have been created by makers. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAssetFillAmount: BigNumber, + signatures: string[], + txData?: Partial | undefined, + ): Promise { + assert.isArray('orders', orders); + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isArray('signatures', signatures); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'marketSellOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])', + [orders, takerAssetFillAmount, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.marketSellOrders.estimateGasAsync.bind(self, orders, takerAssetFillAmount, signatures), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param orders Array of order specifications. + * @param takerAssetFillAmount Desired amount of takerAsset to sell. + * @param signatures Proofs that orders have been created by makers. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAssetFillAmount: BigNumber, + signatures: string[], + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isArray('orders', orders); + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isArray('signatures', signatures); + const self = (this as any) as ExchangeContract; + const txHashPromise = self.marketSellOrders.sendTransactionAsync( + orders, + takerAssetFillAmount, + signatures, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param orders Array of order specifications. + * @param takerAssetFillAmount Desired amount of takerAsset to sell. + * @param signatures Proofs that orders have been created by makers. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAssetFillAmount: BigNumber, + signatures: string[], + txData?: Partial | undefined, + ): Promise { + assert.isArray('orders', orders); + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isArray('signatures', signatures); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'marketSellOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])', + [orders, takerAssetFillAmount, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param orders Array of order specifications. + * @param takerAssetFillAmount Desired amount of takerAsset to sell. + * @param signatures Proofs that orders have been created by makers. + * @returns Amounts filled and fees paid by makers and taker. + */ + async callAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAssetFillAmount: BigNumber, + signatures: string[], + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }> { + assert.isArray('orders', orders); + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isArray('signatures', signatures); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'marketSellOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])', + [orders, takerAssetFillAmount, signatures], + ); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'marketSellOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param orders Array of order specifications. + * @param takerAssetFillAmount Desired amount of takerAsset to sell. + * @param signatures Proofs that orders have been created by makers. + */ + getABIEncodedTransactionData( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAssetFillAmount: BigNumber, + signatures: string[], + ): string { + assert.isArray('orders', orders); + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isArray('signatures', signatures); + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'marketSellOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])', + [orders, takerAssetFillAmount, signatures], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData( + callData: string, + ): { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'marketSellOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])', + ); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData( + returnData: string, + ): { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'marketSellOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])', + ); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Fetches information for all passed in orders. + */ + public getOrdersInfo = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param orders Array of order specifications. + * @returns Array of OrderInfo instances that correspond to each order. + */ + async callAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise> { + assert.isArray('orders', orders); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'getOrdersInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[])', + [orders], + ); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'getOrdersInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[])', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue< + Array<{ orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }> + >(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param orders Array of order specifications. + */ + getABIEncodedTransactionData( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + ): string { + assert.isArray('orders', orders); + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'getOrdersInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[])', + [orders], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData( + callData: string, + ): Array<{ orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }> { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'getOrdersInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[])', + ); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode< + Array<{ orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }> + >(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData( + returnData: string, + ): Array<{ orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }> { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'getOrdersInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[])', + ); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue< + Array<{ orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }> + >(returnData); + return abiDecodedReturnData; + }, + }; + public preSigned = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + index_0: string, + index_1: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('index_0', index_0); + assert.isString('index_1', index_1); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('preSigned(bytes32,address)', [ + index_0, + index_1.toLowerCase(), + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('preSigned(bytes32,address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(index_0: string, index_1: string): string { + assert.isString('index_0', index_0); + assert.isString('index_1', index_1); + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments('preSigned(bytes32,address)', [ + index_0, + index_1.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): boolean { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('preSigned(bytes32,address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): boolean { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('preSigned(bytes32,address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public owner = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('owner()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('owner()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments('owner()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('owner()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('owner()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Verifies that a hash has been signed by the given signer. + */ + public isValidSignature = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param hash Any 32 byte hash. + * @param signerAddress Address that should have signed the given hash. + * @param signature Proof that the hash has been signed by signer. + * @returns True if the address recovered from the provided signature matches the input signer address. + */ + async callAsync( + hash: string, + signerAddress: string, + signature: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('hash', hash); + assert.isString('signerAddress', signerAddress); + assert.isString('signature', signature); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('isValidSignature(bytes32,address,bytes)', [ + hash, + signerAddress.toLowerCase(), + signature, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('isValidSignature(bytes32,address,bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param hash Any 32 byte hash. + * @param signerAddress Address that should have signed the given hash. + * @param signature Proof that the hash has been signed by signer. + */ + getABIEncodedTransactionData(hash: string, signerAddress: string, signature: string): string { + assert.isString('hash', hash); + assert.isString('signerAddress', signerAddress); + assert.isString('signature', signature); + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments('isValidSignature(bytes32,address,bytes)', [ + hash, + signerAddress.toLowerCase(), + signature, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): boolean { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('isValidSignature(bytes32,address,bytes)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): boolean { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('isValidSignature(bytes32,address,bytes)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Synchronously executes multiple fill orders in a single transaction until total amount is bought by taker. + * Returns false if the transaction would otherwise revert. + */ + public marketBuyOrdersNoThrow = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param orders Array of order specifications. + * @param makerAssetFillAmount Desired amount of makerAsset to buy. + * @param signatures Proofs that orders have been signed by makers. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + makerAssetFillAmount: BigNumber, + signatures: string[], + txData?: Partial | undefined, + ): Promise { + assert.isArray('orders', orders); + assert.isBigNumber('makerAssetFillAmount', makerAssetFillAmount); + assert.isArray('signatures', signatures); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'marketBuyOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])', + [orders, makerAssetFillAmount, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.marketBuyOrdersNoThrow.estimateGasAsync.bind(self, orders, makerAssetFillAmount, signatures), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param orders Array of order specifications. + * @param makerAssetFillAmount Desired amount of makerAsset to buy. + * @param signatures Proofs that orders have been signed by makers. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + makerAssetFillAmount: BigNumber, + signatures: string[], + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isArray('orders', orders); + assert.isBigNumber('makerAssetFillAmount', makerAssetFillAmount); + assert.isArray('signatures', signatures); + const self = (this as any) as ExchangeContract; + const txHashPromise = self.marketBuyOrdersNoThrow.sendTransactionAsync( + orders, + makerAssetFillAmount, + signatures, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param orders Array of order specifications. + * @param makerAssetFillAmount Desired amount of makerAsset to buy. + * @param signatures Proofs that orders have been signed by makers. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + makerAssetFillAmount: BigNumber, + signatures: string[], + txData?: Partial | undefined, + ): Promise { + assert.isArray('orders', orders); + assert.isBigNumber('makerAssetFillAmount', makerAssetFillAmount); + assert.isArray('signatures', signatures); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'marketBuyOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])', + [orders, makerAssetFillAmount, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param orders Array of order specifications. + * @param makerAssetFillAmount Desired amount of makerAsset to buy. + * @param signatures Proofs that orders have been signed by makers. + * @returns Amounts filled and fees paid by makers and taker. + */ + async callAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + makerAssetFillAmount: BigNumber, + signatures: string[], + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }> { + assert.isArray('orders', orders); + assert.isBigNumber('makerAssetFillAmount', makerAssetFillAmount); + assert.isArray('signatures', signatures); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'marketBuyOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])', + [orders, makerAssetFillAmount, signatures], + ); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'marketBuyOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param orders Array of order specifications. + * @param makerAssetFillAmount Desired amount of makerAsset to buy. + * @param signatures Proofs that orders have been signed by makers. + */ + getABIEncodedTransactionData( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + makerAssetFillAmount: BigNumber, + signatures: string[], + ): string { + assert.isArray('orders', orders); + assert.isBigNumber('makerAssetFillAmount', makerAssetFillAmount); + assert.isArray('signatures', signatures); + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'marketBuyOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])', + [orders, makerAssetFillAmount, signatures], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData( + callData: string, + ): { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'marketBuyOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])', + ); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData( + returnData: string, + ): { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'marketBuyOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])', + ); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Fills the input order. + */ + public fillOrder = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param order Order struct containing order specifications. + * @param takerAssetFillAmount Desired amount of takerAsset to sell. + * @param signature Proof that order has been created by maker. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + takerAssetFillAmount: BigNumber, + signature: string, + txData?: Partial | undefined, + ): Promise { + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isString('signature', signature); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'fillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)', + [order, takerAssetFillAmount, signature], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.fillOrder.estimateGasAsync.bind(self, order, takerAssetFillAmount, signature), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param order Order struct containing order specifications. + * @param takerAssetFillAmount Desired amount of takerAsset to sell. + * @param signature Proof that order has been created by maker. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + takerAssetFillAmount: BigNumber, + signature: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isString('signature', signature); + const self = (this as any) as ExchangeContract; + const txHashPromise = self.fillOrder.sendTransactionAsync(order, takerAssetFillAmount, signature, txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param order Order struct containing order specifications. + * @param takerAssetFillAmount Desired amount of takerAsset to sell. + * @param signature Proof that order has been created by maker. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + takerAssetFillAmount: BigNumber, + signature: string, + txData?: Partial | undefined, + ): Promise { + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isString('signature', signature); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'fillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)', + [order, takerAssetFillAmount, signature], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param order Order struct containing order specifications. + * @param takerAssetFillAmount Desired amount of takerAsset to sell. + * @param signature Proof that order has been created by maker. + * @returns Amounts filled and fees paid by maker and taker. + */ + async callAsync( + order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + takerAssetFillAmount: BigNumber, + signature: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }> { + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isString('signature', signature); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'fillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)', + [order, takerAssetFillAmount, signature], + ); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'fillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param order Order struct containing order specifications. + * @param takerAssetFillAmount Desired amount of takerAsset to sell. + * @param signature Proof that order has been created by maker. + */ + getABIEncodedTransactionData( + order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + takerAssetFillAmount: BigNumber, + signature: string, + ): string { + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isString('signature', signature); + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'fillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)', + [order, takerAssetFillAmount, signature], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData( + callData: string, + ): { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'fillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)', + ); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData( + returnData: string, + ): { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'fillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)', + ); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Executes an exchange method call in the context of signer. + */ + public executeTransaction = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param salt Arbitrary number to ensure uniqueness of transaction hash. + * @param signerAddress Address of transaction signer. + * @param data AbiV2 encoded calldata. + * @param signature Proof of signer transaction by signer. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + salt: BigNumber, + signerAddress: string, + data: string, + signature: string, + txData?: Partial | undefined, + ): Promise { + assert.isBigNumber('salt', salt); + assert.isString('signerAddress', signerAddress); + assert.isString('data', data); + assert.isString('signature', signature); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('executeTransaction(uint256,address,bytes,bytes)', [ + salt, + signerAddress.toLowerCase(), + data, + signature, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.executeTransaction.estimateGasAsync.bind(self, salt, signerAddress.toLowerCase(), data, signature), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param salt Arbitrary number to ensure uniqueness of transaction hash. + * @param signerAddress Address of transaction signer. + * @param data AbiV2 encoded calldata. + * @param signature Proof of signer transaction by signer. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + salt: BigNumber, + signerAddress: string, + data: string, + signature: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isBigNumber('salt', salt); + assert.isString('signerAddress', signerAddress); + assert.isString('data', data); + assert.isString('signature', signature); + const self = (this as any) as ExchangeContract; + const txHashPromise = self.executeTransaction.sendTransactionAsync( + salt, + signerAddress.toLowerCase(), + data, + signature, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param salt Arbitrary number to ensure uniqueness of transaction hash. + * @param signerAddress Address of transaction signer. + * @param data AbiV2 encoded calldata. + * @param signature Proof of signer transaction by signer. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + salt: BigNumber, + signerAddress: string, + data: string, + signature: string, + txData?: Partial | undefined, + ): Promise { + assert.isBigNumber('salt', salt); + assert.isString('signerAddress', signerAddress); + assert.isString('data', data); + assert.isString('signature', signature); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('executeTransaction(uint256,address,bytes,bytes)', [ + salt, + signerAddress.toLowerCase(), + data, + signature, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param salt Arbitrary number to ensure uniqueness of transaction hash. + * @param signerAddress Address of transaction signer. + * @param data AbiV2 encoded calldata. + * @param signature Proof of signer transaction by signer. + */ + async callAsync( + salt: BigNumber, + signerAddress: string, + data: string, + signature: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isBigNumber('salt', salt); + assert.isString('signerAddress', signerAddress); + assert.isString('data', data); + assert.isString('signature', signature); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('executeTransaction(uint256,address,bytes,bytes)', [ + salt, + signerAddress.toLowerCase(), + data, + signature, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('executeTransaction(uint256,address,bytes,bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param salt Arbitrary number to ensure uniqueness of transaction hash. + * @param signerAddress Address of transaction signer. + * @param data AbiV2 encoded calldata. + * @param signature Proof of signer transaction by signer. + */ + getABIEncodedTransactionData(salt: BigNumber, signerAddress: string, data: string, signature: string): string { + assert.isBigNumber('salt', salt); + assert.isString('signerAddress', signerAddress); + assert.isString('data', data); + assert.isString('signature', signature); + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'executeTransaction(uint256,address,bytes,bytes)', + [salt, signerAddress.toLowerCase(), data, signature], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('executeTransaction(uint256,address,bytes,bytes)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('executeTransaction(uint256,address,bytes,bytes)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Registers an asset proxy to its asset proxy id. + * Once an asset proxy is registered, it cannot be unregistered. + */ + public registerAssetProxy = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param assetProxy Address of new asset proxy to register. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(assetProxy: string, txData?: Partial | undefined): Promise { + assert.isString('assetProxy', assetProxy); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('registerAssetProxy(address)', [assetProxy.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.registerAssetProxy.estimateGasAsync.bind(self, assetProxy.toLowerCase()), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param assetProxy Address of new asset proxy to register. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + assetProxy: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('assetProxy', assetProxy); + const self = (this as any) as ExchangeContract; + const txHashPromise = self.registerAssetProxy.sendTransactionAsync(assetProxy.toLowerCase(), txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param assetProxy Address of new asset proxy to register. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(assetProxy: string, txData?: Partial | undefined): Promise { + assert.isString('assetProxy', assetProxy); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('registerAssetProxy(address)', [assetProxy.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param assetProxy Address of new asset proxy to register. + */ + async callAsync( + assetProxy: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('assetProxy', assetProxy); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('registerAssetProxy(address)', [assetProxy.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('registerAssetProxy(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param assetProxy Address of new asset proxy to register. + */ + getABIEncodedTransactionData(assetProxy: string): string { + assert.isString('assetProxy', assetProxy); + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments('registerAssetProxy(address)', [ + assetProxy.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('registerAssetProxy(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('registerAssetProxy(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Gets information about an order: status, hash, and amount filled. + */ + public getOrderInfo = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param order Order to gather information on. + * @returns OrderInfo Information about the order and its state. See LibOrder.OrderInfo for a complete description. + */ + async callAsync( + order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'getOrderInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes))', + [order], + ); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'getOrderInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes))', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + orderStatus: number; + orderHash: string; + orderTakerAssetFilledAmount: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param order Order to gather information on. + */ + getABIEncodedTransactionData(order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }): string { + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'getOrderInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes))', + [order], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData( + callData: string, + ): { orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber } { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'getOrderInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes))', + ); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode<{ + orderStatus: number; + orderHash: string; + orderTakerAssetFilledAmount: BigNumber; + }>(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData( + returnData: string, + ): { orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber } { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'getOrderInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes))', + ); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue<{ + orderStatus: number; + orderHash: string; + orderTakerAssetFilledAmount: BigNumber; + }>(returnData); + return abiDecodedReturnData; + }, + }; + /** + * After calling, the order can not be filled anymore. + * Throws if order is invalid or sender does not have permission to cancel. + */ + public cancelOrder = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param order Order to cancel. Order must be OrderStatus.FILLABLE. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + txData?: Partial | undefined, + ): Promise { + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'cancelOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes))', + [order], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.cancelOrder.estimateGasAsync.bind(self, order), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param order Order to cancel. Order must be OrderStatus.FILLABLE. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + const self = (this as any) as ExchangeContract; + const txHashPromise = self.cancelOrder.sendTransactionAsync(order, txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param order Order to cancel. Order must be OrderStatus.FILLABLE. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + txData?: Partial | undefined, + ): Promise { + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'cancelOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes))', + [order], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param order Order to cancel. Order must be OrderStatus.FILLABLE. + */ + async callAsync( + order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'cancelOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes))', + [order], + ); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'cancelOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes))', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param order Order to cancel. Order must be OrderStatus.FILLABLE. + */ + getABIEncodedTransactionData(order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }): string { + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'cancelOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes))', + [order], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'cancelOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes))', + ); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'cancelOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes))', + ); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public orderEpoch = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + index_0: string, + index_1: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('index_0', index_0); + assert.isString('index_1', index_1); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('orderEpoch(address,address)', [ + index_0.toLowerCase(), + index_1.toLowerCase(), + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('orderEpoch(address,address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(index_0: string, index_1: string): string { + assert.isString('index_0', index_0); + assert.isString('index_1', index_1); + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments('orderEpoch(address,address)', [ + index_0.toLowerCase(), + index_1.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): BigNumber { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('orderEpoch(address,address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): BigNumber { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('orderEpoch(address,address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public ZRX_ASSET_DATA = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('ZRX_ASSET_DATA()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('ZRX_ASSET_DATA()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments('ZRX_ASSET_DATA()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('ZRX_ASSET_DATA()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('ZRX_ASSET_DATA()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Synchronously executes multiple calls of fillOrder until total amount of takerAsset is sold by taker. + * Returns false if the transaction would otherwise revert. + */ + public marketSellOrdersNoThrow = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param orders Array of order specifications. + * @param takerAssetFillAmount Desired amount of takerAsset to sell. + * @param signatures Proofs that orders have been signed by makers. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAssetFillAmount: BigNumber, + signatures: string[], + txData?: Partial | undefined, + ): Promise { + assert.isArray('orders', orders); + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isArray('signatures', signatures); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'marketSellOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])', + [orders, takerAssetFillAmount, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.marketSellOrdersNoThrow.estimateGasAsync.bind(self, orders, takerAssetFillAmount, signatures), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param orders Array of order specifications. + * @param takerAssetFillAmount Desired amount of takerAsset to sell. + * @param signatures Proofs that orders have been signed by makers. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAssetFillAmount: BigNumber, + signatures: string[], + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isArray('orders', orders); + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isArray('signatures', signatures); + const self = (this as any) as ExchangeContract; + const txHashPromise = self.marketSellOrdersNoThrow.sendTransactionAsync( + orders, + takerAssetFillAmount, + signatures, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param orders Array of order specifications. + * @param takerAssetFillAmount Desired amount of takerAsset to sell. + * @param signatures Proofs that orders have been signed by makers. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAssetFillAmount: BigNumber, + signatures: string[], + txData?: Partial | undefined, + ): Promise { + assert.isArray('orders', orders); + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isArray('signatures', signatures); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'marketSellOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])', + [orders, takerAssetFillAmount, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param orders Array of order specifications. + * @param takerAssetFillAmount Desired amount of takerAsset to sell. + * @param signatures Proofs that orders have been signed by makers. + * @returns Amounts filled and fees paid by makers and taker. + */ + async callAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAssetFillAmount: BigNumber, + signatures: string[], + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }> { + assert.isArray('orders', orders); + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isArray('signatures', signatures); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'marketSellOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])', + [orders, takerAssetFillAmount, signatures], + ); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'marketSellOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param orders Array of order specifications. + * @param takerAssetFillAmount Desired amount of takerAsset to sell. + * @param signatures Proofs that orders have been signed by makers. + */ + getABIEncodedTransactionData( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAssetFillAmount: BigNumber, + signatures: string[], + ): string { + assert.isArray('orders', orders); + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isArray('signatures', signatures); + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'marketSellOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])', + [orders, takerAssetFillAmount, signatures], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData( + callData: string, + ): { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'marketSellOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])', + ); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData( + returnData: string, + ): { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'marketSellOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])', + ); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(returnData); + return abiDecodedReturnData; + }, + }; + public EIP712_DOMAIN_HASH = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('EIP712_DOMAIN_HASH()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('EIP712_DOMAIN_HASH()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments('EIP712_DOMAIN_HASH()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('EIP712_DOMAIN_HASH()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('EIP712_DOMAIN_HASH()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Synchronously executes multiple calls of fillOrder until total amount of makerAsset is bought by taker. + */ + public marketBuyOrders = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param orders Array of order specifications. + * @param makerAssetFillAmount Desired amount of makerAsset to buy. + * @param signatures Proofs that orders have been signed by makers. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + makerAssetFillAmount: BigNumber, + signatures: string[], + txData?: Partial | undefined, + ): Promise { + assert.isArray('orders', orders); + assert.isBigNumber('makerAssetFillAmount', makerAssetFillAmount); + assert.isArray('signatures', signatures); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'marketBuyOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])', + [orders, makerAssetFillAmount, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.marketBuyOrders.estimateGasAsync.bind(self, orders, makerAssetFillAmount, signatures), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param orders Array of order specifications. + * @param makerAssetFillAmount Desired amount of makerAsset to buy. + * @param signatures Proofs that orders have been signed by makers. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + makerAssetFillAmount: BigNumber, + signatures: string[], + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isArray('orders', orders); + assert.isBigNumber('makerAssetFillAmount', makerAssetFillAmount); + assert.isArray('signatures', signatures); + const self = (this as any) as ExchangeContract; + const txHashPromise = self.marketBuyOrders.sendTransactionAsync( + orders, + makerAssetFillAmount, + signatures, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param orders Array of order specifications. + * @param makerAssetFillAmount Desired amount of makerAsset to buy. + * @param signatures Proofs that orders have been signed by makers. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + makerAssetFillAmount: BigNumber, + signatures: string[], + txData?: Partial | undefined, + ): Promise { + assert.isArray('orders', orders); + assert.isBigNumber('makerAssetFillAmount', makerAssetFillAmount); + assert.isArray('signatures', signatures); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'marketBuyOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])', + [orders, makerAssetFillAmount, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param orders Array of order specifications. + * @param makerAssetFillAmount Desired amount of makerAsset to buy. + * @param signatures Proofs that orders have been signed by makers. + * @returns Amounts filled and fees paid by makers and taker. + */ + async callAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + makerAssetFillAmount: BigNumber, + signatures: string[], + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }> { + assert.isArray('orders', orders); + assert.isBigNumber('makerAssetFillAmount', makerAssetFillAmount); + assert.isArray('signatures', signatures); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments( + 'marketBuyOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])', + [orders, makerAssetFillAmount, signatures], + ); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'marketBuyOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param orders Array of order specifications. + * @param makerAssetFillAmount Desired amount of makerAsset to buy. + * @param signatures Proofs that orders have been signed by makers. + */ + getABIEncodedTransactionData( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + makerAssetFillAmount: BigNumber, + signatures: string[], + ): string { + assert.isArray('orders', orders); + assert.isBigNumber('makerAssetFillAmount', makerAssetFillAmount); + assert.isArray('signatures', signatures); + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'marketBuyOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])', + [orders, makerAssetFillAmount, signatures], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData( + callData: string, + ): { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'marketBuyOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])', + ); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData( + returnData: string, + ): { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder( + 'marketBuyOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])', + ); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }>(returnData); + return abiDecodedReturnData; + }, + }; + public currentContextAddress = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('currentContextAddress()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('currentContextAddress()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments('currentContextAddress()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('currentContextAddress()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('currentContextAddress()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public transferOwnership = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(newOwner: string, txData?: Partial | undefined): Promise { + assert.isString('newOwner', newOwner); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.transferOwnership.estimateGasAsync.bind(self, newOwner.toLowerCase()), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + newOwner: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('newOwner', newOwner); + const self = (this as any) as ExchangeContract; + const txHashPromise = self.transferOwnership.sendTransactionAsync(newOwner.toLowerCase(), txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(newOwner: string, txData?: Partial | undefined): Promise { + assert.isString('newOwner', newOwner); + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(newOwner: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.isString('newOwner', newOwner); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(newOwner: string): string { + assert.isString('newOwner', newOwner); + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments('transferOwnership(address)', [ + newOwner.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public VERSION = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ExchangeContract; + const encodedData = self._strictEncodeArguments('VERSION()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('VERSION()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as ExchangeContract; + const abiEncodedTransactionData = self._strictEncodeArguments('VERSION()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('VERSION()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder('VERSION()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + private readonly _subscriptionManager: SubscriptionManager; + public static async deployFrom0xArtifactAsync( + artifact: ContractArtifact | SimpleContractArtifact, + supportedProvider: SupportedProvider, + txDefaults: Partial, + logDecodeDependencies: { [contractName: string]: ContractArtifact | SimpleContractArtifact }, + _zrxAssetData: string, + ): 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 ExchangeContract.deployAsync( + bytecode, + abi, + provider, + txDefaults, + logDecodeDependenciesAbiOnly, + _zrxAssetData, + ); + } + public static async deployAsync( + bytecode: string, + abi: ContractAbi, + supportedProvider: SupportedProvider, + txDefaults: Partial, + logDecodeDependencies: { [contractName: string]: ContractAbi }, + _zrxAssetData: string, + ): 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); + [_zrxAssetData] = BaseContract._formatABIDataItemList( + constructorAbi.inputs, + [_zrxAssetData], + BaseContract._bigNumberToString, + ); + const iface = new ethers.utils.Interface(abi); + const deployInfo = iface.deployFunction; + const txData = deployInfo.encode(bytecode, [_zrxAssetData]); + const web3Wrapper = new Web3Wrapper(provider); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { 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(`Exchange successfully deployed at ${txReceipt.contractAddress}`); + const contractInstance = new ExchangeContract( + txReceipt.contractAddress as string, + provider, + txDefaults, + logDecodeDependencies, + ); + contractInstance.constructorArgs = [_zrxAssetData]; + return contractInstance; + } + + /** + * @returns The contract ABI + */ + public static ABI(): ContractAbi { + const abi = [ + { + constant: true, + inputs: [ + { + name: 'index_0', + type: 'bytes32', + }, + ], + name: 'filled', + outputs: [ + { + name: '', + type: 'uint256', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'orders', + type: 'tuple[]', + 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: 'takerAssetFillAmounts', + type: 'uint256[]', + }, + { + name: 'signatures', + type: 'bytes[]', + }, + ], + name: 'batchFillOrders', + outputs: [ + { + name: 'totalFillResults', + type: 'tuple', + components: [ + { + name: 'makerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'takerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'makerFeePaid', + type: 'uint256', + }, + { + name: 'takerFeePaid', + type: 'uint256', + }, + ], + }, + ], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'index_0', + type: 'bytes32', + }, + ], + name: 'cancelled', + outputs: [ + { + name: '', + type: 'bool', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'hash', + type: 'bytes32', + }, + { + name: 'signerAddress', + type: 'address', + }, + { + name: 'signature', + type: 'bytes', + }, + ], + name: 'preSign', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'leftOrder', + type: 'tuple', + 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: 'rightOrder', + type: 'tuple', + 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: 'leftSignature', + type: 'bytes', + }, + { + name: 'rightSignature', + type: 'bytes', + }, + ], + name: 'matchOrders', + outputs: [ + { + name: 'matchedFillResults', + type: 'tuple', + components: [ + { + name: 'left', + type: 'tuple', + components: [ + { + name: 'makerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'takerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'makerFeePaid', + type: 'uint256', + }, + { + name: 'takerFeePaid', + type: 'uint256', + }, + ], + }, + { + name: 'right', + type: 'tuple', + components: [ + { + name: 'makerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'takerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'makerFeePaid', + type: 'uint256', + }, + { + name: 'takerFeePaid', + type: 'uint256', + }, + ], + }, + { + name: 'leftMakerAssetSpreadAmount', + type: 'uint256', + }, + ], + }, + ], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'order', + type: 'tuple', + 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: 'takerAssetFillAmount', + type: 'uint256', + }, + { + name: 'signature', + type: 'bytes', + }, + ], + name: 'fillOrderNoThrow', + outputs: [ + { + name: 'fillResults', + type: 'tuple', + components: [ + { + name: 'makerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'takerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'makerFeePaid', + type: 'uint256', + }, + { + name: 'takerFeePaid', + type: 'uint256', + }, + ], + }, + ], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'index_0', + type: 'bytes4', + }, + ], + name: 'assetProxies', + outputs: [ + { + name: '', + type: 'address', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'orders', + type: 'tuple[]', + 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: 'batchCancelOrders', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'orders', + type: 'tuple[]', + 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: 'takerAssetFillAmounts', + type: 'uint256[]', + }, + { + name: 'signatures', + type: 'bytes[]', + }, + ], + name: 'batchFillOrKillOrders', + outputs: [ + { + name: 'totalFillResults', + type: 'tuple', + components: [ + { + name: 'makerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'takerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'makerFeePaid', + type: 'uint256', + }, + { + name: 'takerFeePaid', + type: 'uint256', + }, + ], + }, + ], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'targetOrderEpoch', + type: 'uint256', + }, + ], + name: 'cancelOrdersUpTo', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'orders', + type: 'tuple[]', + 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: 'takerAssetFillAmounts', + type: 'uint256[]', + }, + { + name: 'signatures', + type: 'bytes[]', + }, + ], + name: 'batchFillOrdersNoThrow', + outputs: [ + { + name: 'totalFillResults', + type: 'tuple', + components: [ + { + name: 'makerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'takerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'makerFeePaid', + type: 'uint256', + }, + { + name: 'takerFeePaid', + type: 'uint256', + }, + ], + }, + ], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'assetProxyId', + type: 'bytes4', + }, + ], + name: 'getAssetProxy', + outputs: [ + { + name: '', + type: 'address', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'index_0', + type: 'bytes32', + }, + ], + name: 'transactions', + outputs: [ + { + name: '', + type: 'bool', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'order', + type: 'tuple', + 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: 'takerAssetFillAmount', + type: 'uint256', + }, + { + name: 'signature', + type: 'bytes', + }, + ], + name: 'fillOrKillOrder', + outputs: [ + { + name: 'fillResults', + type: 'tuple', + components: [ + { + name: 'makerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'takerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'makerFeePaid', + type: 'uint256', + }, + { + name: 'takerFeePaid', + type: 'uint256', + }, + ], + }, + ], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'validatorAddress', + type: 'address', + }, + { + name: 'approval', + type: 'bool', + }, + ], + name: 'setSignatureValidatorApproval', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'index_0', + type: 'address', + }, + { + name: 'index_1', + type: 'address', + }, + ], + name: 'allowedValidators', + outputs: [ + { + name: '', + type: 'bool', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'orders', + type: 'tuple[]', + 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: 'takerAssetFillAmount', + type: 'uint256', + }, + { + name: 'signatures', + type: 'bytes[]', + }, + ], + name: 'marketSellOrders', + outputs: [ + { + name: 'totalFillResults', + type: 'tuple', + components: [ + { + name: 'makerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'takerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'makerFeePaid', + type: 'uint256', + }, + { + name: 'takerFeePaid', + type: 'uint256', + }, + ], + }, + ], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'orders', + type: 'tuple[]', + 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: 'getOrdersInfo', + outputs: [ + { + name: '', + type: 'tuple[]', + components: [ + { + name: 'orderStatus', + type: 'uint8', + }, + { + name: 'orderHash', + type: 'bytes32', + }, + { + name: 'orderTakerAssetFilledAmount', + type: 'uint256', + }, + ], + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'index_0', + type: 'bytes32', + }, + { + name: 'index_1', + type: 'address', + }, + ], + name: 'preSigned', + outputs: [ + { + name: '', + type: 'bool', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'owner', + outputs: [ + { + name: '', + type: 'address', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'hash', + type: 'bytes32', + }, + { + name: 'signerAddress', + type: 'address', + }, + { + name: 'signature', + type: 'bytes', + }, + ], + name: 'isValidSignature', + outputs: [ + { + name: 'isValid', + type: 'bool', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'orders', + type: 'tuple[]', + 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: 'makerAssetFillAmount', + type: 'uint256', + }, + { + name: 'signatures', + type: 'bytes[]', + }, + ], + name: 'marketBuyOrdersNoThrow', + outputs: [ + { + name: 'totalFillResults', + type: 'tuple', + components: [ + { + name: 'makerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'takerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'makerFeePaid', + type: 'uint256', + }, + { + name: 'takerFeePaid', + type: 'uint256', + }, + ], + }, + ], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'order', + type: 'tuple', + 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: 'takerAssetFillAmount', + type: 'uint256', + }, + { + name: 'signature', + type: 'bytes', + }, + ], + name: 'fillOrder', + outputs: [ + { + name: 'fillResults', + type: 'tuple', + components: [ + { + name: 'makerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'takerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'makerFeePaid', + type: 'uint256', + }, + { + name: 'takerFeePaid', + type: 'uint256', + }, + ], + }, + ], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'salt', + type: 'uint256', + }, + { + name: 'signerAddress', + type: 'address', + }, + { + name: 'data', + type: 'bytes', + }, + { + name: 'signature', + type: 'bytes', + }, + ], + name: 'executeTransaction', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'assetProxy', + type: 'address', + }, + ], + name: 'registerAssetProxy', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'order', + type: 'tuple', + 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: 'getOrderInfo', + outputs: [ + { + name: 'orderInfo', + type: 'tuple', + components: [ + { + name: 'orderStatus', + type: 'uint8', + }, + { + name: 'orderHash', + type: 'bytes32', + }, + { + name: 'orderTakerAssetFilledAmount', + type: 'uint256', + }, + ], + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'order', + type: 'tuple', + 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: 'cancelOrder', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'index_0', + type: 'address', + }, + { + name: 'index_1', + type: 'address', + }, + ], + name: 'orderEpoch', + outputs: [ + { + name: '', + type: 'uint256', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'ZRX_ASSET_DATA', + outputs: [ + { + name: '', + type: 'bytes', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'orders', + type: 'tuple[]', + 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: 'takerAssetFillAmount', + type: 'uint256', + }, + { + name: 'signatures', + type: 'bytes[]', + }, + ], + name: 'marketSellOrdersNoThrow', + outputs: [ + { + name: 'totalFillResults', + type: 'tuple', + components: [ + { + name: 'makerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'takerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'makerFeePaid', + type: 'uint256', + }, + { + name: 'takerFeePaid', + type: 'uint256', + }, + ], + }, + ], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'EIP712_DOMAIN_HASH', + outputs: [ + { + name: '', + type: 'bytes32', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'orders', + type: 'tuple[]', + 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: 'makerAssetFillAmount', + type: 'uint256', + }, + { + name: 'signatures', + type: 'bytes[]', + }, + ], + name: 'marketBuyOrders', + outputs: [ + { + name: 'totalFillResults', + type: 'tuple', + components: [ + { + name: 'makerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'takerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'makerFeePaid', + type: 'uint256', + }, + { + name: 'takerFeePaid', + type: 'uint256', + }, + ], + }, + ], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'currentContextAddress', + outputs: [ + { + name: '', + type: 'address', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'newOwner', + type: 'address', + }, + ], + name: 'transferOwnership', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'VERSION', + outputs: [ + { + name: '', + type: 'string', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + name: '_zrxAssetData', + type: 'bytes', + }, + ], + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'constructor', + }, + { + anonymous: false, + inputs: [ + { + name: 'signerAddress', + type: 'address', + indexed: true, + }, + { + name: 'validatorAddress', + type: 'address', + indexed: true, + }, + { + name: 'approved', + type: 'bool', + indexed: false, + }, + ], + name: 'SignatureValidatorApproval', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: 'makerAddress', + type: 'address', + indexed: true, + }, + { + name: 'feeRecipientAddress', + type: 'address', + indexed: true, + }, + { + name: 'takerAddress', + type: 'address', + indexed: false, + }, + { + name: 'senderAddress', + type: 'address', + indexed: false, + }, + { + name: 'makerAssetFilledAmount', + type: 'uint256', + indexed: false, + }, + { + name: 'takerAssetFilledAmount', + type: 'uint256', + indexed: false, + }, + { + name: 'makerFeePaid', + type: 'uint256', + indexed: false, + }, + { + name: 'takerFeePaid', + type: 'uint256', + indexed: false, + }, + { + name: 'orderHash', + type: 'bytes32', + indexed: true, + }, + { + name: 'makerAssetData', + type: 'bytes', + indexed: false, + }, + { + name: 'takerAssetData', + type: 'bytes', + indexed: false, + }, + ], + name: 'Fill', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: 'makerAddress', + type: 'address', + indexed: true, + }, + { + name: 'feeRecipientAddress', + type: 'address', + indexed: true, + }, + { + name: 'senderAddress', + type: 'address', + indexed: false, + }, + { + name: 'orderHash', + type: 'bytes32', + indexed: true, + }, + { + name: 'makerAssetData', + type: 'bytes', + indexed: false, + }, + { + name: 'takerAssetData', + type: 'bytes', + indexed: false, + }, + ], + name: 'Cancel', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: 'makerAddress', + type: 'address', + indexed: true, + }, + { + name: 'senderAddress', + type: 'address', + indexed: true, + }, + { + name: 'orderEpoch', + type: 'uint256', + indexed: false, + }, + ], + name: 'CancelUpTo', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: 'id', + type: 'bytes4', + indexed: false, + }, + { + name: 'assetProxy', + type: 'address', + indexed: false, + }, + ], + name: 'AssetProxyRegistered', + outputs: [], + type: 'event', + }, + ] as ContractAbi; + return abi; + } + /** + * Subscribe to an event type emitted by the Exchange contract. + * @param eventName The Exchange 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: ExchangeEvents, + indexFilterValues: IndexedFilterValues, + callback: EventCallback, + isVerbose: boolean = false, + blockPollingIntervalMs?: number, + ): string { + assert.doesBelongToStringEnum('eventName', eventName, ExchangeEvents); + assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); + assert.isFunction('callback', callback); + const subscriptionToken = this._subscriptionManager.subscribe( + this.address, + eventName, + indexFilterValues, + ExchangeContract.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 Exchange 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: ExchangeEvents, + blockRange: BlockRange, + indexFilterValues: IndexedFilterValues, + ): Promise>> { + assert.doesBelongToStringEnum('eventName', eventName, ExchangeEvents); + assert.doesConformToSchema('blockRange', blockRange, schemas.blockRangeSchema); + assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); + const logs = await this._subscriptionManager.getLogsAsync( + this.address, + eventName, + blockRange, + indexFilterValues, + ExchangeContract.ABI(), + ); + return logs; + } + constructor( + address: string, + supportedProvider: SupportedProvider, + txDefaults?: Partial, + logDecodeDependencies?: { [contractName: string]: ContractAbi }, + ) { + super('Exchange', ExchangeContract.ABI(), address, supportedProvider, txDefaults, logDecodeDependencies); + classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + this._subscriptionManager = new SubscriptionManager( + ExchangeContract.ABI(), + this._web3Wrapper, + ); + } +} + +// 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/contract-wrappers/src/generated-wrappers/forwarder.ts b/packages/contract-wrappers/src/generated-wrappers/forwarder.ts new file mode 100644 index 0000000000..d7d643b2ac --- /dev/null +++ b/packages/contract-wrappers/src/generated-wrappers/forwarder.ts @@ -0,0 +1,2022 @@ +// tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma +// tslint:disable:whitespace no-unbound-method no-trailing-whitespace +// tslint:disable:no-unused-variable +import { BaseContract, PromiseWithTransactionHash } from '@0x/base-contract'; +import { schemas } from '@0x/json-schemas'; +import { + BlockParam, + BlockParamLiteral, + CallData, + ContractAbi, + ContractArtifact, + DecodedLogArgs, + MethodAbi, + TransactionReceiptWithDecodedLogs, + TxData, + TxDataPayable, + SupportedProvider, +} from 'ethereum-types'; +import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; +import { 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:no-parameter-reassignment +// tslint:disable-next-line:class-name +export class ForwarderContract extends BaseContract { + /** + * Attempt to purchase makerAssetFillAmount of makerAsset by selling ETH provided with transaction. + * Any ZRX required to pay fees for primary orders will automatically be purchased by this contract. + * Any ETH not spent will be refunded to sender. + */ + public marketBuyOrdersWithEth = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param orders Array of order specifications used containing desired + * makerAsset and WETH as takerAsset. + * @param makerAssetFillAmount Desired amount of makerAsset to purchase. + * @param signatures Proofs that orders have been created by makers. + * @param feeOrders Array of order specifications containing ZRX as makerAsset + * and WETH as takerAsset. Used to purchase ZRX for primary order fees. + * @param feeSignatures Proofs that feeOrders have been created by makers. + * @param feePercentage Percentage of WETH sold that will payed as fee to + * forwarding contract feeRecipient. + * @param feeRecipient Address that will receive ETH when orders are filled. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + makerAssetFillAmount: BigNumber, + signatures: string[], + feeOrders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + feeSignatures: string[], + feePercentage: BigNumber, + feeRecipient: string, + txData?: Partial | undefined, + ): Promise { + assert.isArray('orders', orders); + assert.isBigNumber('makerAssetFillAmount', makerAssetFillAmount); + assert.isArray('signatures', signatures); + assert.isArray('feeOrders', feeOrders); + assert.isArray('feeSignatures', feeSignatures); + assert.isBigNumber('feePercentage', feePercentage); + assert.isString('feeRecipient', feeRecipient); + const self = (this as any) as ForwarderContract; + const encodedData = self._strictEncodeArguments( + 'marketBuyOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],bytes[],uint256,address)', + [ + orders, + makerAssetFillAmount, + signatures, + feeOrders, + feeSignatures, + feePercentage, + feeRecipient.toLowerCase(), + ], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.marketBuyOrdersWithEth.estimateGasAsync.bind( + self, + orders, + makerAssetFillAmount, + signatures, + feeOrders, + feeSignatures, + feePercentage, + feeRecipient.toLowerCase(), + ), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param orders Array of order specifications used containing desired + * makerAsset and WETH as takerAsset. + * @param makerAssetFillAmount Desired amount of makerAsset to purchase. + * @param signatures Proofs that orders have been created by makers. + * @param feeOrders Array of order specifications containing ZRX as makerAsset + * and WETH as takerAsset. Used to purchase ZRX for primary order fees. + * @param feeSignatures Proofs that feeOrders have been created by makers. + * @param feePercentage Percentage of WETH sold that will payed as fee to + * forwarding contract feeRecipient. + * @param feeRecipient Address that will receive ETH when orders are filled. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + makerAssetFillAmount: BigNumber, + signatures: string[], + feeOrders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + feeSignatures: string[], + feePercentage: BigNumber, + feeRecipient: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isArray('orders', orders); + assert.isBigNumber('makerAssetFillAmount', makerAssetFillAmount); + assert.isArray('signatures', signatures); + assert.isArray('feeOrders', feeOrders); + assert.isArray('feeSignatures', feeSignatures); + assert.isBigNumber('feePercentage', feePercentage); + assert.isString('feeRecipient', feeRecipient); + const self = (this as any) as ForwarderContract; + const txHashPromise = self.marketBuyOrdersWithEth.sendTransactionAsync( + orders, + makerAssetFillAmount, + signatures, + feeOrders, + feeSignatures, + feePercentage, + feeRecipient.toLowerCase(), + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param orders Array of order specifications used containing desired + * makerAsset and WETH as takerAsset. + * @param makerAssetFillAmount Desired amount of makerAsset to purchase. + * @param signatures Proofs that orders have been created by makers. + * @param feeOrders Array of order specifications containing ZRX as makerAsset + * and WETH as takerAsset. Used to purchase ZRX for primary order fees. + * @param feeSignatures Proofs that feeOrders have been created by makers. + * @param feePercentage Percentage of WETH sold that will payed as fee to + * forwarding contract feeRecipient. + * @param feeRecipient Address that will receive ETH when orders are filled. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + makerAssetFillAmount: BigNumber, + signatures: string[], + feeOrders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + feeSignatures: string[], + feePercentage: BigNumber, + feeRecipient: string, + txData?: Partial | undefined, + ): Promise { + assert.isArray('orders', orders); + assert.isBigNumber('makerAssetFillAmount', makerAssetFillAmount); + assert.isArray('signatures', signatures); + assert.isArray('feeOrders', feeOrders); + assert.isArray('feeSignatures', feeSignatures); + assert.isBigNumber('feePercentage', feePercentage); + assert.isString('feeRecipient', feeRecipient); + const self = (this as any) as ForwarderContract; + const encodedData = self._strictEncodeArguments( + 'marketBuyOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],bytes[],uint256,address)', + [ + orders, + makerAssetFillAmount, + signatures, + feeOrders, + feeSignatures, + feePercentage, + feeRecipient.toLowerCase(), + ], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param orders Array of order specifications used containing desired + * makerAsset and WETH as takerAsset. + * @param makerAssetFillAmount Desired amount of makerAsset to purchase. + * @param signatures Proofs that orders have been created by makers. + * @param feeOrders Array of order specifications containing ZRX as makerAsset + * and WETH as takerAsset. Used to purchase ZRX for primary order fees. + * @param feeSignatures Proofs that feeOrders have been created by makers. + * @param feePercentage Percentage of WETH sold that will payed as fee to + * forwarding contract feeRecipient. + * @param feeRecipient Address that will receive ETH when orders are filled. + * @returns Amounts filled and fees paid by maker and taker for both sets of orders. + */ + async callAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + makerAssetFillAmount: BigNumber, + signatures: string[], + feeOrders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + feeSignatures: string[], + feePercentage: BigNumber, + feeRecipient: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise< + [ + { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }, + { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } + ] + > { + assert.isArray('orders', orders); + assert.isBigNumber('makerAssetFillAmount', makerAssetFillAmount); + assert.isArray('signatures', signatures); + assert.isArray('feeOrders', feeOrders); + assert.isArray('feeSignatures', feeSignatures); + assert.isBigNumber('feePercentage', feePercentage); + assert.isString('feeRecipient', feeRecipient); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ForwarderContract; + const encodedData = self._strictEncodeArguments( + 'marketBuyOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],bytes[],uint256,address)', + [ + orders, + makerAssetFillAmount, + signatures, + feeOrders, + feeSignatures, + feePercentage, + feeRecipient.toLowerCase(), + ], + ); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'marketBuyOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],bytes[],uint256,address)', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue< + [ + { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }, + { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } + ] + >(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param orders Array of order specifications used containing desired + * makerAsset and WETH as takerAsset. + * @param makerAssetFillAmount Desired amount of makerAsset to purchase. + * @param signatures Proofs that orders have been created by makers. + * @param feeOrders Array of order specifications containing ZRX as makerAsset + * and WETH as takerAsset. Used to purchase ZRX for primary order fees. + * @param feeSignatures Proofs that feeOrders have been created by makers. + * @param feePercentage Percentage of WETH sold that will payed as fee to + * forwarding contract feeRecipient. + * @param feeRecipient Address that will receive ETH when orders are filled. + */ + getABIEncodedTransactionData( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + makerAssetFillAmount: BigNumber, + signatures: string[], + feeOrders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + feeSignatures: string[], + feePercentage: BigNumber, + feeRecipient: string, + ): string { + assert.isArray('orders', orders); + assert.isBigNumber('makerAssetFillAmount', makerAssetFillAmount); + assert.isArray('signatures', signatures); + assert.isArray('feeOrders', feeOrders); + assert.isArray('feeSignatures', feeSignatures); + assert.isBigNumber('feePercentage', feePercentage); + assert.isString('feeRecipient', feeRecipient); + const self = (this as any) as ForwarderContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'marketBuyOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],bytes[],uint256,address)', + [ + orders, + makerAssetFillAmount, + signatures, + feeOrders, + feeSignatures, + feePercentage, + feeRecipient.toLowerCase(), + ], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData( + callData: string, + ): [ + { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }, + { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } + ] { + const self = (this as any) as ForwarderContract; + const abiEncoder = self._lookupAbiEncoder( + 'marketBuyOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],bytes[],uint256,address)', + ); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode< + [ + { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }, + { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } + ] + >(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData( + returnData: string, + ): [ + { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }, + { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } + ] { + const self = (this as any) as ForwarderContract; + const abiEncoder = self._lookupAbiEncoder( + 'marketBuyOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],bytes[],uint256,address)', + ); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue< + [ + { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }, + { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } + ] + >(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Withdraws assets from this contract. The contract requires a ZRX balance in order to + * function optimally, and this function allows the ZRX to be withdrawn by owner. It may also be + * used to withdraw assets that were accidentally sent to this contract. + */ + public withdrawAsset = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param assetData Byte array encoded for the respective asset proxy. + * @param amount Amount of ERC20 token to withdraw. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + assetData: string, + amount: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('assetData', assetData); + assert.isBigNumber('amount', amount); + const self = (this as any) as ForwarderContract; + const encodedData = self._strictEncodeArguments('withdrawAsset(bytes,uint256)', [assetData, amount]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.withdrawAsset.estimateGasAsync.bind(self, assetData, amount), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param assetData Byte array encoded for the respective asset proxy. + * @param amount Amount of ERC20 token to withdraw. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + assetData: string, + amount: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('assetData', assetData); + assert.isBigNumber('amount', amount); + const self = (this as any) as ForwarderContract; + const txHashPromise = self.withdrawAsset.sendTransactionAsync(assetData, amount, txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param assetData Byte array encoded for the respective asset proxy. + * @param amount Amount of ERC20 token to withdraw. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + assetData: string, + amount: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('assetData', assetData); + assert.isBigNumber('amount', amount); + const self = (this as any) as ForwarderContract; + const encodedData = self._strictEncodeArguments('withdrawAsset(bytes,uint256)', [assetData, amount]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param assetData Byte array encoded for the respective asset proxy. + * @param amount Amount of ERC20 token to withdraw. + */ + async callAsync( + assetData: string, + amount: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('assetData', assetData); + assert.isBigNumber('amount', amount); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ForwarderContract; + const encodedData = self._strictEncodeArguments('withdrawAsset(bytes,uint256)', [assetData, amount]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('withdrawAsset(bytes,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param assetData Byte array encoded for the respective asset proxy. + * @param amount Amount of ERC20 token to withdraw. + */ + getABIEncodedTransactionData(assetData: string, amount: BigNumber): string { + assert.isString('assetData', assetData); + assert.isBigNumber('amount', amount); + const self = (this as any) as ForwarderContract; + const abiEncodedTransactionData = self._strictEncodeArguments('withdrawAsset(bytes,uint256)', [ + assetData, + amount, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as ForwarderContract; + const abiEncoder = self._lookupAbiEncoder('withdrawAsset(bytes,uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as ForwarderContract; + const abiEncoder = self._lookupAbiEncoder('withdrawAsset(bytes,uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public owner = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ForwarderContract; + const encodedData = self._strictEncodeArguments('owner()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('owner()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as ForwarderContract; + const abiEncodedTransactionData = self._strictEncodeArguments('owner()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as ForwarderContract; + const abiEncoder = self._lookupAbiEncoder('owner()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as ForwarderContract; + const abiEncoder = self._lookupAbiEncoder('owner()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Purchases as much of orders' makerAssets as possible by selling up to 95% of transaction's ETH value. + * Any ZRX required to pay fees for primary orders will automatically be purchased by this contract. + * 5% of ETH value is reserved for paying fees to order feeRecipients (in ZRX) and forwarding contract feeRecipient (in ETH). + * Any ETH not spent will be refunded to sender. + */ + public marketSellOrdersWithEth = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param orders Array of order specifications used containing desired + * makerAsset and WETH as takerAsset. + * @param signatures Proofs that orders have been created by makers. + * @param feeOrders Array of order specifications containing ZRX as makerAsset + * and WETH as takerAsset. Used to purchase ZRX for primary order fees. + * @param feeSignatures Proofs that feeOrders have been created by makers. + * @param feePercentage Percentage of WETH sold that will payed as fee to + * forwarding contract feeRecipient. + * @param feeRecipient Address that will receive ETH when orders are filled. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + signatures: string[], + feeOrders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + feeSignatures: string[], + feePercentage: BigNumber, + feeRecipient: string, + txData?: Partial | undefined, + ): Promise { + assert.isArray('orders', orders); + assert.isArray('signatures', signatures); + assert.isArray('feeOrders', feeOrders); + assert.isArray('feeSignatures', feeSignatures); + assert.isBigNumber('feePercentage', feePercentage); + assert.isString('feeRecipient', feeRecipient); + const self = (this as any) as ForwarderContract; + const encodedData = self._strictEncodeArguments( + 'marketSellOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],bytes[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],bytes[],uint256,address)', + [orders, signatures, feeOrders, feeSignatures, feePercentage, feeRecipient.toLowerCase()], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.marketSellOrdersWithEth.estimateGasAsync.bind( + self, + orders, + signatures, + feeOrders, + feeSignatures, + feePercentage, + feeRecipient.toLowerCase(), + ), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param orders Array of order specifications used containing desired + * makerAsset and WETH as takerAsset. + * @param signatures Proofs that orders have been created by makers. + * @param feeOrders Array of order specifications containing ZRX as makerAsset + * and WETH as takerAsset. Used to purchase ZRX for primary order fees. + * @param feeSignatures Proofs that feeOrders have been created by makers. + * @param feePercentage Percentage of WETH sold that will payed as fee to + * forwarding contract feeRecipient. + * @param feeRecipient Address that will receive ETH when orders are filled. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + signatures: string[], + feeOrders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + feeSignatures: string[], + feePercentage: BigNumber, + feeRecipient: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isArray('orders', orders); + assert.isArray('signatures', signatures); + assert.isArray('feeOrders', feeOrders); + assert.isArray('feeSignatures', feeSignatures); + assert.isBigNumber('feePercentage', feePercentage); + assert.isString('feeRecipient', feeRecipient); + const self = (this as any) as ForwarderContract; + const txHashPromise = self.marketSellOrdersWithEth.sendTransactionAsync( + orders, + signatures, + feeOrders, + feeSignatures, + feePercentage, + feeRecipient.toLowerCase(), + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param orders Array of order specifications used containing desired + * makerAsset and WETH as takerAsset. + * @param signatures Proofs that orders have been created by makers. + * @param feeOrders Array of order specifications containing ZRX as makerAsset + * and WETH as takerAsset. Used to purchase ZRX for primary order fees. + * @param feeSignatures Proofs that feeOrders have been created by makers. + * @param feePercentage Percentage of WETH sold that will payed as fee to + * forwarding contract feeRecipient. + * @param feeRecipient Address that will receive ETH when orders are filled. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + signatures: string[], + feeOrders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + feeSignatures: string[], + feePercentage: BigNumber, + feeRecipient: string, + txData?: Partial | undefined, + ): Promise { + assert.isArray('orders', orders); + assert.isArray('signatures', signatures); + assert.isArray('feeOrders', feeOrders); + assert.isArray('feeSignatures', feeSignatures); + assert.isBigNumber('feePercentage', feePercentage); + assert.isString('feeRecipient', feeRecipient); + const self = (this as any) as ForwarderContract; + const encodedData = self._strictEncodeArguments( + 'marketSellOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],bytes[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],bytes[],uint256,address)', + [orders, signatures, feeOrders, feeSignatures, feePercentage, feeRecipient.toLowerCase()], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param orders Array of order specifications used containing desired + * makerAsset and WETH as takerAsset. + * @param signatures Proofs that orders have been created by makers. + * @param feeOrders Array of order specifications containing ZRX as makerAsset + * and WETH as takerAsset. Used to purchase ZRX for primary order fees. + * @param feeSignatures Proofs that feeOrders have been created by makers. + * @param feePercentage Percentage of WETH sold that will payed as fee to + * forwarding contract feeRecipient. + * @param feeRecipient Address that will receive ETH when orders are filled. + * @returns Amounts filled and fees paid by maker and taker for both sets of orders. + */ + async callAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + signatures: string[], + feeOrders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + feeSignatures: string[], + feePercentage: BigNumber, + feeRecipient: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise< + [ + { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }, + { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } + ] + > { + assert.isArray('orders', orders); + assert.isArray('signatures', signatures); + assert.isArray('feeOrders', feeOrders); + assert.isArray('feeSignatures', feeSignatures); + assert.isBigNumber('feePercentage', feePercentage); + assert.isString('feeRecipient', feeRecipient); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ForwarderContract; + const encodedData = self._strictEncodeArguments( + 'marketSellOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],bytes[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],bytes[],uint256,address)', + [orders, signatures, feeOrders, feeSignatures, feePercentage, feeRecipient.toLowerCase()], + ); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'marketSellOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],bytes[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],bytes[],uint256,address)', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue< + [ + { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }, + { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } + ] + >(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param orders Array of order specifications used containing desired + * makerAsset and WETH as takerAsset. + * @param signatures Proofs that orders have been created by makers. + * @param feeOrders Array of order specifications containing ZRX as makerAsset + * and WETH as takerAsset. Used to purchase ZRX for primary order fees. + * @param feeSignatures Proofs that feeOrders have been created by makers. + * @param feePercentage Percentage of WETH sold that will payed as fee to + * forwarding contract feeRecipient. + * @param feeRecipient Address that will receive ETH when orders are filled. + */ + getABIEncodedTransactionData( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + signatures: string[], + feeOrders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + feeSignatures: string[], + feePercentage: BigNumber, + feeRecipient: string, + ): string { + assert.isArray('orders', orders); + assert.isArray('signatures', signatures); + assert.isArray('feeOrders', feeOrders); + assert.isArray('feeSignatures', feeSignatures); + assert.isBigNumber('feePercentage', feePercentage); + assert.isString('feeRecipient', feeRecipient); + const self = (this as any) as ForwarderContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'marketSellOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],bytes[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],bytes[],uint256,address)', + [orders, signatures, feeOrders, feeSignatures, feePercentage, feeRecipient.toLowerCase()], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData( + callData: string, + ): [ + { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }, + { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } + ] { + const self = (this as any) as ForwarderContract; + const abiEncoder = self._lookupAbiEncoder( + 'marketSellOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],bytes[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],bytes[],uint256,address)', + ); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode< + [ + { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }, + { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } + ] + >(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData( + returnData: string, + ): [ + { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }, + { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } + ] { + const self = (this as any) as ForwarderContract; + const abiEncoder = self._lookupAbiEncoder( + 'marketSellOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],bytes[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],bytes[],uint256,address)', + ); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue< + [ + { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + }, + { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + } + ] + >(returnData); + return abiDecodedReturnData; + }, + }; + public transferOwnership = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(newOwner: string, txData?: Partial | undefined): Promise { + assert.isString('newOwner', newOwner); + const self = (this as any) as ForwarderContract; + const encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.transferOwnership.estimateGasAsync.bind(self, newOwner.toLowerCase()), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + newOwner: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('newOwner', newOwner); + const self = (this as any) as ForwarderContract; + const txHashPromise = self.transferOwnership.sendTransactionAsync(newOwner.toLowerCase(), txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(newOwner: string, txData?: Partial | undefined): Promise { + assert.isString('newOwner', newOwner); + const self = (this as any) as ForwarderContract; + const encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(newOwner: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.isString('newOwner', newOwner); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ForwarderContract; + const encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(newOwner: string): string { + assert.isString('newOwner', newOwner); + const self = (this as any) as ForwarderContract; + const abiEncodedTransactionData = self._strictEncodeArguments('transferOwnership(address)', [ + newOwner.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as ForwarderContract; + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as ForwarderContract; + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public static async deployFrom0xArtifactAsync( + artifact: ContractArtifact | SimpleContractArtifact, + supportedProvider: SupportedProvider, + txDefaults: Partial, + logDecodeDependencies: { [contractName: string]: ContractArtifact | SimpleContractArtifact }, + _exchange: string, + _zrxAssetData: string, + _wethAssetData: string, + ): 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 ForwarderContract.deployAsync( + bytecode, + abi, + provider, + txDefaults, + logDecodeDependenciesAbiOnly, + _exchange, + _zrxAssetData, + _wethAssetData, + ); + } + public static async deployAsync( + bytecode: string, + abi: ContractAbi, + supportedProvider: SupportedProvider, + txDefaults: Partial, + logDecodeDependencies: { [contractName: string]: ContractAbi }, + _exchange: string, + _zrxAssetData: string, + _wethAssetData: string, + ): 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); + [_exchange, _zrxAssetData, _wethAssetData] = BaseContract._formatABIDataItemList( + constructorAbi.inputs, + [_exchange, _zrxAssetData, _wethAssetData], + BaseContract._bigNumberToString, + ); + const iface = new ethers.utils.Interface(abi); + const deployInfo = iface.deployFunction; + const txData = deployInfo.encode(bytecode, [_exchange, _zrxAssetData, _wethAssetData]); + const web3Wrapper = new Web3Wrapper(provider); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { 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(`Forwarder successfully deployed at ${txReceipt.contractAddress}`); + const contractInstance = new ForwarderContract( + txReceipt.contractAddress as string, + provider, + txDefaults, + logDecodeDependencies, + ); + contractInstance.constructorArgs = [_exchange, _zrxAssetData, _wethAssetData]; + return contractInstance; + } + + /** + * @returns The contract ABI + */ + public static ABI(): ContractAbi { + const abi = [ + { + constant: false, + inputs: [ + { + name: 'orders', + type: 'tuple[]', + 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: 'makerAssetFillAmount', + type: 'uint256', + }, + { + name: 'signatures', + type: 'bytes[]', + }, + { + name: 'feeOrders', + type: 'tuple[]', + 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: 'feeSignatures', + type: 'bytes[]', + }, + { + name: 'feePercentage', + type: 'uint256', + }, + { + name: 'feeRecipient', + type: 'address', + }, + ], + name: 'marketBuyOrdersWithEth', + outputs: [ + { + name: 'orderFillResults', + type: 'tuple', + components: [ + { + name: 'makerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'takerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'makerFeePaid', + type: 'uint256', + }, + { + name: 'takerFeePaid', + type: 'uint256', + }, + ], + }, + { + name: 'feeOrderFillResults', + type: 'tuple', + components: [ + { + name: 'makerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'takerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'makerFeePaid', + type: 'uint256', + }, + { + name: 'takerFeePaid', + type: 'uint256', + }, + ], + }, + ], + payable: true, + stateMutability: 'payable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'assetData', + type: 'bytes', + }, + { + name: 'amount', + type: 'uint256', + }, + ], + name: 'withdrawAsset', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'owner', + outputs: [ + { + name: '', + type: 'address', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'orders', + type: 'tuple[]', + 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: 'signatures', + type: 'bytes[]', + }, + { + name: 'feeOrders', + type: 'tuple[]', + 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: 'feeSignatures', + type: 'bytes[]', + }, + { + name: 'feePercentage', + type: 'uint256', + }, + { + name: 'feeRecipient', + type: 'address', + }, + ], + name: 'marketSellOrdersWithEth', + outputs: [ + { + name: 'orderFillResults', + type: 'tuple', + components: [ + { + name: 'makerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'takerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'makerFeePaid', + type: 'uint256', + }, + { + name: 'takerFeePaid', + type: 'uint256', + }, + ], + }, + { + name: 'feeOrderFillResults', + type: 'tuple', + components: [ + { + name: 'makerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'takerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'makerFeePaid', + type: 'uint256', + }, + { + name: 'takerFeePaid', + type: 'uint256', + }, + ], + }, + ], + payable: true, + stateMutability: 'payable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'newOwner', + type: 'address', + }, + ], + name: 'transferOwnership', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + inputs: [ + { + name: '_exchange', + type: 'address', + }, + { + name: '_zrxAssetData', + type: 'bytes', + }, + { + name: '_wethAssetData', + type: 'bytes', + }, + ], + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'constructor', + }, + { + inputs: [], + outputs: [], + payable: true, + stateMutability: 'payable', + type: 'fallback', + }, + ] as ContractAbi; + return abi; + } + constructor( + address: string, + supportedProvider: SupportedProvider, + txDefaults?: Partial, + logDecodeDependencies?: { [contractName: string]: ContractAbi }, + ) { + super('Forwarder', ForwarderContract.ABI(), address, supportedProvider, txDefaults, logDecodeDependencies); + classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + } +} + +// 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/contract-wrappers/src/generated-wrappers/i_asset_proxy.ts b/packages/contract-wrappers/src/generated-wrappers/i_asset_proxy.ts new file mode 100644 index 0000000000..00b079a261 --- /dev/null +++ b/packages/contract-wrappers/src/generated-wrappers/i_asset_proxy.ts @@ -0,0 +1,1225 @@ +// tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma +// tslint:disable:whitespace no-unbound-method no-trailing-whitespace +// tslint:disable:no-unused-variable +import { BaseContract, PromiseWithTransactionHash } from '@0x/base-contract'; +import { schemas } from '@0x/json-schemas'; +import { + BlockParam, + BlockParamLiteral, + CallData, + ContractAbi, + ContractArtifact, + DecodedLogArgs, + MethodAbi, + TransactionReceiptWithDecodedLogs, + TxData, + TxDataPayable, + SupportedProvider, +} from 'ethereum-types'; +import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; +import { 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:no-parameter-reassignment +// tslint:disable-next-line:class-name +export class IAssetProxyContract extends BaseContract { + /** + * Authorizes an address. + */ + public addAuthorizedAddress = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param target Address to authorize. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(target: string, txData?: Partial | undefined): Promise { + assert.isString('target', target); + const self = (this as any) as IAssetProxyContract; + const encodedData = self._strictEncodeArguments('addAuthorizedAddress(address)', [target.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.addAuthorizedAddress.estimateGasAsync.bind(self, target.toLowerCase()), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param target Address to authorize. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + target: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('target', target); + const self = (this as any) as IAssetProxyContract; + const txHashPromise = self.addAuthorizedAddress.sendTransactionAsync(target.toLowerCase(), txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param target Address to authorize. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(target: string, txData?: Partial | undefined): Promise { + assert.isString('target', target); + const self = (this as any) as IAssetProxyContract; + const encodedData = self._strictEncodeArguments('addAuthorizedAddress(address)', [target.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param target Address to authorize. + */ + async callAsync(target: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.isString('target', target); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as IAssetProxyContract; + const encodedData = self._strictEncodeArguments('addAuthorizedAddress(address)', [target.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('addAuthorizedAddress(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param target Address to authorize. + */ + getABIEncodedTransactionData(target: string): string { + assert.isString('target', target); + const self = (this as any) as IAssetProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('addAuthorizedAddress(address)', [ + target.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as IAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('addAuthorizedAddress(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as IAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('addAuthorizedAddress(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Removes authorizion of an address. + */ + public removeAuthorizedAddress = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param target Address to remove authorization from. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(target: string, txData?: Partial | undefined): Promise { + assert.isString('target', target); + const self = (this as any) as IAssetProxyContract; + const encodedData = self._strictEncodeArguments('removeAuthorizedAddress(address)', [target.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.removeAuthorizedAddress.estimateGasAsync.bind(self, target.toLowerCase()), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param target Address to remove authorization from. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + target: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('target', target); + const self = (this as any) as IAssetProxyContract; + const txHashPromise = self.removeAuthorizedAddress.sendTransactionAsync(target.toLowerCase(), txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param target Address to remove authorization from. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(target: string, txData?: Partial | undefined): Promise { + assert.isString('target', target); + const self = (this as any) as IAssetProxyContract; + const encodedData = self._strictEncodeArguments('removeAuthorizedAddress(address)', [target.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param target Address to remove authorization from. + */ + async callAsync(target: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.isString('target', target); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as IAssetProxyContract; + const encodedData = self._strictEncodeArguments('removeAuthorizedAddress(address)', [target.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddress(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param target Address to remove authorization from. + */ + getABIEncodedTransactionData(target: string): string { + assert.isString('target', target); + const self = (this as any) as IAssetProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('removeAuthorizedAddress(address)', [ + target.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as IAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddress(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as IAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddress(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Removes authorizion of an address. + */ + public removeAuthorizedAddressAtIndex = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param target Address to remove authorization from. + * @param index Index of target in authorities array. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + target: string, + index: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('target', target); + assert.isBigNumber('index', index); + const self = (this as any) as IAssetProxyContract; + const encodedData = self._strictEncodeArguments('removeAuthorizedAddressAtIndex(address,uint256)', [ + target.toLowerCase(), + index, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.removeAuthorizedAddressAtIndex.estimateGasAsync.bind(self, target.toLowerCase(), index), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param target Address to remove authorization from. + * @param index Index of target in authorities array. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + target: string, + index: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('target', target); + assert.isBigNumber('index', index); + const self = (this as any) as IAssetProxyContract; + const txHashPromise = self.removeAuthorizedAddressAtIndex.sendTransactionAsync( + target.toLowerCase(), + index, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param target Address to remove authorization from. + * @param index Index of target in authorities array. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + target: string, + index: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('target', target); + assert.isBigNumber('index', index); + const self = (this as any) as IAssetProxyContract; + const encodedData = self._strictEncodeArguments('removeAuthorizedAddressAtIndex(address,uint256)', [ + target.toLowerCase(), + index, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param target Address to remove authorization from. + * @param index Index of target in authorities array. + */ + async callAsync( + target: string, + index: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('target', target); + assert.isBigNumber('index', index); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as IAssetProxyContract; + const encodedData = self._strictEncodeArguments('removeAuthorizedAddressAtIndex(address,uint256)', [ + target.toLowerCase(), + index, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddressAtIndex(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param target Address to remove authorization from. + * @param index Index of target in authorities array. + */ + getABIEncodedTransactionData(target: string, index: BigNumber): string { + assert.isString('target', target); + assert.isBigNumber('index', index); + const self = (this as any) as IAssetProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'removeAuthorizedAddressAtIndex(address,uint256)', + [target.toLowerCase(), index], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as IAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddressAtIndex(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as IAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddressAtIndex(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Transfers assets. Either succeeds or throws. + */ + public transferFrom = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param assetData Byte array encoded for the respective asset proxy. + * @param from Address to transfer asset from. + * @param to Address to transfer asset to. + * @param amount Amount of asset to transfer. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + assetData: string, + from: string, + to: string, + amount: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('assetData', assetData); + assert.isString('from', from); + assert.isString('to', to); + assert.isBigNumber('amount', amount); + const self = (this as any) as IAssetProxyContract; + const encodedData = self._strictEncodeArguments('transferFrom(bytes,address,address,uint256)', [ + assetData, + from.toLowerCase(), + to.toLowerCase(), + amount, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.transferFrom.estimateGasAsync.bind(self, assetData, from.toLowerCase(), to.toLowerCase(), amount), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param assetData Byte array encoded for the respective asset proxy. + * @param from Address to transfer asset from. + * @param to Address to transfer asset to. + * @param amount Amount of asset to transfer. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + assetData: string, + from: string, + to: string, + amount: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('assetData', assetData); + assert.isString('from', from); + assert.isString('to', to); + assert.isBigNumber('amount', amount); + const self = (this as any) as IAssetProxyContract; + const txHashPromise = self.transferFrom.sendTransactionAsync( + assetData, + from.toLowerCase(), + to.toLowerCase(), + amount, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param assetData Byte array encoded for the respective asset proxy. + * @param from Address to transfer asset from. + * @param to Address to transfer asset to. + * @param amount Amount of asset to transfer. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + assetData: string, + from: string, + to: string, + amount: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('assetData', assetData); + assert.isString('from', from); + assert.isString('to', to); + assert.isBigNumber('amount', amount); + const self = (this as any) as IAssetProxyContract; + const encodedData = self._strictEncodeArguments('transferFrom(bytes,address,address,uint256)', [ + assetData, + from.toLowerCase(), + to.toLowerCase(), + amount, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param assetData Byte array encoded for the respective asset proxy. + * @param from Address to transfer asset from. + * @param to Address to transfer asset to. + * @param amount Amount of asset to transfer. + */ + async callAsync( + assetData: string, + from: string, + to: string, + amount: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('assetData', assetData); + assert.isString('from', from); + assert.isString('to', to); + assert.isBigNumber('amount', amount); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as IAssetProxyContract; + const encodedData = self._strictEncodeArguments('transferFrom(bytes,address,address,uint256)', [ + assetData, + from.toLowerCase(), + to.toLowerCase(), + amount, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transferFrom(bytes,address,address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param assetData Byte array encoded for the respective asset proxy. + * @param from Address to transfer asset from. + * @param to Address to transfer asset to. + * @param amount Amount of asset to transfer. + */ + getABIEncodedTransactionData(assetData: string, from: string, to: string, amount: BigNumber): string { + assert.isString('assetData', assetData); + assert.isString('from', from); + assert.isString('to', to); + assert.isBigNumber('amount', amount); + const self = (this as any) as IAssetProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'transferFrom(bytes,address,address,uint256)', + [assetData, from.toLowerCase(), to.toLowerCase(), amount], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as IAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('transferFrom(bytes,address,address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as IAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('transferFrom(bytes,address,address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Gets the proxy id associated with the proxy address. + */ + public getProxyId = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @returns Proxy id. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as IAssetProxyContract; + const encodedData = self._strictEncodeArguments('getProxyId()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getProxyId()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as IAssetProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('getProxyId()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as IAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('getProxyId()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as IAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('getProxyId()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Gets all authorized addresses. + */ + public getAuthorizedAddresses = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @returns Array of authorized addresses. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as IAssetProxyContract; + const encodedData = self._strictEncodeArguments('getAuthorizedAddresses()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getAuthorizedAddresses()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as IAssetProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('getAuthorizedAddresses()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string[] { + const self = (this as any) as IAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('getAuthorizedAddresses()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string[] { + const self = (this as any) as IAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('getAuthorizedAddresses()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public transferOwnership = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(newOwner: string, txData?: Partial | undefined): Promise { + assert.isString('newOwner', newOwner); + const self = (this as any) as IAssetProxyContract; + const encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.transferOwnership.estimateGasAsync.bind(self, newOwner.toLowerCase()), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + newOwner: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('newOwner', newOwner); + const self = (this as any) as IAssetProxyContract; + const txHashPromise = self.transferOwnership.sendTransactionAsync(newOwner.toLowerCase(), txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(newOwner: string, txData?: Partial | undefined): Promise { + assert.isString('newOwner', newOwner); + const self = (this as any) as IAssetProxyContract; + const encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(newOwner: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.isString('newOwner', newOwner); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as IAssetProxyContract; + const encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(newOwner: string): string { + assert.isString('newOwner', newOwner); + const self = (this as any) as IAssetProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('transferOwnership(address)', [ + newOwner.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as IAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as IAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + 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 IAssetProxyContract.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._applyDefaultsToTxDataAsync( + { 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(`IAssetProxy successfully deployed at ${txReceipt.contractAddress}`); + const contractInstance = new IAssetProxyContract( + txReceipt.contractAddress as string, + provider, + txDefaults, + logDecodeDependencies, + ); + contractInstance.constructorArgs = []; + return contractInstance; + } + + /** + * @returns The contract ABI + */ + public static ABI(): ContractAbi { + const abi = [ + { + constant: false, + inputs: [ + { + name: 'target', + type: 'address', + }, + ], + name: 'addAuthorizedAddress', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'target', + type: 'address', + }, + ], + name: 'removeAuthorizedAddress', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'target', + type: 'address', + }, + { + name: 'index', + type: 'uint256', + }, + ], + name: 'removeAuthorizedAddressAtIndex', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'assetData', + type: 'bytes', + }, + { + name: 'from', + type: 'address', + }, + { + name: 'to', + type: 'address', + }, + { + name: 'amount', + type: 'uint256', + }, + ], + name: 'transferFrom', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'getProxyId', + outputs: [ + { + name: '', + type: 'bytes4', + }, + ], + payable: false, + stateMutability: 'pure', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'getAuthorizedAddresses', + outputs: [ + { + name: '', + type: 'address[]', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'newOwner', + type: 'address', + }, + ], + name: 'transferOwnership', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + ] as ContractAbi; + return abi; + } + constructor( + address: string, + supportedProvider: SupportedProvider, + txDefaults?: Partial, + logDecodeDependencies?: { [contractName: string]: ContractAbi }, + ) { + super('IAssetProxy', IAssetProxyContract.ABI(), address, supportedProvider, txDefaults, logDecodeDependencies); + classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + } +} + +// 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/contract-wrappers/src/generated-wrappers/i_validator.ts b/packages/contract-wrappers/src/generated-wrappers/i_validator.ts new file mode 100644 index 0000000000..86dae30e10 --- /dev/null +++ b/packages/contract-wrappers/src/generated-wrappers/i_validator.ts @@ -0,0 +1,234 @@ +// tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma +// tslint:disable:whitespace no-unbound-method no-trailing-whitespace +// tslint:disable:no-unused-variable +import { BaseContract, PromiseWithTransactionHash } from '@0x/base-contract'; +import { schemas } from '@0x/json-schemas'; +import { + BlockParam, + BlockParamLiteral, + CallData, + ContractAbi, + ContractArtifact, + DecodedLogArgs, + MethodAbi, + TransactionReceiptWithDecodedLogs, + TxData, + TxDataPayable, + SupportedProvider, +} from 'ethereum-types'; +import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; +import { 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:no-parameter-reassignment +// tslint:disable-next-line:class-name +export class IValidatorContract extends BaseContract { + /** + * Verifies that a signature is valid. + */ + public isValidSignature = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param hash Message hash that is signed. + * @param signerAddress Address that should have signed the given hash. + * @param signature Proof of signing. + * @returns Validity of order signature. + */ + async callAsync( + hash: string, + signerAddress: string, + signature: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('hash', hash); + assert.isString('signerAddress', signerAddress); + assert.isString('signature', signature); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as IValidatorContract; + const encodedData = self._strictEncodeArguments('isValidSignature(bytes32,address,bytes)', [ + hash, + signerAddress.toLowerCase(), + signature, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('isValidSignature(bytes32,address,bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param hash Message hash that is signed. + * @param signerAddress Address that should have signed the given hash. + * @param signature Proof of signing. + */ + getABIEncodedTransactionData(hash: string, signerAddress: string, signature: string): string { + assert.isString('hash', hash); + assert.isString('signerAddress', signerAddress); + assert.isString('signature', signature); + const self = (this as any) as IValidatorContract; + const abiEncodedTransactionData = self._strictEncodeArguments('isValidSignature(bytes32,address,bytes)', [ + hash, + signerAddress.toLowerCase(), + signature, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): boolean { + const self = (this as any) as IValidatorContract; + const abiEncoder = self._lookupAbiEncoder('isValidSignature(bytes32,address,bytes)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): boolean { + const self = (this as any) as IValidatorContract; + const abiEncoder = self._lookupAbiEncoder('isValidSignature(bytes32,address,bytes)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + 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 IValidatorContract.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._applyDefaultsToTxDataAsync( + { 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(`IValidator successfully deployed at ${txReceipt.contractAddress}`); + const contractInstance = new IValidatorContract( + 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: 'hash', + type: 'bytes32', + }, + { + name: 'signerAddress', + type: 'address', + }, + { + name: 'signature', + type: 'bytes', + }, + ], + name: 'isValidSignature', + outputs: [ + { + name: 'isValid', + type: 'bool', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + ] as ContractAbi; + return abi; + } + constructor( + address: string, + supportedProvider: SupportedProvider, + txDefaults?: Partial, + logDecodeDependencies?: { [contractName: string]: ContractAbi }, + ) { + super('IValidator', IValidatorContract.ABI(), address, supportedProvider, txDefaults, logDecodeDependencies); + classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + } +} + +// 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/contract-wrappers/src/generated-wrappers/i_wallet.ts b/packages/contract-wrappers/src/generated-wrappers/i_wallet.ts new file mode 100644 index 0000000000..042fc5ce5b --- /dev/null +++ b/packages/contract-wrappers/src/generated-wrappers/i_wallet.ts @@ -0,0 +1,220 @@ +// tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma +// tslint:disable:whitespace no-unbound-method no-trailing-whitespace +// tslint:disable:no-unused-variable +import { BaseContract, PromiseWithTransactionHash } from '@0x/base-contract'; +import { schemas } from '@0x/json-schemas'; +import { + BlockParam, + BlockParamLiteral, + CallData, + ContractAbi, + ContractArtifact, + DecodedLogArgs, + MethodAbi, + TransactionReceiptWithDecodedLogs, + TxData, + TxDataPayable, + SupportedProvider, +} from 'ethereum-types'; +import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; +import { 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:no-parameter-reassignment +// tslint:disable-next-line:class-name +export class IWalletContract extends BaseContract { + /** + * Verifies that a signature is valid. + */ + public isValidSignature = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param hash Message hash that is signed. + * @param signature Proof of signing. + * @returns Validity of order signature. + */ + async callAsync( + hash: string, + signature: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('hash', hash); + assert.isString('signature', signature); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as IWalletContract; + const encodedData = self._strictEncodeArguments('isValidSignature(bytes32,bytes)', [hash, signature]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('isValidSignature(bytes32,bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param hash Message hash that is signed. + * @param signature Proof of signing. + */ + getABIEncodedTransactionData(hash: string, signature: string): string { + assert.isString('hash', hash); + assert.isString('signature', signature); + const self = (this as any) as IWalletContract; + const abiEncodedTransactionData = self._strictEncodeArguments('isValidSignature(bytes32,bytes)', [ + hash, + signature, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): boolean { + const self = (this as any) as IWalletContract; + const abiEncoder = self._lookupAbiEncoder('isValidSignature(bytes32,bytes)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): boolean { + const self = (this as any) as IWalletContract; + const abiEncoder = self._lookupAbiEncoder('isValidSignature(bytes32,bytes)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + 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 IWalletContract.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._applyDefaultsToTxDataAsync( + { 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(`IWallet successfully deployed at ${txReceipt.contractAddress}`); + const contractInstance = new IWalletContract( + 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: 'hash', + type: 'bytes32', + }, + { + name: 'signature', + type: 'bytes', + }, + ], + name: 'isValidSignature', + outputs: [ + { + name: 'isValid', + type: 'bool', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + ] as ContractAbi; + return abi; + } + constructor( + address: string, + supportedProvider: SupportedProvider, + txDefaults?: Partial, + logDecodeDependencies?: { [contractName: string]: ContractAbi }, + ) { + super('IWallet', IWalletContract.ABI(), address, supportedProvider, txDefaults, logDecodeDependencies); + classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + } +} + +// 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/contract-wrappers/src/generated-wrappers/multi_asset_proxy.ts b/packages/contract-wrappers/src/generated-wrappers/multi_asset_proxy.ts new file mode 100644 index 0000000000..676dab94b4 --- /dev/null +++ b/packages/contract-wrappers/src/generated-wrappers/multi_asset_proxy.ts @@ -0,0 +1,1747 @@ +// tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma +// tslint:disable:whitespace no-unbound-method no-trailing-whitespace +// tslint:disable:no-unused-variable +import { + BaseContract, + BlockRange, + EventCallback, + IndexedFilterValues, + SubscriptionManager, + PromiseWithTransactionHash, +} from '@0x/base-contract'; +import { schemas } from '@0x/json-schemas'; +import { + BlockParam, + BlockParamLiteral, + CallData, + ContractAbi, + ContractArtifact, + DecodedLogArgs, + LogWithDecodedArgs, + MethodAbi, + TransactionReceiptWithDecodedLogs, + TxData, + TxDataPayable, + SupportedProvider, +} from 'ethereum-types'; +import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; +import { 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 MultiAssetProxyEventArgs = + | MultiAssetProxyAuthorizedAddressAddedEventArgs + | MultiAssetProxyAuthorizedAddressRemovedEventArgs + | MultiAssetProxyAssetProxyRegisteredEventArgs; + +export enum MultiAssetProxyEvents { + AuthorizedAddressAdded = 'AuthorizedAddressAdded', + AuthorizedAddressRemoved = 'AuthorizedAddressRemoved', + AssetProxyRegistered = 'AssetProxyRegistered', +} + +export interface MultiAssetProxyAuthorizedAddressAddedEventArgs extends DecodedLogArgs { + target: string; + caller: string; +} + +export interface MultiAssetProxyAuthorizedAddressRemovedEventArgs extends DecodedLogArgs { + target: string; + caller: string; +} + +export interface MultiAssetProxyAssetProxyRegisteredEventArgs extends DecodedLogArgs { + id: string; + assetProxy: string; +} + +/* istanbul ignore next */ +// tslint:disable:no-parameter-reassignment +// tslint:disable-next-line:class-name +export class MultiAssetProxyContract extends BaseContract { + public assetProxies = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(index_0: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.isString('index_0', index_0); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as MultiAssetProxyContract; + const encodedData = self._strictEncodeArguments('assetProxies(bytes4)', [index_0]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('assetProxies(bytes4)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(index_0: string): string { + assert.isString('index_0', index_0); + const self = (this as any) as MultiAssetProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('assetProxies(bytes4)', [index_0]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as MultiAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('assetProxies(bytes4)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as MultiAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('assetProxies(bytes4)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Authorizes an address. + */ + public addAuthorizedAddress = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param target Address to authorize. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(target: string, txData?: Partial | undefined): Promise { + assert.isString('target', target); + const self = (this as any) as MultiAssetProxyContract; + const encodedData = self._strictEncodeArguments('addAuthorizedAddress(address)', [target.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.addAuthorizedAddress.estimateGasAsync.bind(self, target.toLowerCase()), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param target Address to authorize. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + target: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('target', target); + const self = (this as any) as MultiAssetProxyContract; + const txHashPromise = self.addAuthorizedAddress.sendTransactionAsync(target.toLowerCase(), txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param target Address to authorize. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(target: string, txData?: Partial | undefined): Promise { + assert.isString('target', target); + const self = (this as any) as MultiAssetProxyContract; + const encodedData = self._strictEncodeArguments('addAuthorizedAddress(address)', [target.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param target Address to authorize. + */ + async callAsync(target: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.isString('target', target); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as MultiAssetProxyContract; + const encodedData = self._strictEncodeArguments('addAuthorizedAddress(address)', [target.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('addAuthorizedAddress(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param target Address to authorize. + */ + getABIEncodedTransactionData(target: string): string { + assert.isString('target', target); + const self = (this as any) as MultiAssetProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('addAuthorizedAddress(address)', [ + target.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as MultiAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('addAuthorizedAddress(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as MultiAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('addAuthorizedAddress(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public authorities = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + index_0: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isBigNumber('index_0', index_0); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as MultiAssetProxyContract; + const encodedData = self._strictEncodeArguments('authorities(uint256)', [index_0]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('authorities(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(index_0: BigNumber): string { + assert.isBigNumber('index_0', index_0); + const self = (this as any) as MultiAssetProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('authorities(uint256)', [index_0]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as MultiAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('authorities(uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as MultiAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('authorities(uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Gets an asset proxy. + */ + public getAssetProxy = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param assetProxyId Id of the asset proxy. + * @returns The asset proxy registered to assetProxyId. Returns 0x0 if no proxy is registered. + */ + async callAsync( + assetProxyId: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('assetProxyId', assetProxyId); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as MultiAssetProxyContract; + const encodedData = self._strictEncodeArguments('getAssetProxy(bytes4)', [assetProxyId]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getAssetProxy(bytes4)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param assetProxyId Id of the asset proxy. + */ + getABIEncodedTransactionData(assetProxyId: string): string { + assert.isString('assetProxyId', assetProxyId); + const self = (this as any) as MultiAssetProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('getAssetProxy(bytes4)', [assetProxyId]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as MultiAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('getAssetProxy(bytes4)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as MultiAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('getAssetProxy(bytes4)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Removes authorizion of an address. + */ + public removeAuthorizedAddress = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param target Address to remove authorization from. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(target: string, txData?: Partial | undefined): Promise { + assert.isString('target', target); + const self = (this as any) as MultiAssetProxyContract; + const encodedData = self._strictEncodeArguments('removeAuthorizedAddress(address)', [target.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.removeAuthorizedAddress.estimateGasAsync.bind(self, target.toLowerCase()), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param target Address to remove authorization from. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + target: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('target', target); + const self = (this as any) as MultiAssetProxyContract; + const txHashPromise = self.removeAuthorizedAddress.sendTransactionAsync(target.toLowerCase(), txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param target Address to remove authorization from. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(target: string, txData?: Partial | undefined): Promise { + assert.isString('target', target); + const self = (this as any) as MultiAssetProxyContract; + const encodedData = self._strictEncodeArguments('removeAuthorizedAddress(address)', [target.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param target Address to remove authorization from. + */ + async callAsync(target: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.isString('target', target); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as MultiAssetProxyContract; + const encodedData = self._strictEncodeArguments('removeAuthorizedAddress(address)', [target.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddress(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param target Address to remove authorization from. + */ + getABIEncodedTransactionData(target: string): string { + assert.isString('target', target); + const self = (this as any) as MultiAssetProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('removeAuthorizedAddress(address)', [ + target.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as MultiAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddress(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as MultiAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddress(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public owner = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as MultiAssetProxyContract; + const encodedData = self._strictEncodeArguments('owner()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('owner()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as MultiAssetProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('owner()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as MultiAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('owner()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as MultiAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('owner()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Removes authorizion of an address. + */ + public removeAuthorizedAddressAtIndex = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param target Address to remove authorization from. + * @param index Index of target in authorities array. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + target: string, + index: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('target', target); + assert.isBigNumber('index', index); + const self = (this as any) as MultiAssetProxyContract; + const encodedData = self._strictEncodeArguments('removeAuthorizedAddressAtIndex(address,uint256)', [ + target.toLowerCase(), + index, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.removeAuthorizedAddressAtIndex.estimateGasAsync.bind(self, target.toLowerCase(), index), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param target Address to remove authorization from. + * @param index Index of target in authorities array. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + target: string, + index: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('target', target); + assert.isBigNumber('index', index); + const self = (this as any) as MultiAssetProxyContract; + const txHashPromise = self.removeAuthorizedAddressAtIndex.sendTransactionAsync( + target.toLowerCase(), + index, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param target Address to remove authorization from. + * @param index Index of target in authorities array. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + target: string, + index: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('target', target); + assert.isBigNumber('index', index); + const self = (this as any) as MultiAssetProxyContract; + const encodedData = self._strictEncodeArguments('removeAuthorizedAddressAtIndex(address,uint256)', [ + target.toLowerCase(), + index, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param target Address to remove authorization from. + * @param index Index of target in authorities array. + */ + async callAsync( + target: string, + index: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('target', target); + assert.isBigNumber('index', index); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as MultiAssetProxyContract; + const encodedData = self._strictEncodeArguments('removeAuthorizedAddressAtIndex(address,uint256)', [ + target.toLowerCase(), + index, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddressAtIndex(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param target Address to remove authorization from. + * @param index Index of target in authorities array. + */ + getABIEncodedTransactionData(target: string, index: BigNumber): string { + assert.isString('target', target); + assert.isBigNumber('index', index); + const self = (this as any) as MultiAssetProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'removeAuthorizedAddressAtIndex(address,uint256)', + [target.toLowerCase(), index], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as MultiAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddressAtIndex(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as MultiAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddressAtIndex(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Gets the proxy id associated with the proxy address. + */ + public getProxyId = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @returns Proxy id. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as MultiAssetProxyContract; + const encodedData = self._strictEncodeArguments('getProxyId()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getProxyId()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as MultiAssetProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('getProxyId()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as MultiAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('getProxyId()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as MultiAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('getProxyId()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public authorized = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + index_0: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('index_0', index_0); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as MultiAssetProxyContract; + const encodedData = self._strictEncodeArguments('authorized(address)', [index_0.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('authorized(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(index_0: string): string { + assert.isString('index_0', index_0); + const self = (this as any) as MultiAssetProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('authorized(address)', [ + index_0.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): boolean { + const self = (this as any) as MultiAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('authorized(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): boolean { + const self = (this as any) as MultiAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('authorized(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Registers an asset proxy to its asset proxy id. + * Once an asset proxy is registered, it cannot be unregistered. + */ + public registerAssetProxy = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param assetProxy Address of new asset proxy to register. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(assetProxy: string, txData?: Partial | undefined): Promise { + assert.isString('assetProxy', assetProxy); + const self = (this as any) as MultiAssetProxyContract; + const encodedData = self._strictEncodeArguments('registerAssetProxy(address)', [assetProxy.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.registerAssetProxy.estimateGasAsync.bind(self, assetProxy.toLowerCase()), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param assetProxy Address of new asset proxy to register. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + assetProxy: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('assetProxy', assetProxy); + const self = (this as any) as MultiAssetProxyContract; + const txHashPromise = self.registerAssetProxy.sendTransactionAsync(assetProxy.toLowerCase(), txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param assetProxy Address of new asset proxy to register. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(assetProxy: string, txData?: Partial | undefined): Promise { + assert.isString('assetProxy', assetProxy); + const self = (this as any) as MultiAssetProxyContract; + const encodedData = self._strictEncodeArguments('registerAssetProxy(address)', [assetProxy.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param assetProxy Address of new asset proxy to register. + */ + async callAsync( + assetProxy: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('assetProxy', assetProxy); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as MultiAssetProxyContract; + const encodedData = self._strictEncodeArguments('registerAssetProxy(address)', [assetProxy.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('registerAssetProxy(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param assetProxy Address of new asset proxy to register. + */ + getABIEncodedTransactionData(assetProxy: string): string { + assert.isString('assetProxy', assetProxy); + const self = (this as any) as MultiAssetProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('registerAssetProxy(address)', [ + assetProxy.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as MultiAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('registerAssetProxy(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as MultiAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('registerAssetProxy(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * Gets all authorized addresses. + */ + public getAuthorizedAddresses = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @returns Array of authorized addresses. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as MultiAssetProxyContract; + const encodedData = self._strictEncodeArguments('getAuthorizedAddresses()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getAuthorizedAddresses()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as MultiAssetProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('getAuthorizedAddresses()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string[] { + const self = (this as any) as MultiAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('getAuthorizedAddresses()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string[] { + const self = (this as any) as MultiAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('getAuthorizedAddresses()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public transferOwnership = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(newOwner: string, txData?: Partial | undefined): Promise { + assert.isString('newOwner', newOwner); + const self = (this as any) as MultiAssetProxyContract; + const encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.transferOwnership.estimateGasAsync.bind(self, newOwner.toLowerCase()), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + newOwner: string, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('newOwner', newOwner); + const self = (this as any) as MultiAssetProxyContract; + const txHashPromise = self.transferOwnership.sendTransactionAsync(newOwner.toLowerCase(), txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(newOwner: string, txData?: Partial | undefined): Promise { + assert.isString('newOwner', newOwner); + const self = (this as any) as MultiAssetProxyContract; + const encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(newOwner: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.isString('newOwner', newOwner); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as MultiAssetProxyContract; + const encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(newOwner: string): string { + assert.isString('newOwner', newOwner); + const self = (this as any) as MultiAssetProxyContract; + const abiEncodedTransactionData = self._strictEncodeArguments('transferOwnership(address)', [ + newOwner.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as MultiAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as MultiAssetProxyContract; + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + 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 MultiAssetProxyContract.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._applyDefaultsToTxDataAsync( + { 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(`MultiAssetProxy successfully deployed at ${txReceipt.contractAddress}`); + const contractInstance = new MultiAssetProxyContract( + 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: 'index_0', + type: 'bytes4', + }, + ], + name: 'assetProxies', + outputs: [ + { + name: '', + type: 'address', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'target', + type: 'address', + }, + ], + name: 'addAuthorizedAddress', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'index_0', + type: 'uint256', + }, + ], + name: 'authorities', + outputs: [ + { + name: '', + type: 'address', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'assetProxyId', + type: 'bytes4', + }, + ], + name: 'getAssetProxy', + outputs: [ + { + name: '', + type: 'address', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'target', + type: 'address', + }, + ], + name: 'removeAuthorizedAddress', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'owner', + outputs: [ + { + name: '', + type: 'address', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'target', + type: 'address', + }, + { + name: 'index', + type: 'uint256', + }, + ], + name: 'removeAuthorizedAddressAtIndex', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'getProxyId', + outputs: [ + { + name: '', + type: 'bytes4', + }, + ], + payable: false, + stateMutability: 'pure', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'index_0', + type: 'address', + }, + ], + name: 'authorized', + outputs: [ + { + name: '', + type: 'bool', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'assetProxy', + type: 'address', + }, + ], + name: 'registerAssetProxy', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'getAuthorizedAddresses', + outputs: [ + { + name: '', + type: 'address[]', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'newOwner', + type: 'address', + }, + ], + name: 'transferOwnership', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + inputs: [], + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'fallback', + }, + { + anonymous: false, + inputs: [ + { + name: 'target', + type: 'address', + indexed: true, + }, + { + name: 'caller', + type: 'address', + indexed: true, + }, + ], + name: 'AuthorizedAddressAdded', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: 'target', + type: 'address', + indexed: true, + }, + { + name: 'caller', + type: 'address', + indexed: true, + }, + ], + name: 'AuthorizedAddressRemoved', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: 'id', + type: 'bytes4', + indexed: false, + }, + { + name: 'assetProxy', + type: 'address', + indexed: false, + }, + ], + name: 'AssetProxyRegistered', + outputs: [], + type: 'event', + }, + ] as ContractAbi; + return abi; + } + /** + * Subscribe to an event type emitted by the MultiAssetProxy contract. + * @param eventName The MultiAssetProxy 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: MultiAssetProxyEvents, + indexFilterValues: IndexedFilterValues, + callback: EventCallback, + isVerbose: boolean = false, + blockPollingIntervalMs?: number, + ): string { + assert.doesBelongToStringEnum('eventName', eventName, MultiAssetProxyEvents); + assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); + assert.isFunction('callback', callback); + const subscriptionToken = this._subscriptionManager.subscribe( + this.address, + eventName, + indexFilterValues, + MultiAssetProxyContract.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 MultiAssetProxy 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: MultiAssetProxyEvents, + blockRange: BlockRange, + indexFilterValues: IndexedFilterValues, + ): Promise>> { + assert.doesBelongToStringEnum('eventName', eventName, MultiAssetProxyEvents); + assert.doesConformToSchema('blockRange', blockRange, schemas.blockRangeSchema); + assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); + const logs = await this._subscriptionManager.getLogsAsync( + this.address, + eventName, + blockRange, + indexFilterValues, + MultiAssetProxyContract.ABI(), + ); + return logs; + } + constructor( + address: string, + supportedProvider: SupportedProvider, + txDefaults?: Partial, + logDecodeDependencies?: { [contractName: string]: ContractAbi }, + ) { + super( + 'MultiAssetProxy', + MultiAssetProxyContract.ABI(), + address, + supportedProvider, + txDefaults, + logDecodeDependencies, + ); + classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + this._subscriptionManager = new SubscriptionManager( + MultiAssetProxyContract.ABI(), + this._web3Wrapper, + ); + } +} + +// 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/contract-wrappers/src/generated-wrappers/order_validator.ts b/packages/contract-wrappers/src/generated-wrappers/order_validator.ts new file mode 100644 index 0000000000..b7499f179d --- /dev/null +++ b/packages/contract-wrappers/src/generated-wrappers/order_validator.ts @@ -0,0 +1,1662 @@ +// tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma +// tslint:disable:whitespace no-unbound-method no-trailing-whitespace +// tslint:disable:no-unused-variable +import { BaseContract, PromiseWithTransactionHash } from '@0x/base-contract'; +import { schemas } from '@0x/json-schemas'; +import { + BlockParam, + BlockParamLiteral, + CallData, + ContractAbi, + ContractArtifact, + DecodedLogArgs, + MethodAbi, + TransactionReceiptWithDecodedLogs, + TxData, + TxDataPayable, + SupportedProvider, +} from 'ethereum-types'; +import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; +import { 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:no-parameter-reassignment +// tslint:disable-next-line:class-name +export class OrderValidatorContract extends BaseContract { + public getOrderAndTraderInfo = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + takerAddress: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise< + [ + { orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }, + { + makerBalance: BigNumber; + makerAllowance: BigNumber; + takerBalance: BigNumber; + takerAllowance: BigNumber; + makerZrxBalance: BigNumber; + makerZrxAllowance: BigNumber; + takerZrxBalance: BigNumber; + takerZrxAllowance: BigNumber; + } + ] + > { + assert.isString('takerAddress', takerAddress); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as OrderValidatorContract; + const encodedData = self._strictEncodeArguments( + 'getOrderAndTraderInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),address)', + [order, takerAddress.toLowerCase()], + ); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'getOrderAndTraderInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),address)', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue< + [ + { orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }, + { + makerBalance: BigNumber; + makerAllowance: BigNumber; + takerBalance: BigNumber; + takerAllowance: BigNumber; + makerZrxBalance: BigNumber; + makerZrxAllowance: BigNumber; + takerZrxBalance: BigNumber; + takerZrxAllowance: BigNumber; + } + ] + >(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData( + order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + takerAddress: string, + ): string { + assert.isString('takerAddress', takerAddress); + const self = (this as any) as OrderValidatorContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'getOrderAndTraderInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),address)', + [order, takerAddress.toLowerCase()], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData( + callData: string, + ): [ + { orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }, + { + makerBalance: BigNumber; + makerAllowance: BigNumber; + takerBalance: BigNumber; + takerAllowance: BigNumber; + makerZrxBalance: BigNumber; + makerZrxAllowance: BigNumber; + takerZrxBalance: BigNumber; + takerZrxAllowance: BigNumber; + } + ] { + const self = (this as any) as OrderValidatorContract; + const abiEncoder = self._lookupAbiEncoder( + 'getOrderAndTraderInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),address)', + ); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode< + [ + { orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }, + { + makerBalance: BigNumber; + makerAllowance: BigNumber; + takerBalance: BigNumber; + takerAllowance: BigNumber; + makerZrxBalance: BigNumber; + makerZrxAllowance: BigNumber; + takerZrxBalance: BigNumber; + takerZrxAllowance: BigNumber; + } + ] + >(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData( + returnData: string, + ): [ + { orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }, + { + makerBalance: BigNumber; + makerAllowance: BigNumber; + takerBalance: BigNumber; + takerAllowance: BigNumber; + makerZrxBalance: BigNumber; + makerZrxAllowance: BigNumber; + takerZrxBalance: BigNumber; + takerZrxAllowance: BigNumber; + } + ] { + const self = (this as any) as OrderValidatorContract; + const abiEncoder = self._lookupAbiEncoder( + 'getOrderAndTraderInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),address)', + ); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue< + [ + { orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }, + { + makerBalance: BigNumber; + makerAllowance: BigNumber; + takerBalance: BigNumber; + takerAllowance: BigNumber; + makerZrxBalance: BigNumber; + makerZrxAllowance: BigNumber; + takerZrxBalance: BigNumber; + takerZrxAllowance: BigNumber; + } + ] + >(returnData); + return abiDecodedReturnData; + }, + }; + public getBalanceAndAllowance = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + target: string, + assetData: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<[BigNumber, BigNumber]> { + assert.isString('target', target); + assert.isString('assetData', assetData); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as OrderValidatorContract; + const encodedData = self._strictEncodeArguments('getBalanceAndAllowance(address,bytes)', [ + target.toLowerCase(), + assetData, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getBalanceAndAllowance(address,bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[BigNumber, BigNumber]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(target: string, assetData: string): string { + assert.isString('target', target); + assert.isString('assetData', assetData); + const self = (this as any) as OrderValidatorContract; + const abiEncodedTransactionData = self._strictEncodeArguments('getBalanceAndAllowance(address,bytes)', [ + target.toLowerCase(), + assetData, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): [BigNumber, BigNumber] { + const self = (this as any) as OrderValidatorContract; + const abiEncoder = self._lookupAbiEncoder('getBalanceAndAllowance(address,bytes)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode<[BigNumber, BigNumber]>(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): [BigNumber, BigNumber] { + const self = (this as any) as OrderValidatorContract; + const abiEncoder = self._lookupAbiEncoder('getBalanceAndAllowance(address,bytes)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue<[BigNumber, BigNumber]>(returnData); + return abiDecodedReturnData; + }, + }; + public getOrdersAndTradersInfo = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAddresses: string[], + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise< + [ + Array<{ orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }>, + Array<{ + makerBalance: BigNumber; + makerAllowance: BigNumber; + takerBalance: BigNumber; + takerAllowance: BigNumber; + makerZrxBalance: BigNumber; + makerZrxAllowance: BigNumber; + takerZrxBalance: BigNumber; + takerZrxAllowance: BigNumber; + }> + ] + > { + assert.isArray('orders', orders); + assert.isArray('takerAddresses', takerAddresses); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as OrderValidatorContract; + const encodedData = self._strictEncodeArguments( + 'getOrdersAndTradersInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],address[])', + [orders, takerAddresses], + ); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'getOrdersAndTradersInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],address[])', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue< + [ + Array<{ orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }>, + Array<{ + makerBalance: BigNumber; + makerAllowance: BigNumber; + takerBalance: BigNumber; + takerAllowance: BigNumber; + makerZrxBalance: BigNumber; + makerZrxAllowance: BigNumber; + takerZrxBalance: BigNumber; + takerZrxAllowance: BigNumber; + }> + ] + >(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAddresses: string[], + ): string { + assert.isArray('orders', orders); + assert.isArray('takerAddresses', takerAddresses); + const self = (this as any) as OrderValidatorContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'getOrdersAndTradersInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],address[])', + [orders, takerAddresses], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData( + callData: string, + ): [ + Array<{ orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }>, + Array<{ + makerBalance: BigNumber; + makerAllowance: BigNumber; + takerBalance: BigNumber; + takerAllowance: BigNumber; + makerZrxBalance: BigNumber; + makerZrxAllowance: BigNumber; + takerZrxBalance: BigNumber; + takerZrxAllowance: BigNumber; + }> + ] { + const self = (this as any) as OrderValidatorContract; + const abiEncoder = self._lookupAbiEncoder( + 'getOrdersAndTradersInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],address[])', + ); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode< + [ + Array<{ orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }>, + Array<{ + makerBalance: BigNumber; + makerAllowance: BigNumber; + takerBalance: BigNumber; + takerAllowance: BigNumber; + makerZrxBalance: BigNumber; + makerZrxAllowance: BigNumber; + takerZrxBalance: BigNumber; + takerZrxAllowance: BigNumber; + }> + ] + >(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData( + returnData: string, + ): [ + Array<{ orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }>, + Array<{ + makerBalance: BigNumber; + makerAllowance: BigNumber; + takerBalance: BigNumber; + takerAllowance: BigNumber; + makerZrxBalance: BigNumber; + makerZrxAllowance: BigNumber; + takerZrxBalance: BigNumber; + takerZrxAllowance: BigNumber; + }> + ] { + const self = (this as any) as OrderValidatorContract; + const abiEncoder = self._lookupAbiEncoder( + 'getOrdersAndTradersInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],address[])', + ); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue< + [ + Array<{ orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }>, + Array<{ + makerBalance: BigNumber; + makerAllowance: BigNumber; + takerBalance: BigNumber; + takerAllowance: BigNumber; + makerZrxBalance: BigNumber; + makerZrxAllowance: BigNumber; + takerZrxBalance: BigNumber; + takerZrxAllowance: BigNumber; + }> + ] + >(returnData); + return abiDecodedReturnData; + }, + }; + public getTradersInfo = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAddresses: string[], + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise< + Array<{ + makerBalance: BigNumber; + makerAllowance: BigNumber; + takerBalance: BigNumber; + takerAllowance: BigNumber; + makerZrxBalance: BigNumber; + makerZrxAllowance: BigNumber; + takerZrxBalance: BigNumber; + takerZrxAllowance: BigNumber; + }> + > { + assert.isArray('orders', orders); + assert.isArray('takerAddresses', takerAddresses); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as OrderValidatorContract; + const encodedData = self._strictEncodeArguments( + 'getTradersInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],address[])', + [orders, takerAddresses], + ); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'getTradersInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],address[])', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue< + Array<{ + makerBalance: BigNumber; + makerAllowance: BigNumber; + takerBalance: BigNumber; + takerAllowance: BigNumber; + makerZrxBalance: BigNumber; + makerZrxAllowance: BigNumber; + takerZrxBalance: BigNumber; + takerZrxAllowance: BigNumber; + }> + >(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData( + orders: Array<{ + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }>, + takerAddresses: string[], + ): string { + assert.isArray('orders', orders); + assert.isArray('takerAddresses', takerAddresses); + const self = (this as any) as OrderValidatorContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'getTradersInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],address[])', + [orders, takerAddresses], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData( + callData: string, + ): Array<{ + makerBalance: BigNumber; + makerAllowance: BigNumber; + takerBalance: BigNumber; + takerAllowance: BigNumber; + makerZrxBalance: BigNumber; + makerZrxAllowance: BigNumber; + takerZrxBalance: BigNumber; + takerZrxAllowance: BigNumber; + }> { + const self = (this as any) as OrderValidatorContract; + const abiEncoder = self._lookupAbiEncoder( + 'getTradersInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],address[])', + ); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode< + Array<{ + makerBalance: BigNumber; + makerAllowance: BigNumber; + takerBalance: BigNumber; + takerAllowance: BigNumber; + makerZrxBalance: BigNumber; + makerZrxAllowance: BigNumber; + takerZrxBalance: BigNumber; + takerZrxAllowance: BigNumber; + }> + >(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData( + returnData: string, + ): Array<{ + makerBalance: BigNumber; + makerAllowance: BigNumber; + takerBalance: BigNumber; + takerAllowance: BigNumber; + makerZrxBalance: BigNumber; + makerZrxAllowance: BigNumber; + takerZrxBalance: BigNumber; + takerZrxAllowance: BigNumber; + }> { + const self = (this as any) as OrderValidatorContract; + const abiEncoder = self._lookupAbiEncoder( + 'getTradersInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],address[])', + ); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue< + Array<{ + makerBalance: BigNumber; + makerAllowance: BigNumber; + takerBalance: BigNumber; + takerAllowance: BigNumber; + makerZrxBalance: BigNumber; + makerZrxAllowance: BigNumber; + takerZrxBalance: BigNumber; + takerZrxAllowance: BigNumber; + }> + >(returnData); + return abiDecodedReturnData; + }, + }; + public getERC721TokenOwner = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + token: string, + tokenId: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('token', token); + assert.isBigNumber('tokenId', tokenId); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as OrderValidatorContract; + const encodedData = self._strictEncodeArguments('getERC721TokenOwner(address,uint256)', [ + token.toLowerCase(), + tokenId, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getERC721TokenOwner(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(token: string, tokenId: BigNumber): string { + assert.isString('token', token); + assert.isBigNumber('tokenId', tokenId); + const self = (this as any) as OrderValidatorContract; + const abiEncodedTransactionData = self._strictEncodeArguments('getERC721TokenOwner(address,uint256)', [ + token.toLowerCase(), + tokenId, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as OrderValidatorContract; + const abiEncoder = self._lookupAbiEncoder('getERC721TokenOwner(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as OrderValidatorContract; + const abiEncoder = self._lookupAbiEncoder('getERC721TokenOwner(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public getBalancesAndAllowances = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + target: string, + assetData: string[], + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<[BigNumber[], BigNumber[]]> { + assert.isString('target', target); + assert.isArray('assetData', assetData); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as OrderValidatorContract; + const encodedData = self._strictEncodeArguments('getBalancesAndAllowances(address,bytes[])', [ + target.toLowerCase(), + assetData, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getBalancesAndAllowances(address,bytes[])'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[BigNumber[], BigNumber[]]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(target: string, assetData: string[]): string { + assert.isString('target', target); + assert.isArray('assetData', assetData); + const self = (this as any) as OrderValidatorContract; + const abiEncodedTransactionData = self._strictEncodeArguments('getBalancesAndAllowances(address,bytes[])', [ + target.toLowerCase(), + assetData, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): [BigNumber[], BigNumber[]] { + const self = (this as any) as OrderValidatorContract; + const abiEncoder = self._lookupAbiEncoder('getBalancesAndAllowances(address,bytes[])'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode<[BigNumber[], BigNumber[]]>(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): [BigNumber[], BigNumber[]] { + const self = (this as any) as OrderValidatorContract; + const abiEncoder = self._lookupAbiEncoder('getBalancesAndAllowances(address,bytes[])'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue<[BigNumber[], BigNumber[]]>(returnData); + return abiDecodedReturnData; + }, + }; + public getTraderInfo = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + takerAddress: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ + makerBalance: BigNumber; + makerAllowance: BigNumber; + takerBalance: BigNumber; + takerAllowance: BigNumber; + makerZrxBalance: BigNumber; + makerZrxAllowance: BigNumber; + takerZrxBalance: BigNumber; + takerZrxAllowance: BigNumber; + }> { + assert.isString('takerAddress', takerAddress); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as OrderValidatorContract; + const encodedData = self._strictEncodeArguments( + 'getTraderInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),address)', + [order, takerAddress.toLowerCase()], + ); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'getTraderInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),address)', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + makerBalance: BigNumber; + makerAllowance: BigNumber; + takerBalance: BigNumber; + takerAllowance: BigNumber; + makerZrxBalance: BigNumber; + makerZrxAllowance: BigNumber; + takerZrxBalance: BigNumber; + takerZrxAllowance: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData( + order: { + makerAddress: string; + takerAddress: string; + feeRecipientAddress: string; + senderAddress: string; + makerAssetAmount: BigNumber; + takerAssetAmount: BigNumber; + makerFee: BigNumber; + takerFee: BigNumber; + expirationTimeSeconds: BigNumber; + salt: BigNumber; + makerAssetData: string; + takerAssetData: string; + }, + takerAddress: string, + ): string { + assert.isString('takerAddress', takerAddress); + const self = (this as any) as OrderValidatorContract; + const abiEncodedTransactionData = self._strictEncodeArguments( + 'getTraderInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),address)', + [order, takerAddress.toLowerCase()], + ); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData( + callData: string, + ): { + makerBalance: BigNumber; + makerAllowance: BigNumber; + takerBalance: BigNumber; + takerAllowance: BigNumber; + makerZrxBalance: BigNumber; + makerZrxAllowance: BigNumber; + takerZrxBalance: BigNumber; + takerZrxAllowance: BigNumber; + } { + const self = (this as any) as OrderValidatorContract; + const abiEncoder = self._lookupAbiEncoder( + 'getTraderInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),address)', + ); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode<{ + makerBalance: BigNumber; + makerAllowance: BigNumber; + takerBalance: BigNumber; + takerAllowance: BigNumber; + makerZrxBalance: BigNumber; + makerZrxAllowance: BigNumber; + takerZrxBalance: BigNumber; + takerZrxAllowance: BigNumber; + }>(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData( + returnData: string, + ): { + makerBalance: BigNumber; + makerAllowance: BigNumber; + takerBalance: BigNumber; + takerAllowance: BigNumber; + makerZrxBalance: BigNumber; + makerZrxAllowance: BigNumber; + takerZrxBalance: BigNumber; + takerZrxAllowance: BigNumber; + } { + const self = (this as any) as OrderValidatorContract; + const abiEncoder = self._lookupAbiEncoder( + 'getTraderInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),address)', + ); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue<{ + makerBalance: BigNumber; + makerAllowance: BigNumber; + takerBalance: BigNumber; + takerAllowance: BigNumber; + makerZrxBalance: BigNumber; + makerZrxAllowance: BigNumber; + takerZrxBalance: BigNumber; + takerZrxAllowance: BigNumber; + }>(returnData); + return abiDecodedReturnData; + }, + }; + public static async deployFrom0xArtifactAsync( + artifact: ContractArtifact | SimpleContractArtifact, + supportedProvider: SupportedProvider, + txDefaults: Partial, + logDecodeDependencies: { [contractName: string]: ContractArtifact | SimpleContractArtifact }, + _exchange: string, + _zrxAssetData: string, + ): 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 OrderValidatorContract.deployAsync( + bytecode, + abi, + provider, + txDefaults, + logDecodeDependenciesAbiOnly, + _exchange, + _zrxAssetData, + ); + } + public static async deployAsync( + bytecode: string, + abi: ContractAbi, + supportedProvider: SupportedProvider, + txDefaults: Partial, + logDecodeDependencies: { [contractName: string]: ContractAbi }, + _exchange: string, + _zrxAssetData: string, + ): 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); + [_exchange, _zrxAssetData] = BaseContract._formatABIDataItemList( + constructorAbi.inputs, + [_exchange, _zrxAssetData], + BaseContract._bigNumberToString, + ); + const iface = new ethers.utils.Interface(abi); + const deployInfo = iface.deployFunction; + const txData = deployInfo.encode(bytecode, [_exchange, _zrxAssetData]); + const web3Wrapper = new Web3Wrapper(provider); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { 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(`OrderValidator successfully deployed at ${txReceipt.contractAddress}`); + const contractInstance = new OrderValidatorContract( + txReceipt.contractAddress as string, + provider, + txDefaults, + logDecodeDependencies, + ); + contractInstance.constructorArgs = [_exchange, _zrxAssetData]; + return contractInstance; + } + + /** + * @returns The contract ABI + */ + public static ABI(): ContractAbi { + const abi = [ + { + constant: true, + inputs: [ + { + name: 'order', + type: 'tuple', + 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: 'takerAddress', + type: 'address', + }, + ], + name: 'getOrderAndTraderInfo', + outputs: [ + { + name: 'orderInfo', + type: 'tuple', + components: [ + { + name: 'orderStatus', + type: 'uint8', + }, + { + name: 'orderHash', + type: 'bytes32', + }, + { + name: 'orderTakerAssetFilledAmount', + type: 'uint256', + }, + ], + }, + { + name: 'traderInfo', + type: 'tuple', + components: [ + { + name: 'makerBalance', + type: 'uint256', + }, + { + name: 'makerAllowance', + type: 'uint256', + }, + { + name: 'takerBalance', + type: 'uint256', + }, + { + name: 'takerAllowance', + type: 'uint256', + }, + { + name: 'makerZrxBalance', + type: 'uint256', + }, + { + name: 'makerZrxAllowance', + type: 'uint256', + }, + { + name: 'takerZrxBalance', + type: 'uint256', + }, + { + name: 'takerZrxAllowance', + type: 'uint256', + }, + ], + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'target', + type: 'address', + }, + { + name: 'assetData', + type: 'bytes', + }, + ], + name: 'getBalanceAndAllowance', + outputs: [ + { + name: 'balance', + type: 'uint256', + }, + { + name: 'allowance', + type: 'uint256', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'orders', + type: 'tuple[]', + 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: 'takerAddresses', + type: 'address[]', + }, + ], + name: 'getOrdersAndTradersInfo', + outputs: [ + { + name: 'ordersInfo', + type: 'tuple[]', + components: [ + { + name: 'orderStatus', + type: 'uint8', + }, + { + name: 'orderHash', + type: 'bytes32', + }, + { + name: 'orderTakerAssetFilledAmount', + type: 'uint256', + }, + ], + }, + { + name: 'tradersInfo', + type: 'tuple[]', + components: [ + { + name: 'makerBalance', + type: 'uint256', + }, + { + name: 'makerAllowance', + type: 'uint256', + }, + { + name: 'takerBalance', + type: 'uint256', + }, + { + name: 'takerAllowance', + type: 'uint256', + }, + { + name: 'makerZrxBalance', + type: 'uint256', + }, + { + name: 'makerZrxAllowance', + type: 'uint256', + }, + { + name: 'takerZrxBalance', + type: 'uint256', + }, + { + name: 'takerZrxAllowance', + type: 'uint256', + }, + ], + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'orders', + type: 'tuple[]', + 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: 'takerAddresses', + type: 'address[]', + }, + ], + name: 'getTradersInfo', + outputs: [ + { + name: '', + type: 'tuple[]', + components: [ + { + name: 'makerBalance', + type: 'uint256', + }, + { + name: 'makerAllowance', + type: 'uint256', + }, + { + name: 'takerBalance', + type: 'uint256', + }, + { + name: 'takerAllowance', + type: 'uint256', + }, + { + name: 'makerZrxBalance', + type: 'uint256', + }, + { + name: 'makerZrxAllowance', + type: 'uint256', + }, + { + name: 'takerZrxBalance', + type: 'uint256', + }, + { + name: 'takerZrxAllowance', + type: 'uint256', + }, + ], + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'token', + type: 'address', + }, + { + name: 'tokenId', + type: 'uint256', + }, + ], + name: 'getERC721TokenOwner', + outputs: [ + { + name: 'owner', + type: 'address', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'target', + type: 'address', + }, + { + name: 'assetData', + type: 'bytes[]', + }, + ], + name: 'getBalancesAndAllowances', + outputs: [ + { + name: '', + type: 'uint256[]', + }, + { + name: '', + type: 'uint256[]', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'order', + type: 'tuple', + 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: 'takerAddress', + type: 'address', + }, + ], + name: 'getTraderInfo', + outputs: [ + { + name: 'traderInfo', + type: 'tuple', + components: [ + { + name: 'makerBalance', + type: 'uint256', + }, + { + name: 'makerAllowance', + type: 'uint256', + }, + { + name: 'takerBalance', + type: 'uint256', + }, + { + name: 'takerAllowance', + type: 'uint256', + }, + { + name: 'makerZrxBalance', + type: 'uint256', + }, + { + name: 'makerZrxAllowance', + type: 'uint256', + }, + { + name: 'takerZrxBalance', + type: 'uint256', + }, + { + name: 'takerZrxAllowance', + type: 'uint256', + }, + ], + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + name: '_exchange', + type: 'address', + }, + { + name: '_zrxAssetData', + type: 'bytes', + }, + ], + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'constructor', + }, + ] as ContractAbi; + return abi; + } + constructor( + address: string, + supportedProvider: SupportedProvider, + txDefaults?: Partial, + logDecodeDependencies?: { [contractName: string]: ContractAbi }, + ) { + super( + 'OrderValidator', + OrderValidatorContract.ABI(), + address, + supportedProvider, + txDefaults, + logDecodeDependencies, + ); + classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + } +} + +// 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/contract-wrappers/src/generated-wrappers/weth9.ts b/packages/contract-wrappers/src/generated-wrappers/weth9.ts new file mode 100644 index 0000000000..208683f64b --- /dev/null +++ b/packages/contract-wrappers/src/generated-wrappers/weth9.ts @@ -0,0 +1,1690 @@ +// tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma +// tslint:disable:whitespace no-unbound-method no-trailing-whitespace +// tslint:disable:no-unused-variable +import { + BaseContract, + BlockRange, + EventCallback, + IndexedFilterValues, + SubscriptionManager, + PromiseWithTransactionHash, +} from '@0x/base-contract'; +import { schemas } from '@0x/json-schemas'; +import { + BlockParam, + BlockParamLiteral, + CallData, + ContractAbi, + ContractArtifact, + DecodedLogArgs, + LogWithDecodedArgs, + MethodAbi, + TransactionReceiptWithDecodedLogs, + TxData, + TxDataPayable, + SupportedProvider, +} from 'ethereum-types'; +import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; +import { 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 WETH9EventArgs = + | WETH9ApprovalEventArgs + | WETH9TransferEventArgs + | WETH9DepositEventArgs + | WETH9WithdrawalEventArgs; + +export enum WETH9Events { + Approval = 'Approval', + Transfer = 'Transfer', + Deposit = 'Deposit', + Withdrawal = 'Withdrawal', +} + +export interface WETH9ApprovalEventArgs extends DecodedLogArgs { + _owner: string; + _spender: string; + _value: BigNumber; +} + +export interface WETH9TransferEventArgs extends DecodedLogArgs { + _from: string; + _to: string; + _value: BigNumber; +} + +export interface WETH9DepositEventArgs extends DecodedLogArgs { + _owner: string; + _value: BigNumber; +} + +export interface WETH9WithdrawalEventArgs extends DecodedLogArgs { + _owner: string; + _value: BigNumber; +} + +/* istanbul ignore next */ +// tslint:disable:no-parameter-reassignment +// tslint:disable-next-line:class-name +export class WETH9Contract extends BaseContract { + public name = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as WETH9Contract; + const encodedData = self._strictEncodeArguments('name()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('name()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as WETH9Contract; + const abiEncodedTransactionData = self._strictEncodeArguments('name()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as WETH9Contract; + const abiEncoder = self._lookupAbiEncoder('name()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as WETH9Contract; + const abiEncoder = self._lookupAbiEncoder('name()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public approve = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(guy: string, wad: BigNumber, txData?: Partial | undefined): Promise { + assert.isString('guy', guy); + assert.isBigNumber('wad', wad); + const self = (this as any) as WETH9Contract; + const encodedData = self._strictEncodeArguments('approve(address,uint256)', [guy.toLowerCase(), wad]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.approve.estimateGasAsync.bind(self, guy.toLowerCase(), wad), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + guy: string, + wad: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('guy', guy); + assert.isBigNumber('wad', wad); + const self = (this as any) as WETH9Contract; + const txHashPromise = self.approve.sendTransactionAsync(guy.toLowerCase(), wad, txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(guy: string, wad: BigNumber, txData?: Partial | undefined): Promise { + assert.isString('guy', guy); + assert.isBigNumber('wad', wad); + const self = (this as any) as WETH9Contract; + const encodedData = self._strictEncodeArguments('approve(address,uint256)', [guy.toLowerCase(), wad]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + guy: string, + wad: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('guy', guy); + assert.isBigNumber('wad', wad); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as WETH9Contract; + const encodedData = self._strictEncodeArguments('approve(address,uint256)', [guy.toLowerCase(), wad]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('approve(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(guy: string, wad: BigNumber): string { + assert.isString('guy', guy); + assert.isBigNumber('wad', wad); + const self = (this as any) as WETH9Contract; + const abiEncodedTransactionData = self._strictEncodeArguments('approve(address,uint256)', [ + guy.toLowerCase(), + wad, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): boolean { + const self = (this as any) as WETH9Contract; + const abiEncoder = self._lookupAbiEncoder('approve(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): boolean { + const self = (this as any) as WETH9Contract; + const abiEncoder = self._lookupAbiEncoder('approve(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public totalSupply = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as WETH9Contract; + const encodedData = self._strictEncodeArguments('totalSupply()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('totalSupply()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as WETH9Contract; + const abiEncodedTransactionData = self._strictEncodeArguments('totalSupply()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): BigNumber { + const self = (this as any) as WETH9Contract; + const abiEncoder = self._lookupAbiEncoder('totalSupply()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): BigNumber { + const self = (this as any) as WETH9Contract; + const abiEncoder = self._lookupAbiEncoder('totalSupply()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public transferFrom = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + src: string, + dst: string, + wad: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('src', src); + assert.isString('dst', dst); + assert.isBigNumber('wad', wad); + const self = (this as any) as WETH9Contract; + const encodedData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + src.toLowerCase(), + dst.toLowerCase(), + wad, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.transferFrom.estimateGasAsync.bind(self, src.toLowerCase(), dst.toLowerCase(), wad), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + src: string, + dst: string, + wad: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('src', src); + assert.isString('dst', dst); + assert.isBigNumber('wad', wad); + const self = (this as any) as WETH9Contract; + const txHashPromise = self.transferFrom.sendTransactionAsync( + src.toLowerCase(), + dst.toLowerCase(), + wad, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + src: string, + dst: string, + wad: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('src', src); + assert.isString('dst', dst); + assert.isBigNumber('wad', wad); + const self = (this as any) as WETH9Contract; + const encodedData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + src.toLowerCase(), + dst.toLowerCase(), + wad, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + src: string, + dst: string, + wad: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('src', src); + assert.isString('dst', dst); + assert.isBigNumber('wad', wad); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as WETH9Contract; + const encodedData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + src.toLowerCase(), + dst.toLowerCase(), + wad, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(src: string, dst: string, wad: BigNumber): string { + assert.isString('src', src); + assert.isString('dst', dst); + assert.isBigNumber('wad', wad); + const self = (this as any) as WETH9Contract; + const abiEncodedTransactionData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + src.toLowerCase(), + dst.toLowerCase(), + wad, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): boolean { + const self = (this as any) as WETH9Contract; + const abiEncoder = self._lookupAbiEncoder('transferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): boolean { + const self = (this as any) as WETH9Contract; + const abiEncoder = self._lookupAbiEncoder('transferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public withdraw = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(wad: BigNumber, txData?: Partial | undefined): Promise { + assert.isBigNumber('wad', wad); + const self = (this as any) as WETH9Contract; + const encodedData = self._strictEncodeArguments('withdraw(uint256)', [wad]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.withdraw.estimateGasAsync.bind(self, wad), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + wad: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isBigNumber('wad', wad); + const self = (this as any) as WETH9Contract; + const txHashPromise = self.withdraw.sendTransactionAsync(wad, txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(wad: BigNumber, txData?: Partial | undefined): Promise { + assert.isBigNumber('wad', wad); + const self = (this as any) as WETH9Contract; + const encodedData = self._strictEncodeArguments('withdraw(uint256)', [wad]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(wad: BigNumber, callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.isBigNumber('wad', wad); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as WETH9Contract; + const encodedData = self._strictEncodeArguments('withdraw(uint256)', [wad]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('withdraw(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(wad: BigNumber): string { + assert.isBigNumber('wad', wad); + const self = (this as any) as WETH9Contract; + const abiEncodedTransactionData = self._strictEncodeArguments('withdraw(uint256)', [wad]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as WETH9Contract; + const abiEncoder = self._lookupAbiEncoder('withdraw(uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as WETH9Contract; + const abiEncoder = self._lookupAbiEncoder('withdraw(uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public decimals = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as WETH9Contract; + const encodedData = self._strictEncodeArguments('decimals()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decimals()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as WETH9Contract; + const abiEncodedTransactionData = self._strictEncodeArguments('decimals()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): number { + const self = (this as any) as WETH9Contract; + const abiEncoder = self._lookupAbiEncoder('decimals()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): number { + const self = (this as any) as WETH9Contract; + const abiEncoder = self._lookupAbiEncoder('decimals()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public balanceOf = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + index_0: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('index_0', index_0); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as WETH9Contract; + const encodedData = self._strictEncodeArguments('balanceOf(address)', [index_0.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('balanceOf(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(index_0: string): string { + assert.isString('index_0', index_0); + const self = (this as any) as WETH9Contract; + const abiEncodedTransactionData = self._strictEncodeArguments('balanceOf(address)', [ + index_0.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): BigNumber { + const self = (this as any) as WETH9Contract; + const abiEncoder = self._lookupAbiEncoder('balanceOf(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): BigNumber { + const self = (this as any) as WETH9Contract; + const abiEncoder = self._lookupAbiEncoder('balanceOf(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public symbol = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as WETH9Contract; + const encodedData = self._strictEncodeArguments('symbol()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('symbol()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as WETH9Contract; + const abiEncodedTransactionData = self._strictEncodeArguments('symbol()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as WETH9Contract; + const abiEncoder = self._lookupAbiEncoder('symbol()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as WETH9Contract; + const abiEncoder = self._lookupAbiEncoder('symbol()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public transfer = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(dst: string, wad: BigNumber, txData?: Partial | undefined): Promise { + assert.isString('dst', dst); + assert.isBigNumber('wad', wad); + const self = (this as any) as WETH9Contract; + const encodedData = self._strictEncodeArguments('transfer(address,uint256)', [dst.toLowerCase(), wad]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.transfer.estimateGasAsync.bind(self, dst.toLowerCase(), wad), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + dst: string, + wad: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('dst', dst); + assert.isBigNumber('wad', wad); + const self = (this as any) as WETH9Contract; + const txHashPromise = self.transfer.sendTransactionAsync(dst.toLowerCase(), wad, txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(dst: string, wad: BigNumber, txData?: Partial | undefined): Promise { + assert.isString('dst', dst); + assert.isBigNumber('wad', wad); + const self = (this as any) as WETH9Contract; + const encodedData = self._strictEncodeArguments('transfer(address,uint256)', [dst.toLowerCase(), wad]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + dst: string, + wad: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('dst', dst); + assert.isBigNumber('wad', wad); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as WETH9Contract; + const encodedData = self._strictEncodeArguments('transfer(address,uint256)', [dst.toLowerCase(), wad]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transfer(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(dst: string, wad: BigNumber): string { + assert.isString('dst', dst); + assert.isBigNumber('wad', wad); + const self = (this as any) as WETH9Contract; + const abiEncodedTransactionData = self._strictEncodeArguments('transfer(address,uint256)', [ + dst.toLowerCase(), + wad, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): boolean { + const self = (this as any) as WETH9Contract; + const abiEncoder = self._lookupAbiEncoder('transfer(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): boolean { + const self = (this as any) as WETH9Contract; + const abiEncoder = self._lookupAbiEncoder('transfer(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public deposit = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync(txData?: Partial | undefined): Promise { + const self = (this as any) as WETH9Contract; + const encodedData = self._strictEncodeArguments('deposit()', []); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.deposit.estimateGasAsync.bind(self), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + const self = (this as any) as WETH9Contract; + const txHashPromise = self.deposit.sendTransactionAsync(txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(txData?: Partial | undefined): Promise { + const self = (this as any) as WETH9Contract; + const encodedData = self._strictEncodeArguments('deposit()', []); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as WETH9Contract; + const encodedData = self._strictEncodeArguments('deposit()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('deposit()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as WETH9Contract; + const abiEncodedTransactionData = self._strictEncodeArguments('deposit()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): void { + const self = (this as any) as WETH9Contract; + const abiEncoder = self._lookupAbiEncoder('deposit()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): void { + const self = (this as any) as WETH9Contract; + const abiEncoder = self._lookupAbiEncoder('deposit()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public allowance = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + index_0: string, + index_1: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('index_0', index_0); + assert.isString('index_1', index_1); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as WETH9Contract; + const encodedData = self._strictEncodeArguments('allowance(address,address)', [ + index_0.toLowerCase(), + index_1.toLowerCase(), + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('allowance(address,address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(index_0: string, index_1: string): string { + assert.isString('index_0', index_0); + assert.isString('index_1', index_1); + const self = (this as any) as WETH9Contract; + const abiEncodedTransactionData = self._strictEncodeArguments('allowance(address,address)', [ + index_0.toLowerCase(), + index_1.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): BigNumber { + const self = (this as any) as WETH9Contract; + const abiEncoder = self._lookupAbiEncoder('allowance(address,address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): BigNumber { + const self = (this as any) as WETH9Contract; + const abiEncoder = self._lookupAbiEncoder('allowance(address,address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + 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 WETH9Contract.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._applyDefaultsToTxDataAsync( + { 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(`WETH9 successfully deployed at ${txReceipt.contractAddress}`); + const contractInstance = new WETH9Contract( + 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: 'name', + outputs: [ + { + name: '', + type: 'string', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'guy', + type: 'address', + }, + { + name: 'wad', + type: 'uint256', + }, + ], + name: 'approve', + outputs: [ + { + name: '', + type: 'bool', + }, + ], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'totalSupply', + outputs: [ + { + name: '', + type: 'uint256', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'src', + type: 'address', + }, + { + name: 'dst', + type: 'address', + }, + { + name: 'wad', + type: 'uint256', + }, + ], + name: 'transferFrom', + outputs: [ + { + name: '', + type: 'bool', + }, + ], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'wad', + type: 'uint256', + }, + ], + name: 'withdraw', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'decimals', + outputs: [ + { + name: '', + type: 'uint8', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'index_0', + type: 'address', + }, + ], + name: 'balanceOf', + outputs: [ + { + name: '', + type: 'uint256', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'symbol', + outputs: [ + { + name: '', + type: 'string', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'dst', + type: 'address', + }, + { + name: 'wad', + type: 'uint256', + }, + ], + name: 'transfer', + outputs: [ + { + name: '', + type: 'bool', + }, + ], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [], + name: 'deposit', + outputs: [], + payable: true, + stateMutability: 'payable', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'index_0', + type: 'address', + }, + { + name: 'index_1', + type: 'address', + }, + ], + name: 'allowance', + outputs: [ + { + name: '', + type: 'uint256', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + inputs: [], + outputs: [], + payable: true, + stateMutability: 'payable', + type: 'fallback', + }, + { + anonymous: false, + inputs: [ + { + name: '_owner', + type: 'address', + indexed: true, + }, + { + name: '_spender', + type: 'address', + indexed: true, + }, + { + name: '_value', + type: 'uint256', + indexed: false, + }, + ], + name: 'Approval', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: '_from', + type: 'address', + indexed: true, + }, + { + name: '_to', + type: 'address', + indexed: true, + }, + { + name: '_value', + type: 'uint256', + indexed: false, + }, + ], + name: 'Transfer', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: '_owner', + type: 'address', + indexed: true, + }, + { + name: '_value', + type: 'uint256', + indexed: false, + }, + ], + name: 'Deposit', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: '_owner', + type: 'address', + indexed: true, + }, + { + name: '_value', + type: 'uint256', + indexed: false, + }, + ], + name: 'Withdrawal', + outputs: [], + type: 'event', + }, + ] as ContractAbi; + return abi; + } + /** + * Subscribe to an event type emitted by the WETH9 contract. + * @param eventName The WETH9 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: WETH9Events, + indexFilterValues: IndexedFilterValues, + callback: EventCallback, + isVerbose: boolean = false, + blockPollingIntervalMs?: number, + ): string { + assert.doesBelongToStringEnum('eventName', eventName, WETH9Events); + assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); + assert.isFunction('callback', callback); + const subscriptionToken = this._subscriptionManager.subscribe( + this.address, + eventName, + indexFilterValues, + WETH9Contract.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 WETH9 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: WETH9Events, + blockRange: BlockRange, + indexFilterValues: IndexedFilterValues, + ): Promise>> { + assert.doesBelongToStringEnum('eventName', eventName, WETH9Events); + assert.doesConformToSchema('blockRange', blockRange, schemas.blockRangeSchema); + assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); + const logs = await this._subscriptionManager.getLogsAsync( + this.address, + eventName, + blockRange, + indexFilterValues, + WETH9Contract.ABI(), + ); + return logs; + } + constructor( + address: string, + supportedProvider: SupportedProvider, + txDefaults?: Partial, + logDecodeDependencies?: { [contractName: string]: ContractAbi }, + ) { + super('WETH9', WETH9Contract.ABI(), address, supportedProvider, txDefaults, logDecodeDependencies); + classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + this._subscriptionManager = new SubscriptionManager( + WETH9Contract.ABI(), + this._web3Wrapper, + ); + } +} + +// 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/contract-wrappers/src/generated-wrappers/zrx_token.ts b/packages/contract-wrappers/src/generated-wrappers/zrx_token.ts new file mode 100644 index 0000000000..1ff3150abe --- /dev/null +++ b/packages/contract-wrappers/src/generated-wrappers/zrx_token.ts @@ -0,0 +1,1365 @@ +// tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma +// tslint:disable:whitespace no-unbound-method no-trailing-whitespace +// tslint:disable:no-unused-variable +import { + BaseContract, + BlockRange, + EventCallback, + IndexedFilterValues, + SubscriptionManager, + PromiseWithTransactionHash, +} from '@0x/base-contract'; +import { schemas } from '@0x/json-schemas'; +import { + BlockParam, + BlockParamLiteral, + CallData, + ContractAbi, + ContractArtifact, + DecodedLogArgs, + LogWithDecodedArgs, + MethodAbi, + TransactionReceiptWithDecodedLogs, + TxData, + TxDataPayable, + SupportedProvider, +} from 'ethereum-types'; +import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; +import { 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 ZRXTokenEventArgs = ZRXTokenTransferEventArgs | ZRXTokenApprovalEventArgs; + +export enum ZRXTokenEvents { + Transfer = 'Transfer', + Approval = 'Approval', +} + +export interface ZRXTokenTransferEventArgs extends DecodedLogArgs { + _from: string; + _to: string; + _value: BigNumber; +} + +export interface ZRXTokenApprovalEventArgs extends DecodedLogArgs { + _owner: string; + _spender: string; + _value: BigNumber; +} + +/* istanbul ignore next */ +// tslint:disable:no-parameter-reassignment +// tslint:disable-next-line:class-name +export class ZRXTokenContract extends BaseContract { + public name = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ZRXTokenContract; + const encodedData = self._strictEncodeArguments('name()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('name()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as ZRXTokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('name()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as ZRXTokenContract; + const abiEncoder = self._lookupAbiEncoder('name()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as ZRXTokenContract; + const abiEncoder = self._lookupAbiEncoder('name()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public approve = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + _spender: string, + _value: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_spender', _spender); + assert.isBigNumber('_value', _value); + const self = (this as any) as ZRXTokenContract; + const encodedData = self._strictEncodeArguments('approve(address,uint256)', [ + _spender.toLowerCase(), + _value, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.approve.estimateGasAsync.bind(self, _spender.toLowerCase(), _value), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + _spender: string, + _value: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('_spender', _spender); + assert.isBigNumber('_value', _value); + const self = (this as any) as ZRXTokenContract; + const txHashPromise = self.approve.sendTransactionAsync(_spender.toLowerCase(), _value, txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + _spender: string, + _value: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_spender', _spender); + assert.isBigNumber('_value', _value); + const self = (this as any) as ZRXTokenContract; + const encodedData = self._strictEncodeArguments('approve(address,uint256)', [ + _spender.toLowerCase(), + _value, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + _spender: string, + _value: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_spender', _spender); + assert.isBigNumber('_value', _value); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ZRXTokenContract; + const encodedData = self._strictEncodeArguments('approve(address,uint256)', [ + _spender.toLowerCase(), + _value, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('approve(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(_spender: string, _value: BigNumber): string { + assert.isString('_spender', _spender); + assert.isBigNumber('_value', _value); + const self = (this as any) as ZRXTokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('approve(address,uint256)', [ + _spender.toLowerCase(), + _value, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): boolean { + const self = (this as any) as ZRXTokenContract; + const abiEncoder = self._lookupAbiEncoder('approve(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): boolean { + const self = (this as any) as ZRXTokenContract; + const abiEncoder = self._lookupAbiEncoder('approve(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public totalSupply = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ZRXTokenContract; + const encodedData = self._strictEncodeArguments('totalSupply()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('totalSupply()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as ZRXTokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('totalSupply()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): BigNumber { + const self = (this as any) as ZRXTokenContract; + const abiEncoder = self._lookupAbiEncoder('totalSupply()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): BigNumber { + const self = (this as any) as ZRXTokenContract; + const abiEncoder = self._lookupAbiEncoder('totalSupply()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + /** + * ERC20 transferFrom, modified such that an allowance of MAX_UINT represents an unlimited allowance. + */ + public transferFrom = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param _from Address to transfer from. + * @param _to Address to transfer to. + * @param _value Amount to transfer. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + _from: string, + _to: string, + _value: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + const self = (this as any) as ZRXTokenContract; + const encodedData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _value, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.transferFrom.estimateGasAsync.bind(self, _from.toLowerCase(), _to.toLowerCase(), _value), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param _from Address to transfer from. + * @param _to Address to transfer to. + * @param _value Amount to transfer. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + _from: string, + _to: string, + _value: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + const self = (this as any) as ZRXTokenContract; + const txHashPromise = self.transferFrom.sendTransactionAsync( + _from.toLowerCase(), + _to.toLowerCase(), + _value, + txData, + ); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param _from Address to transfer from. + * @param _to Address to transfer to. + * @param _value Amount to transfer. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync( + _from: string, + _to: string, + _value: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + const self = (this as any) as ZRXTokenContract; + const encodedData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _value, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + * @param _from Address to transfer from. + * @param _to Address to transfer to. + * @param _value Amount to transfer. + * @returns Success of transfer. + */ + async callAsync( + _from: string, + _to: string, + _value: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ZRXTokenContract; + const encodedData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _value, + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + * @param _from Address to transfer from. + * @param _to Address to transfer to. + * @param _value Amount to transfer. + */ + getABIEncodedTransactionData(_from: string, _to: string, _value: BigNumber): string { + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + const self = (this as any) as ZRXTokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _value, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): boolean { + const self = (this as any) as ZRXTokenContract; + const abiEncoder = self._lookupAbiEncoder('transferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): boolean { + const self = (this as any) as ZRXTokenContract; + const abiEncoder = self._lookupAbiEncoder('transferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public decimals = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ZRXTokenContract; + const encodedData = self._strictEncodeArguments('decimals()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decimals()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as ZRXTokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('decimals()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): number { + const self = (this as any) as ZRXTokenContract; + const abiEncoder = self._lookupAbiEncoder('decimals()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): number { + const self = (this as any) as ZRXTokenContract; + const abiEncoder = self._lookupAbiEncoder('decimals()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public balanceOf = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + _owner: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_owner', _owner); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ZRXTokenContract; + const encodedData = self._strictEncodeArguments('balanceOf(address)', [_owner.toLowerCase()]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('balanceOf(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(_owner: string): string { + assert.isString('_owner', _owner); + const self = (this as any) as ZRXTokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('balanceOf(address)', [_owner.toLowerCase()]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): BigNumber { + const self = (this as any) as ZRXTokenContract; + const abiEncoder = self._lookupAbiEncoder('balanceOf(address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): BigNumber { + const self = (this as any) as ZRXTokenContract; + const abiEncoder = self._lookupAbiEncoder('balanceOf(address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public symbol = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ZRXTokenContract; + const encodedData = self._strictEncodeArguments('symbol()', []); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('symbol()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(): string { + const self = (this as any) as ZRXTokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('symbol()', []); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): string { + const self = (this as any) as ZRXTokenContract; + const abiEncoder = self._lookupAbiEncoder('symbol()'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): string { + const self = (this as any) as ZRXTokenContract; + const abiEncoder = self._lookupAbiEncoder('symbol()'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public transfer = { + /** + * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write + * Ethereum operation and will cost gas. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async sendTransactionAsync( + _to: string, + _value: BigNumber, + txData?: Partial | undefined, + ): Promise { + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + const self = (this as any) as ZRXTokenContract; + const encodedData = self._strictEncodeArguments('transfer(address,uint256)', [_to.toLowerCase(), _value]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + self.transfer.estimateGasAsync.bind(self, _to.toLowerCase(), _value), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + /** + * Sends an Ethereum transaction and waits until the transaction has been successfully mined without reverting. + * If the transaction was mined, but reverted, an error is thrown. + * @param txData Additional data for transaction + * @param pollingIntervalMs Interval at which to poll for success + * @returns A promise that resolves when the transaction is successful + */ + awaitTransactionSuccessAsync( + _to: string, + _value: BigNumber, + txData?: Partial, + pollingIntervalMs?: number, + timeoutMs?: number, + ): PromiseWithTransactionHash { + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + const self = (this as any) as ZRXTokenContract; + const txHashPromise = self.transfer.sendTransactionAsync(_to.toLowerCase(), _value, txData); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + pollingIntervalMs, + timeoutMs, + ); + })(), + ); + }, + /** + * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. + * @param txData Additional data for transaction + * @returns The hash of the transaction + */ + async estimateGasAsync(_to: string, _value: BigNumber, txData?: Partial | undefined): Promise { + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + const self = (this as any) as ZRXTokenContract; + const encodedData = self._strictEncodeArguments('transfer(address,uint256)', [_to.toLowerCase(), _value]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + _to: string, + _value: BigNumber, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ZRXTokenContract; + const encodedData = self._strictEncodeArguments('transfer(address,uint256)', [_to.toLowerCase(), _value]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transfer(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(_to: string, _value: BigNumber): string { + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + const self = (this as any) as ZRXTokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('transfer(address,uint256)', [ + _to.toLowerCase(), + _value, + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): boolean { + const self = (this as any) as ZRXTokenContract; + const abiEncoder = self._lookupAbiEncoder('transfer(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): boolean { + const self = (this as any) as ZRXTokenContract; + const abiEncoder = self._lookupAbiEncoder('transfer(address,uint256)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + public allowance = { + /** + * Sends a read-only call to the contract method. Returns the result that would happen if one were to send an + * Ethereum transaction to this method, given the current state of the blockchain. Calls do not cost gas + * since they don't modify state. + */ + async callAsync( + _owner: string, + _spender: string, + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise { + assert.isString('_owner', _owner); + assert.isString('_spender', _spender); + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const self = (this as any) as ZRXTokenContract; + const encodedData = self._strictEncodeArguments('allowance(address,address)', [ + _owner.toLowerCase(), + _spender.toLowerCase(), + ]); + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + BaseContract._throwIfRevertWithReasonCallResult(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('allowance(address,address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + /** + * Returns the ABI encoded transaction data needed to send an Ethereum transaction calling this method. Before + * sending the Ethereum tx, this encoded tx data can first be sent to a separate signing service or can be used + * to create a 0x transaction (see protocol spec for more details). + */ + getABIEncodedTransactionData(_owner: string, _spender: string): string { + assert.isString('_owner', _owner); + assert.isString('_spender', _spender); + const self = (this as any) as ZRXTokenContract; + const abiEncodedTransactionData = self._strictEncodeArguments('allowance(address,address)', [ + _owner.toLowerCase(), + _spender.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + getABIDecodedTransactionData(callData: string): BigNumber { + const self = (this as any) as ZRXTokenContract; + const abiEncoder = self._lookupAbiEncoder('allowance(address,address)'); + // tslint:disable boolean-naming + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + }, + getABIDecodedReturnData(returnData: string): BigNumber { + const self = (this as any) as ZRXTokenContract; + const abiEncoder = self._lookupAbiEncoder('allowance(address,address)'); + // tslint:disable boolean-naming + const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); + return abiDecodedReturnData; + }, + }; + 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 ZRXTokenContract.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._applyDefaultsToTxDataAsync( + { 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(`ZRXToken successfully deployed at ${txReceipt.contractAddress}`); + const contractInstance = new ZRXTokenContract( + 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: 'name', + outputs: [ + { + name: '', + type: 'string', + }, + ], + payable: false, + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: '_spender', + type: 'address', + }, + { + name: '_value', + type: 'uint256', + }, + ], + name: 'approve', + outputs: [ + { + name: '', + type: 'bool', + }, + ], + payable: false, + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'totalSupply', + outputs: [ + { + name: '', + type: 'uint256', + }, + ], + payable: false, + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: '_from', + type: 'address', + }, + { + name: '_to', + type: 'address', + }, + { + name: '_value', + type: 'uint256', + }, + ], + name: 'transferFrom', + outputs: [ + { + name: '', + type: 'bool', + }, + ], + payable: false, + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'decimals', + outputs: [ + { + name: '', + type: 'uint8', + }, + ], + payable: false, + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: '_owner', + type: 'address', + }, + ], + name: 'balanceOf', + outputs: [ + { + name: '', + type: 'uint256', + }, + ], + payable: false, + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'symbol', + outputs: [ + { + name: '', + type: 'string', + }, + ], + payable: false, + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: '_to', + type: 'address', + }, + { + name: '_value', + type: 'uint256', + }, + ], + name: 'transfer', + outputs: [ + { + name: '', + type: 'bool', + }, + ], + payable: false, + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: '_owner', + type: 'address', + }, + { + name: '_spender', + type: 'address', + }, + ], + name: 'allowance', + outputs: [ + { + name: '', + type: 'uint256', + }, + ], + payable: false, + type: 'function', + }, + { + inputs: [], + outputs: [], + payable: false, + type: 'constructor', + }, + { + anonymous: false, + inputs: [ + { + name: '_from', + type: 'address', + indexed: true, + }, + { + name: '_to', + type: 'address', + indexed: true, + }, + { + name: '_value', + type: 'uint256', + indexed: false, + }, + ], + name: 'Transfer', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: '_owner', + type: 'address', + indexed: true, + }, + { + name: '_spender', + type: 'address', + indexed: true, + }, + { + name: '_value', + type: 'uint256', + indexed: false, + }, + ], + name: 'Approval', + outputs: [], + type: 'event', + }, + ] as ContractAbi; + return abi; + } + /** + * Subscribe to an event type emitted by the ZRXToken contract. + * @param eventName The ZRXToken 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: ZRXTokenEvents, + indexFilterValues: IndexedFilterValues, + callback: EventCallback, + isVerbose: boolean = false, + blockPollingIntervalMs?: number, + ): string { + assert.doesBelongToStringEnum('eventName', eventName, ZRXTokenEvents); + assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); + assert.isFunction('callback', callback); + const subscriptionToken = this._subscriptionManager.subscribe( + this.address, + eventName, + indexFilterValues, + ZRXTokenContract.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 ZRXToken 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: ZRXTokenEvents, + blockRange: BlockRange, + indexFilterValues: IndexedFilterValues, + ): Promise>> { + assert.doesBelongToStringEnum('eventName', eventName, ZRXTokenEvents); + assert.doesConformToSchema('blockRange', blockRange, schemas.blockRangeSchema); + assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); + const logs = await this._subscriptionManager.getLogsAsync( + this.address, + eventName, + blockRange, + indexFilterValues, + ZRXTokenContract.ABI(), + ); + return logs; + } + constructor( + address: string, + supportedProvider: SupportedProvider, + txDefaults?: Partial, + logDecodeDependencies?: { [contractName: string]: ContractAbi }, + ) { + super('ZRXToken', ZRXTokenContract.ABI(), address, supportedProvider, txDefaults, logDecodeDependencies); + classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + this._subscriptionManager = new SubscriptionManager( + ZRXTokenContract.ABI(), + this._web3Wrapper, + ); + } +} + +// 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/contract-wrappers/src/index.ts b/packages/contract-wrappers/src/index.ts index 2c9f869392..7ab661f92f 100644 --- a/packages/contract-wrappers/src/index.ts +++ b/packages/contract-wrappers/src/index.ts @@ -1,124 +1,26 @@ -export { ContractAddresses } from '@0x/contract-addresses'; - -export { - WETH9Events, - WETH9WithdrawalEventArgs, - WETH9ApprovalEventArgs, - WETH9EventArgs, - WETH9DepositEventArgs, - WETH9TransferEventArgs, - ERC20TokenTransferEventArgs, - ERC20TokenApprovalEventArgs, - ERC20TokenEvents, - ERC20TokenEventArgs, - ERC721TokenApprovalEventArgs, - ERC721TokenApprovalForAllEventArgs, - ERC721TokenTransferEventArgs, - ERC721TokenEvents, - ERC721TokenEventArgs, - ExchangeCancelUpToEventArgs, - ExchangeAssetProxyRegisteredEventArgs, - ExchangeSignatureValidatorApprovalEventArgs, - ExchangeFillEventArgs, - ExchangeCancelEventArgs, - ExchangeEventArgs, - ExchangeEvents, -} from '@0x/abi-gen-wrappers'; +export * from './generated-wrappers/asset_proxy_owner'; +export * from './generated-wrappers/dummy_erc20_token'; +export * from './generated-wrappers/dummy_erc721_token'; +export * from './generated-wrappers/dutch_auction'; +export * from './generated-wrappers/erc20_proxy'; +export * from './generated-wrappers/erc20_token'; +export * from './generated-wrappers/erc721_proxy'; +export * from './generated-wrappers/erc721_token'; +export * from './generated-wrappers/exchange'; +export * from './generated-wrappers/forwarder'; +export * from './generated-wrappers/i_asset_proxy'; +export * from './generated-wrappers/i_validator'; +export * from './generated-wrappers/i_wallet'; +export * from './generated-wrappers/multi_asset_proxy'; +export * from './generated-wrappers/order_validator'; +export * from './generated-wrappers/weth9'; +export * from './generated-wrappers/zrx_token'; +export * from './generated-wrappers/coordinator'; +export * from './generated-wrappers/coordinator_registry'; +export * from './generated-wrappers/eth_balance_checker'; + +export * from '@0x/contract-addresses'; export { ContractWrappers } from './contract_wrappers'; -export { CoordinatorWrapper } from './contract_wrappers/coordinator_wrapper'; -export { ERC20TokenWrapper } from './contract_wrappers/erc20_token_wrapper'; -export { ERC721TokenWrapper } from './contract_wrappers/erc721_token_wrapper'; -export { EtherTokenWrapper } from './contract_wrappers/ether_token_wrapper'; -export { ExchangeWrapper } from './contract_wrappers/exchange_wrapper'; -export { ERC20ProxyWrapper } from './contract_wrappers/erc20_proxy_wrapper'; -export { ERC721ProxyWrapper } from './contract_wrappers/erc721_proxy_wrapper'; -export { ForwarderWrapper } from './contract_wrappers/forwarder_wrapper'; -export { OrderValidatorWrapper } from './contract_wrappers/order_validator_wrapper'; -export { DutchAuctionWrapper } from './contract_wrappers/dutch_auction_wrapper'; - -export { TransactionEncoder } from './utils/transaction_encoder'; - -export { AbiDecoder, DecodedCalldata } from '@0x/utils'; - -export { - ContractWrappersError, - ForwarderWrapperError, - IndexedFilterValues, - BlockRange, - ContractWrappersConfig, - MethodOpts, - OrderTransactionOpts, - TransactionOpts, - OrderStatus, - OrderInfo, - EventCallback, - DecodedLogEvent, - BalanceAndAllowance, - OrderAndTraderInfo, - TraderInfo, - ValidateOrderFillableOpts, - CoordinatorServerCancellationResponse, - CoordinatorServerError, -} from './types'; - -export { - AssetData, - ERC20AssetData, - ERC721AssetData, - ERC1155AssetData, - SingleAssetData, - MultiAssetData, - StaticCallAssetData, - MultiAssetDataWithRecursiveDecoding, - DutchAuctionDetails, - DutchAuctionData, - Order, - SignedOrder, - AssetProxyId, - SignedZeroExTransaction, - ZeroExTransaction, -} from '@0x/types'; - -export { - BlockParamLiteral, - BlockParam, - ContractEventArg, - SupportedProvider, - ContractAbi, - JSONRPCRequestPayload, - JSONRPCResponsePayload, - JSONRPCErrorCallback, - JSONRPCResponseError, - AbiDefinition, - LogWithDecodedArgs, - LogEntry, - DecodedLogEntry, - DecodedLogEntryEvent, - LogEntryEvent, - RawLog, - FunctionAbi, - EventAbi, - EventParameter, - DecodedLogArgs, - MethodAbi, - ConstructorAbi, - FallbackAbi, - DataItem, - TupleDataItem, - ConstructorStateMutability, - StateMutability, - Web3JsProvider, - GanacheProvider, - EIP1193Provider, - ZeroExProvider, - EIP1193Event, - Web3JsV1Provider, - Web3JsV2Provider, - Web3JsV3Provider, -} from 'ethereum-types'; - -export { AbstractBalanceAndProxyAllowanceFetcher, AbstractOrderFilledCancelledFetcher } from '@0x/order-utils'; - -export { AssetBalanceAndProxyAllowanceFetcher } from './fetchers/asset_balance_and_proxy_allowance_fetcher'; -export { OrderFilledCancelledFetcher } from './fetchers/order_filled_cancelled_fetcher'; +export { CoordinatorWrapper } from './coordinator_wrapper'; +export { OrderStatus } from './types'; diff --git a/packages/contract-wrappers/src/schemas/method_opts_schema.ts b/packages/contract-wrappers/src/schemas/method_opts_schema.ts deleted file mode 100644 index 83003f8188..0000000000 --- a/packages/contract-wrappers/src/schemas/method_opts_schema.ts +++ /dev/null @@ -1,7 +0,0 @@ -export const methodOptsSchema = { - id: '/MethodOpts', - properties: { - defaultBlock: { $ref: '/blockParamSchema' }, - }, - type: 'object', -}; diff --git a/packages/contract-wrappers/src/schemas/validate_order_fillable_opts_schema.ts b/packages/contract-wrappers/src/schemas/validate_order_fillable_opts_schema.ts deleted file mode 100644 index 2e111af04c..0000000000 --- a/packages/contract-wrappers/src/schemas/validate_order_fillable_opts_schema.ts +++ /dev/null @@ -1,7 +0,0 @@ -export const validateOrderFillableOptsSchema = { - id: '/ValidateOrderFillableOpts', - properties: { - expectedFillTakerTokenAmount: { $ref: '/wholeNumberSchema' }, - }, - type: 'object', -}; diff --git a/packages/contract-wrappers/src/types.ts b/packages/contract-wrappers/src/types.ts index de190c62d1..55f2d9ea29 100644 --- a/packages/contract-wrappers/src/types.ts +++ b/packages/contract-wrappers/src/types.ts @@ -1,47 +1,8 @@ -import { - ERC20TokenEventArgs, - ERC20TokenEvents, - ERC721TokenEventArgs, - ERC721TokenEvents, - ExchangeEventArgs, - ExchangeEvents, - WETH9EventArgs, - WETH9Events, -} from '@0x/abi-gen-wrappers'; import { ContractAddresses } from '@0x/contract-addresses'; -import { OrderState, SignedOrder } from '@0x/types'; import { BigNumber } from '@0x/utils'; -import { BlockParam, ContractEventArg, DecodedLogArgs, LogEntryEvent, LogWithDecodedArgs } from 'ethereum-types'; +import { ContractEventArg, DecodedLogArgs, LogWithDecodedArgs } from 'ethereum-types'; -export enum ExchangeWrapperError { - AssetDataMismatch = 'ASSET_DATA_MISMATCH', -} - -export enum ForwarderWrapperError { - CompleteFillFailed = 'COMPLETE_FILL_FAILED', -} - -export enum ContractWrappersError { - ContractNotDeployedOnNetwork = 'CONTRACT_NOT_DEPLOYED_ON_NETWORK', - InsufficientAllowanceForTransfer = 'INSUFFICIENT_ALLOWANCE_FOR_TRANSFER', - InsufficientBalanceForTransfer = 'INSUFFICIENT_BALANCE_FOR_TRANSFER', - InsufficientEthBalanceForDeposit = 'INSUFFICIENT_ETH_BALANCE_FOR_DEPOSIT', - InsufficientWEthBalanceForWithdrawal = 'INSUFFICIENT_WETH_BALANCE_FOR_WITHDRAWAL', - InvalidJump = 'INVALID_JUMP', - OutOfGas = 'OUT_OF_GAS', - SubscriptionNotFound = 'SUBSCRIPTION_NOT_FOUND', - SubscriptionAlreadyPresent = 'SUBSCRIPTION_ALREADY_PRESENT', - ERC721OwnerNotFound = 'ERC_721_OWNER_NOT_FOUND', - ERC721NoApproval = 'ERC_721_NO_APPROVAL', - SignatureRequestDenied = 'SIGNATURE_REQUEST_DENIED', -} - -export enum InternalContractWrappersError { - NoAbiDecoder = 'NO_ABI_DECODER', -} - -export type LogEvent = LogEntryEvent; export interface DecodedLogEvent { isRemoved: boolean; log: LogWithDecodedArgs; @@ -52,30 +13,6 @@ export type EventCallback = ( log?: DecodedLogEvent, ) => void; -export interface ContractEvent { - logIndex: number; - transactionIndex: number; - transactionHash: string; - blockHash: string; - blockNumber: number; - address: string; - type: string; - event: string; - args: ContractEventArgs; -} - -export type ContractEventArgs = ExchangeEventArgs | ERC20TokenEventArgs | ERC721TokenEventArgs | WETH9EventArgs; - -// [address, name, symbol, decimals, ipfsHash, swarmHash] -export type TokenMetadata = [string, string, string, number, string, string]; - -export interface Token { - name: string; - address: string; - symbol: string; - decimals: number; -} - export interface TxOpts { from: string; gas?: number; @@ -83,29 +20,10 @@ export interface TxOpts { gasPrice?: BigNumber; } -export interface TokenAddressBySymbol { - [symbol: string]: string; -} - -export type ContractEvents = ERC20TokenEvents | ERC721TokenEvents | ExchangeEvents | WETH9Events; - export interface IndexedFilterValues { [index: string]: ContractEventArg; } -export interface BlockRange { - fromBlock: BlockParam; - toBlock: BlockParam; -} - -export interface OrderFillRequest { - signedOrder: SignedOrder; - takerAssetFillAmount: BigNumber; -} - -export type AsyncMethod = (...args: any[]) => Promise; -export type SyncMethod = (...args: any[]) => any; - /** * networkId: The id of the underlying ethereum network your provider is connected to. (1-mainnet, 3-ropsten, 4-rinkeby, 42-kovan, 50-testrpc) * gasPrice: Gas price to use with every transaction @@ -119,35 +37,6 @@ export interface ContractWrappersConfig { blockPollingIntervalMs?: number; } -/** - * `expectedFillTakerTokenAmount`: If specified, the validation method will ensure that the supplied order maker has a sufficient - * allowance/balance to fill this amount of the order's takerTokenAmount. - * - * `validateRemainingOrderAmountIsFillable`: The validation method ensures that the maker has sufficient allowance/balance to fill - * the entire remaining order amount. If this option is set to false, the balances - * and allowances are calculated to determine the order is fillable for a - * non-zero amount (some value less than or equal to the order remaining amount). - * We call such orders "partially fillable orders". Default is `true`. - * - * `simulationTakerAddress`: During the maker transfer simulation, tokens are sent from the maker to the `simulationTakerAddress`. This defaults - * to the `takerAddress` specified in the order. Some tokens prevent transfer to the NULL address so this address can be specified. - */ -export interface ValidateOrderFillableOpts { - expectedFillTakerTokenAmount?: BigNumber; - validateRemainingOrderAmountIsFillable?: boolean; - simulationTakerAddress?: string; -} - -/** - * defaultBlock: The block up to which to query the blockchain state. Setting this to a historical block number - * let's the user query the blockchain's state at an arbitrary point in time. In order for this to work, the - * backing Ethereum node must keep the entire historical state of the chain (e.g setting `--pruning=archive` - * flag when running Parity). - */ -export interface MethodOpts { - defaultBlock?: BlockParam; -} - /** * gasPrice: Gas price in Wei to use for a transaction * gasLimit: The amount of gas to send with a transaction (in Gwei) @@ -167,18 +56,6 @@ export interface OrderTransactionOpts extends TransactionOpts { shouldValidate?: boolean; } -export enum TradeSide { - Maker = 'maker', - Taker = 'taker', -} - -export enum TransferType { - Trade = 'trade', - Fee = 'fee', -} - -export type OnOrderStateChangeCallback = (err: Error | null, orderState?: OrderState) => void; - export interface OrderInfo { orderStatus: OrderStatus; orderHash: string; @@ -195,31 +72,6 @@ export enum OrderStatus { Cancelled, } -export interface TraderInfo { - makerBalance: BigNumber; - makerAllowance: BigNumber; - takerBalance: BigNumber; - takerAllowance: BigNumber; - makerZrxBalance: BigNumber; - makerZrxAllowance: BigNumber; - takerZrxBalance: BigNumber; - takerZrxAllowance: BigNumber; -} - -export interface OrderAndTraderInfo { - orderInfo: OrderInfo; - traderInfo: TraderInfo; -} - -export interface BalanceAndAllowance { - balance: BigNumber; - allowance: BigNumber; -} - -export enum DutchAuctionWrapperError { - AssetDataMismatch = 'ASSET_DATA_MISMATCH', -} - export { CoordinatorServerCancellationResponse, CoordinatorServerError } from './utils/coordinator_server_types'; export interface CoordinatorTransaction { diff --git a/packages/contract-wrappers/src/utils/assert.ts b/packages/contract-wrappers/src/utils/assert.ts index c4214542c6..1f1c8201a5 100644 --- a/packages/contract-wrappers/src/utils/assert.ts +++ b/packages/contract-wrappers/src/utils/assert.ts @@ -8,7 +8,7 @@ import { Web3Wrapper } from '@0x/web3-wrapper'; import { SupportedProvider } from 'ethereum-types'; import * as _ from 'lodash'; -import { constants } from './constants'; +const NULL_ADDRESS = '0x0000000000000000000000000000000000000000'; export const assert = { ...sharedAssert, @@ -56,7 +56,7 @@ export const assert = { } }, allTakerAddressesAreNull(orders: Order[]): void { - assert.ordersHaveAtMostOneUniqueValueForProperty(orders, 'takerAddress', constants.NULL_ADDRESS); + assert.ordersHaveAtMostOneUniqueValueForProperty(orders, 'takerAddress', NULL_ADDRESS); }, allMakerAssetDatasAreErc20Token(orders: Order[], tokenAddress: string): void { assert.ordersHaveAtMostOneUniqueValueForProperty( diff --git a/packages/contract-wrappers/src/utils/calldata_optimization_utils.ts b/packages/contract-wrappers/src/utils/calldata_optimization_utils.ts deleted file mode 100644 index bee7acaa7c..0000000000 --- a/packages/contract-wrappers/src/utils/calldata_optimization_utils.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { SignedOrder } from '@0x/types'; -import * as _ from 'lodash'; - -import { constants } from './constants'; - -export const calldataOptimizationUtils = { - /** - * Takes an array of orders and outputs an array of equivalent orders where all takerAssetData are '0x' and - * all makerAssetData are '0x' except for that of the first order, which retains its original value - * @param orders An array of SignedOrder objects - * @returns optimized orders - */ - optimizeForwarderOrders(orders: SignedOrder[]): SignedOrder[] { - const optimizedOrders = _.map(orders, (order, index) => - transformOrder(order, { - makerAssetData: index === 0 ? order.makerAssetData : constants.NULL_BYTES, - takerAssetData: constants.NULL_BYTES, - }), - ); - return optimizedOrders; - }, - /** - * Takes an array of orders and outputs an array of equivalent orders where all takerAssetData are '0x' and - * all makerAssetData are '0x' - * @param orders An array of SignedOrder objects - * @returns optimized orders - */ - optimizeForwarderFeeOrders(orders: SignedOrder[]): SignedOrder[] { - const optimizedOrders = _.map(orders, (order, index) => - transformOrder(order, { - makerAssetData: constants.NULL_BYTES, - takerAssetData: constants.NULL_BYTES, - }), - ); - return optimizedOrders; - }, -}; - -const transformOrder = (order: SignedOrder, partialOrder: Partial) => { - return { - ...order, - ...partialOrder, - }; -}; diff --git a/packages/contract-wrappers/src/utils/constants.ts b/packages/contract-wrappers/src/utils/constants.ts deleted file mode 100644 index 94afdc1127..0000000000 --- a/packages/contract-wrappers/src/utils/constants.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { BigNumber } from '@0x/utils'; - -export const constants = { - NULL_ADDRESS: '0x0000000000000000000000000000000000000000', - NULL_BYTES: '0x', - TESTRPC_NETWORK_ID: 50, - INVALID_JUMP_PATTERN: 'invalid JUMP at', - REVERT: 'revert', - OUT_OF_GAS_PATTERN: 'out of gas', - INVALID_TAKER_FORMAT: 'instance.taker is not of a type(s) string', - // tslint:disable-next-line:custom-no-magic-numbers - UNLIMITED_ALLOWANCE_IN_BASE_UNITS: new BigNumber(2).pow(256).minus(1), - DEFAULT_BLOCK_POLLING_INTERVAL: 1000, - ZERO_AMOUNT: new BigNumber(0), - ONE_AMOUNT: new BigNumber(1), - ETHER_TOKEN_DECIMALS: 18, - METAMASK_USER_DENIED_SIGNATURE_PATTERN: 'User denied transaction signature', - TRUST_WALLET_USER_DENIED_SIGNATURE_PATTERN: 'cancelled', -}; diff --git a/packages/contract-wrappers/src/utils/decorators.ts b/packages/contract-wrappers/src/utils/decorators.ts index 3acfa3a886..b1cad0a235 100644 --- a/packages/contract-wrappers/src/utils/decorators.ts +++ b/packages/contract-wrappers/src/utils/decorators.ts @@ -1,8 +1,31 @@ import * as _ from 'lodash'; -import { AsyncMethod, ContractWrappersError, SyncMethod } from '../types'; - -import { constants } from './constants'; +export enum ContractWrappersError { + ContractNotDeployedOnNetwork = 'CONTRACT_NOT_DEPLOYED_ON_NETWORK', + InsufficientAllowanceForTransfer = 'INSUFFICIENT_ALLOWANCE_FOR_TRANSFER', + InsufficientBalanceForTransfer = 'INSUFFICIENT_BALANCE_FOR_TRANSFER', + InsufficientEthBalanceForDeposit = 'INSUFFICIENT_ETH_BALANCE_FOR_DEPOSIT', + InsufficientWEthBalanceForWithdrawal = 'INSUFFICIENT_WETH_BALANCE_FOR_WITHDRAWAL', + InvalidJump = 'INVALID_JUMP', + OutOfGas = 'OUT_OF_GAS', + SubscriptionNotFound = 'SUBSCRIPTION_NOT_FOUND', + SubscriptionAlreadyPresent = 'SUBSCRIPTION_ALREADY_PRESENT', + ERC721OwnerNotFound = 'ERC_721_OWNER_NOT_FOUND', + ERC721NoApproval = 'ERC_721_NO_APPROVAL', + SignatureRequestDenied = 'SIGNATURE_REQUEST_DENIED', +} + +export type AsyncMethod = (...args: any[]) => Promise; +export type SyncMethod = (...args: any[]) => any; + +const constants = { + INVALID_JUMP_PATTERN: 'invalid JUMP at', + REVERT: 'revert', + OUT_OF_GAS_PATTERN: 'out of gas', + INVALID_TAKER_FORMAT: 'instance.taker is not of a type(s) string', + METAMASK_USER_DENIED_SIGNATURE_PATTERN: 'User denied transaction signature', + TRUST_WALLET_USER_DENIED_SIGNATURE_PATTERN: 'cancelled', +}; type ErrorTransformer = (err: Error) => Error; diff --git a/packages/contract-wrappers/src/utils/filter_utils.ts b/packages/contract-wrappers/src/utils/filter_utils.ts deleted file mode 100644 index f16c1975bc..0000000000 --- a/packages/contract-wrappers/src/utils/filter_utils.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { ContractAbi, EventAbi, FilterObject, LogEntry } from 'ethereum-types'; -import * as ethUtil from 'ethereumjs-util'; -import * as jsSHA3 from 'js-sha3'; -import * as _ from 'lodash'; -import * as uuid from 'uuid/v4'; - -import { BlockRange, ContractEvents, IndexedFilterValues } from '../types'; - -const TOPIC_LENGTH = 32; - -export const filterUtils = { - generateUUID(): string { - return uuid(); - }, - getFilter( - address: string, - eventName: ContractEvents, - indexFilterValues: IndexedFilterValues, - abi: ContractAbi, - blockRange?: BlockRange, - ): FilterObject { - const eventAbi = _.find(abi, { 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 = _.map(eventAbi.inputs, '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 { - const value = indexFilterValues[eventInput.name] as string; - 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 = _.zipWith(logTopics, filterTopics, filterUtils.matchesTopic.bind(filterUtils)); - const doesMatchTopics = _.every(matchesTopic); - return doesMatchTopics; - }, - matchesTopic(logTopic: string, filterTopic: string[] | string | null): boolean { - if (_.isArray(filterTopic)) { - return _.includes(filterTopic, logTopic); - } - if (_.isString(filterTopic)) { - return filterTopic === logTopic; - } - // null topic is a wildcard - return true; - }, -}; diff --git a/packages/contract-wrappers/src/utils/getAbiEncodedTransactionData.ts b/packages/contract-wrappers/src/utils/getAbiEncodedTransactionData.ts new file mode 100644 index 0000000000..5ef476d49f --- /dev/null +++ b/packages/contract-wrappers/src/utils/getAbiEncodedTransactionData.ts @@ -0,0 +1,24 @@ +import { ExchangeContract } from '../index'; + +/** + * Returns the ABI encoded transaction hash for a given method and arguments + * @param methodName Must be a valid name of a function in the Solidity Exchange Contract + * @param params The appropriate arguments for the method given, in order + */ +export function getAbiEncodedTransactionData( + contractInstance: ExchangeContract, + methodName: K, + ...params: any[] // tslint:disable-line:trailing-comma +): string { + // HACK (xianny): we haven't formalised contract method functions into a type interface, and would have to + // differentiate contract method members from other class members to get this to work non-hackily + const method = (contractInstance[methodName] as any) as { + getABIEncodedTransactionData: (...args: any[]) => string; + }; + if (method.getABIEncodedTransactionData) { + const abiEncodedData = method.getABIEncodedTransactionData(...params); + return abiEncodedData; + } else { + return ''; + } +} diff --git a/packages/contract-wrappers/src/utils/transaction_encoder.ts b/packages/contract-wrappers/src/utils/transaction_encoder.ts deleted file mode 100644 index 0832ee73a9..0000000000 --- a/packages/contract-wrappers/src/utils/transaction_encoder.ts +++ /dev/null @@ -1,297 +0,0 @@ -import { ExchangeContract } from '@0x/abi-gen-wrappers'; - -import { schemas } from '@0x/json-schemas'; -import { transactionHashUtils } from '@0x/order-utils'; -import { Order, SignedOrder } from '@0x/types'; -import { BigNumber } from '@0x/utils'; -import _ = require('lodash'); - -import { assert } from './assert'; - -/** - * Transaction Encoder. Transaction messages exist for the purpose of calling methods on the Exchange contract - * in the context of another address. For example, UserA can encode and sign a fillOrder transaction and UserB - * can submit this to the blockchain. The Exchange context executes as if UserA had directly submitted this transaction. - */ -export class TransactionEncoder { - private readonly _exchangeInstance: ExchangeContract; - constructor(exchangeInstance: ExchangeContract) { - this._exchangeInstance = exchangeInstance; - } - /** - * Hashes the transaction data for use with the Exchange contract. - * @param data The ABI Encoded 0x Exchange method. I.e fillOrder - * @param salt A random value to provide uniqueness and prevent replay attacks. - * @param signerAddress The address which will sign this transaction. - * @return The hash of the 0x transaction. - */ - public getTransactionHashHex(data: string, salt: BigNumber, signerAddress: string): string { - const exchangeAddress = this._getExchangeContract().address; - const transaction = { - verifyingContractAddress: exchangeAddress, - salt, - signerAddress, - data, - }; - const hashHex = transactionHashUtils.getTransactionHashHex(transaction); - return hashHex; - } - /** - * Encodes a fillOrder transaction. - * @param signedOrder An object that conforms to the SignedOrder interface. - * @param takerAssetFillAmount The amount of the order (in taker asset baseUnits) that you wish to fill. - * @return Hex encoded abi of the function call. - */ - public fillOrderTx(signedOrder: SignedOrder, takerAssetFillAmount: BigNumber): string { - assert.doesConformToSchema('signedOrder', signedOrder, schemas.signedOrderSchema); - assert.isValidBaseUnitAmount('takerAssetFillAmount', takerAssetFillAmount); - const abiEncodedData = this._getExchangeContract().fillOrder.getABIEncodedTransactionData( - signedOrder, - takerAssetFillAmount, - signedOrder.signature, - ); - return abiEncodedData; - } - /** - * Encodes a fillOrderNoThrow transaction. - * @param signedOrder An object that conforms to the SignedOrder interface. - * @param takerAssetFillAmount The amount of the order (in taker asset baseUnits) that you wish to fill. - * @return Hex encoded abi of the function call. - */ - public fillOrderNoThrowTx(signedOrder: SignedOrder, takerAssetFillAmount: BigNumber): string { - assert.doesConformToSchema('signedOrder', signedOrder, schemas.signedOrderSchema); - assert.isValidBaseUnitAmount('takerAssetFillAmount', takerAssetFillAmount); - const abiEncodedData = this._getExchangeContract().fillOrderNoThrow.getABIEncodedTransactionData( - signedOrder, - takerAssetFillAmount, - signedOrder.signature, - ); - return abiEncodedData; - } - /** - * Encodes a fillOrKillOrder transaction. - * @param signedOrder An object that conforms to the SignedOrder interface. - * @param takerAssetFillAmount The amount of the order (in taker asset baseUnits) that you wish to fill. - * @return Hex encoded abi of the function call. - */ - public fillOrKillOrderTx(signedOrder: SignedOrder, takerAssetFillAmount: BigNumber): string { - assert.doesConformToSchema('signedOrder', signedOrder, schemas.signedOrderSchema); - assert.isValidBaseUnitAmount('takerAssetFillAmount', takerAssetFillAmount); - const abiEncodedData = this._getExchangeContract().fillOrKillOrder.getABIEncodedTransactionData( - signedOrder, - takerAssetFillAmount, - signedOrder.signature, - ); - return abiEncodedData; - } - /** - * Encodes a batchFillOrders transaction. - * @param signedOrders An array of signed orders to fill. - * @param takerAssetFillAmounts The amounts of the orders (in taker asset baseUnits) that you wish to fill. - * @return Hex encoded abi of the function call. - */ - public batchFillOrdersTx(signedOrders: SignedOrder[], takerAssetFillAmounts: BigNumber[]): string { - assert.doesConformToSchema('signedOrders', signedOrders, schemas.signedOrdersSchema); - _.forEach(takerAssetFillAmounts, takerAssetFillAmount => - assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount), - ); - const signatures = _.map(signedOrders, signedOrder => signedOrder.signature); - const abiEncodedData = this._getExchangeContract().batchFillOrders.getABIEncodedTransactionData( - signedOrders, - takerAssetFillAmounts, - signatures, - ); - return abiEncodedData; - } - /** - * Encodes a batchFillOrKillOrders transaction. - * @param signedOrders An array of signed orders to fill. - * @param takerAssetFillAmounts The amounts of the orders (in taker asset baseUnits) that you wish to fill. - * @return Hex encoded abi of the function call. - */ - public batchFillOrKillOrdersTx(signedOrders: SignedOrder[], takerAssetFillAmounts: BigNumber[]): string { - assert.doesConformToSchema('signedOrders', signedOrders, schemas.signedOrdersSchema); - _.forEach(takerAssetFillAmounts, takerAssetFillAmount => - assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount), - ); - const signatures = _.map(signedOrders, signedOrder => signedOrder.signature); - const abiEncodedData = this._getExchangeContract().batchFillOrKillOrders.getABIEncodedTransactionData( - signedOrders, - takerAssetFillAmounts, - signatures, - ); - return abiEncodedData; - } - /** - * Encodes a batchFillOrdersNoThrow transaction. - * @param signedOrders An array of signed orders to fill. - * @param takerAssetFillAmounts The amounts of the orders (in taker asset baseUnits) that you wish to fill. - * @return Hex encoded abi of the function call. - */ - public batchFillOrdersNoThrowTx(signedOrders: SignedOrder[], takerAssetFillAmounts: BigNumber[]): string { - assert.doesConformToSchema('signedOrders', signedOrders, schemas.signedOrdersSchema); - _.forEach(takerAssetFillAmounts, takerAssetFillAmount => - assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount), - ); - const signatures = _.map(signedOrders, signedOrder => signedOrder.signature); - const abiEncodedData = this._getExchangeContract().batchFillOrdersNoThrow.getABIEncodedTransactionData( - signedOrders, - takerAssetFillAmounts, - signatures, - ); - return abiEncodedData; - } - /** - * Encodes a batchCancelOrders transaction. - * @param signedOrders An array of orders to cancel. - * @return Hex encoded abi of the function call. - */ - public batchCancelOrdersTx(signedOrders: SignedOrder[]): string { - assert.doesConformToSchema('signedOrders', signedOrders, schemas.signedOrdersSchema); - const abiEncodedData = this._getExchangeContract().batchCancelOrders.getABIEncodedTransactionData(signedOrders); - return abiEncodedData; - } - /** - * Encodes a cancelOrdersUpTo transaction. - * @param targetOrderEpoch Target order epoch. - * @return Hex encoded abi of the function call. - */ - public cancelOrdersUpToTx(targetOrderEpoch: BigNumber): string { - assert.isBigNumber('targetOrderEpoch', targetOrderEpoch); - const abiEncodedData = this._getExchangeContract().cancelOrdersUpTo.getABIEncodedTransactionData( - targetOrderEpoch, - ); - return abiEncodedData; - } - /** - * Encodes a cancelOrder transaction. - * @param order An object that conforms to the Order or SignedOrder interface. The order you would like to cancel. - * @return Hex encoded abi of the function call. - */ - public cancelOrderTx(order: Order | SignedOrder): string { - assert.doesConformToSchema('order', order, schemas.orderSchema); - const abiEncodedData = this._getExchangeContract().cancelOrder.getABIEncodedTransactionData(order); - return abiEncodedData; - } - /** - * Encodes a marketSellOrders transaction. - * @param signedOrders An array of signed orders to fill. - * @param takerAssetFillAmount Taker asset fill amount. - * @return Hex encoded abi of the function call. - */ - public marketSellOrdersTx(signedOrders: SignedOrder[], takerAssetFillAmount: BigNumber): string { - assert.doesConformToSchema('signedOrders', signedOrders, schemas.signedOrdersSchema); - assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); - const signatures = _.map(signedOrders, signedOrder => signedOrder.signature); - const abiEncodedData = this._getExchangeContract().marketSellOrders.getABIEncodedTransactionData( - signedOrders, - takerAssetFillAmount, - signatures, - ); - return abiEncodedData; - } - /** - * Encodes a marketSellOrdersNoThrow transaction. - * @param signedOrders An array of signed orders to fill. - * @param takerAssetFillAmount Taker asset fill amount. - * @return Hex encoded abi of the function call. - */ - public marketSellOrdersNoThrowTx(signedOrders: SignedOrder[], takerAssetFillAmount: BigNumber): string { - assert.doesConformToSchema('signedOrders', signedOrders, schemas.signedOrdersSchema); - assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); - const signatures = _.map(signedOrders, signedOrder => signedOrder.signature); - const abiEncodedData = this._getExchangeContract().marketSellOrdersNoThrow.getABIEncodedTransactionData( - signedOrders, - takerAssetFillAmount, - signatures, - ); - return abiEncodedData; - } - /** - * Encodes a maketBuyOrders transaction. - * @param signedOrders An array of signed orders to fill. - * @param makerAssetFillAmount Maker asset fill amount. - * @return Hex encoded abi of the function call. - */ - public marketBuyOrdersTx(signedOrders: SignedOrder[], makerAssetFillAmount: BigNumber): string { - assert.doesConformToSchema('signedOrders', signedOrders, schemas.signedOrdersSchema); - assert.isBigNumber('makerAssetFillAmount', makerAssetFillAmount); - const signatures = _.map(signedOrders, signedOrder => signedOrder.signature); - const abiEncodedData = this._getExchangeContract().marketBuyOrders.getABIEncodedTransactionData( - signedOrders, - makerAssetFillAmount, - signatures, - ); - return abiEncodedData; - } - /** - * Encodes a maketBuyOrdersNoThrow transaction. - * @param signedOrders An array of signed orders to fill. - * @param makerAssetFillAmount Maker asset fill amount. - * @return Hex encoded abi of the function call. - */ - public marketBuyOrdersNoThrowTx(signedOrders: SignedOrder[], makerAssetFillAmount: BigNumber): string { - assert.doesConformToSchema('signedOrders', signedOrders, schemas.signedOrdersSchema); - assert.isBigNumber('makerAssetFillAmount', makerAssetFillAmount); - const signatures = _.map(signedOrders, signedOrder => signedOrder.signature); - const abiEncodedData = this._getExchangeContract().marketBuyOrdersNoThrow.getABIEncodedTransactionData( - signedOrders, - makerAssetFillAmount, - signatures, - ); - return abiEncodedData; - } - /** - * Encodes a matchOrders transaction. - * @param leftOrder First order to match. - * @param rightOrder Second order to match. - * @return Hex encoded abi of the function call. - */ - public matchOrdersTx(leftOrder: SignedOrder, rightOrder: SignedOrder): string { - assert.doesConformToSchema('leftOrder', leftOrder, schemas.orderSchema); - assert.doesConformToSchema('rightOrder', rightOrder, schemas.orderSchema); - const abiEncodedData = this._getExchangeContract().matchOrders.getABIEncodedTransactionData( - leftOrder, - rightOrder, - leftOrder.signature, - rightOrder.signature, - ); - return abiEncodedData; - } - /** - * Encodes a preSign transaction. - * @param hash Hash to pre-sign - * @param signerAddress Address that should have signed the given hash. - * @param signature Proof that the hash has been signed by signer. - * @return Hex encoded abi of the function call. - */ - public preSignTx(hash: string, signerAddress: string, signature: string): string { - assert.isHexString('hash', hash); - assert.isETHAddressHex('signerAddress', signerAddress); - assert.isHexString('signature', signature); - const abiEncodedData = this._getExchangeContract().preSign.getABIEncodedTransactionData( - hash, - signerAddress, - signature, - ); - return abiEncodedData; - } - /** - * Encodes a setSignatureValidatorApproval transaction. - * @param validatorAddress Validator contract address. - * @param isApproved Boolean value to set approval to. - * @return Hex encoded abi of the function call. - */ - public setSignatureValidatorApprovalTx(validatorAddress: string, isApproved: boolean): string { - assert.isETHAddressHex('validatorAddress', validatorAddress); - assert.isBoolean('isApproved', isApproved); - const abiEncodedData = this._getExchangeContract().setSignatureValidatorApproval.getABIEncodedTransactionData( - validatorAddress, - isApproved, - ); - return abiEncodedData; - } - private _getExchangeContract(): ExchangeContract { - return this._exchangeInstance; - } -} diff --git a/packages/contract-wrappers/src/utils/utils.ts b/packages/contract-wrappers/src/utils/utils.ts deleted file mode 100644 index ab69385e7a..0000000000 --- a/packages/contract-wrappers/src/utils/utils.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { BigNumber } from '@0x/utils'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import * as _ from 'lodash'; - -import { constants } from './constants'; - -export const utils = { - getCurrentUnixTimestampSec(): BigNumber { - const milisecondsInSecond = 1000; - return new BigNumber(Date.now() / milisecondsInSecond).integerValue(); - }, - getCurrentUnixTimestampMs(): BigNumber { - return new BigNumber(Date.now()); - }, - numberPercentageToEtherTokenAmountPercentage(percentage: number): BigNumber { - return Web3Wrapper.toBaseUnitAmount(constants.ONE_AMOUNT, constants.ETHER_TOKEN_DECIMALS).multipliedBy( - percentage, - ); - }, - removeUndefinedProperties(obj: T): Partial { - return _.pickBy(obj); - }, -}; diff --git a/packages/contract-wrappers/test/calldata_decoder_test.ts b/packages/contract-wrappers/test/calldata_decoder_test.ts index ba1539ef55..3657d52511 100644 --- a/packages/contract-wrappers/test/calldata_decoder_test.ts +++ b/packages/contract-wrappers/test/calldata_decoder_test.ts @@ -8,6 +8,7 @@ import * as _ from 'lodash'; import 'mocha'; import { ContractAddresses, ContractWrappers } from '../src'; +import { getAbiEncodedTransactionData } from '../src/utils/getAbiEncodedTransactionData'; import { chaiSetup } from './utils/chai_setup'; import { migrateOnceAsync } from './utils/migrate'; @@ -80,8 +81,14 @@ describe('ABI Decoding Calldata', () => { blockPollingIntervalMs: 10, }; contractWrappers = new ContractWrappers(provider, config); - const transactionEncoder = await contractWrappers.exchange.transactionEncoderAsync(); - matchOrdersTxData = transactionEncoder.matchOrdersTx(signedOrderLeft, signedOrderRight); + matchOrdersTxData = getAbiEncodedTransactionData( + contractWrappers.exchange, + 'matchOrders', + signedOrderLeft, + signedOrderRight, + signedOrderLeft.signature, + signedOrderRight.signature, + ); }); describe('decode', () => { diff --git a/packages/contract-wrappers/test/calldata_optimization_utils_test.ts b/packages/contract-wrappers/test/calldata_optimization_utils_test.ts deleted file mode 100644 index 6cb8a669e3..0000000000 --- a/packages/contract-wrappers/test/calldata_optimization_utils_test.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { orderFactory } from '@0x/order-utils/lib/src/order_factory'; -import * as chai from 'chai'; -import * as _ from 'lodash'; -import 'mocha'; - -import { calldataOptimizationUtils } from '../src/utils/calldata_optimization_utils'; -import { constants } from '../src/utils/constants'; - -import { chaiSetup } from './utils/chai_setup'; - -chaiSetup.configure(); -const expect = chai.expect; - -// utility for generating a set of order objects with mostly NULL values -// except for a specified makerAssetData and takerAssetData -const FAKE_ORDERS_COUNT = 5; -const generateFakeOrders = (makerAssetData: string, takerAssetData: string) => - _.map(_.range(FAKE_ORDERS_COUNT), index => { - const order = orderFactory.createOrder( - constants.NULL_ADDRESS, - constants.ZERO_AMOUNT, - makerAssetData, - constants.ZERO_AMOUNT, - takerAssetData, - constants.NULL_ADDRESS, - ); - return { - ...order, - signature: 'dummy signature', - }; - }); - -describe('calldataOptimizationUtils', () => { - const fakeMakerAssetData = 'fakeMakerAssetData'; - const fakeTakerAssetData = 'fakeTakerAssetData'; - const orders = generateFakeOrders(fakeMakerAssetData, fakeTakerAssetData); - describe('#optimizeForwarderOrders', () => { - it('should make makerAssetData `0x` unless first order', () => { - const optimizedOrders = calldataOptimizationUtils.optimizeForwarderOrders(orders); - expect(optimizedOrders[0].makerAssetData).to.equal(fakeMakerAssetData); - const ordersWithoutHead = _.slice(optimizedOrders, 1); - _.forEach(ordersWithoutHead, order => expect(order.makerAssetData).to.equal(constants.NULL_BYTES)); - }); - it('should make all takerAssetData `0x`', () => { - const optimizedOrders = calldataOptimizationUtils.optimizeForwarderOrders(orders); - _.forEach(optimizedOrders, order => expect(order.takerAssetData).to.equal(constants.NULL_BYTES)); - }); - }); - describe('#optimizeForwarderFeeOrders', () => { - it('should make all makerAssetData `0x`', () => { - const optimizedOrders = calldataOptimizationUtils.optimizeForwarderFeeOrders(orders); - _.forEach(optimizedOrders, order => expect(order.makerAssetData).to.equal(constants.NULL_BYTES)); - }); - it('should make all takerAssetData `0x`', () => { - const optimizedOrders = calldataOptimizationUtils.optimizeForwarderFeeOrders(orders); - _.forEach(optimizedOrders, order => expect(order.takerAssetData).to.equal(constants.NULL_BYTES)); - }); - }); -}); diff --git a/packages/contract-wrappers/test/coordinator_wrapper_test.ts b/packages/contract-wrappers/test/coordinator_wrapper_test.ts index 5a8ea33ed3..8735088a97 100644 --- a/packages/contract-wrappers/test/coordinator_wrapper_test.ts +++ b/packages/contract-wrappers/test/coordinator_wrapper_test.ts @@ -1,7 +1,7 @@ import { CoordinatorRegistryContract } from '@0x/abi-gen-wrappers'; import { constants } from '@0x/contracts-test-utils'; import { defaultOrmConfig, getAppAsync } from '@0x/coordinator-server'; -import { BlockchainLifecycle } from '@0x/dev-utils'; +import { BlockchainLifecycle, tokenUtils } from '@0x/dev-utils'; import { FillScenarios } from '@0x/fill-scenarios'; import { assetDataUtils } from '@0x/order-utils'; import { SignedOrder } from '@0x/types'; @@ -16,7 +16,6 @@ import { CoordinatorServerErrorMsg } from '../src/utils/coordinator_server_types import { chaiSetup } from './utils/chai_setup'; import { migrateOnceAsync } from './utils/migrate'; -import { tokenUtils } from './utils/token_utils'; import { provider, web3Wrapper } from './utils/web3_wrapper'; chaiSetup.configure(); @@ -71,7 +70,7 @@ describe('CoordinatorWrapper', () => { contractWrappers = new ContractWrappers(provider, config); exchangeContractAddress = contractWrappers.exchange.address; userAddresses = await web3Wrapper.getAvailableAddressesAsync(); - zrxTokenAddress = contractWrappers.exchange.zrxTokenAddress; + zrxTokenAddress = contractAddresses.zrxToken; fillScenarios = new FillScenarios( provider, userAddresses, @@ -422,7 +421,7 @@ describe('CoordinatorWrapper', () => { txHash = await contractWrappers.coordinator.hardCancelOrdersUpToAsync(targetOrderEpoch, makerAddress); await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - const orderEpoch = await contractWrappers.exchange.getOrderEpochAsync( + const orderEpoch = await contractWrappers.exchange.orderEpoch.callAsync( makerAddress, contractWrappers.coordinator.address, ); diff --git a/packages/contract-wrappers/test/dutch_auction_wrapper_test.ts b/packages/contract-wrappers/test/dutch_auction_wrapper_test.ts deleted file mode 100644 index 15936a2eed..0000000000 --- a/packages/contract-wrappers/test/dutch_auction_wrapper_test.ts +++ /dev/null @@ -1,143 +0,0 @@ -import { expectTransactionFailedAsync, getLatestBlockTimestampAsync } from '@0x/contracts-test-utils'; -import { BlockchainLifecycle } from '@0x/dev-utils'; -import { assetDataUtils } from '@0x/order-utils'; -import { ERC20AssetData, RevertReason, SignedOrder } from '@0x/types'; -import { BigNumber } from '@0x/utils'; -import * as chai from 'chai'; -import 'mocha'; - -import { ContractWrappers, DutchAuctionWrapper } from '../src'; - -import { chaiSetup } from './utils/chai_setup'; -import { constants } from './utils/constants'; -import { DutchAuctionUtils } from './utils/dutch_auction_utils'; -import { migrateOnceAsync } from './utils/migrate'; -import { tokenUtils } from './utils/token_utils'; -import { provider, web3Wrapper } from './utils/web3_wrapper'; - -chaiSetup.configure(); -const expect = chai.expect; -const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper); - -// tslint:disable:custom-no-magic-numbers -describe('DutchAuctionWrapper', () => { - const makerAssetAmount = new BigNumber(5); - const auctionEndTakerAmount = new BigNumber(10); - const auctionBeginTakerAmount = auctionEndTakerAmount.times(2); - const tenMinutesInSeconds = 10 * 60; - let contractWrappers: ContractWrappers; - let exchangeContractAddress: string; - let userAddresses: string[]; - let makerAddress: string; - let takerAddress: string; - let makerTokenAddress: string; - let takerTokenAddress: string; - let buyOrder: SignedOrder; - let sellOrder: SignedOrder; - let makerTokenAssetData: string; - let takerTokenAssetData: string; - let auctionBeginTimeSeconds: BigNumber; - let auctionEndTimeSeconds: BigNumber; - before(async () => { - // setup contract wrappers & addresses - const contractAddresses = await migrateOnceAsync(); - await blockchainLifecycle.startAsync(); - const config = { - networkId: constants.TESTRPC_NETWORK_ID, - contractAddresses, - blockPollingIntervalMs: 10, - }; - contractWrappers = new ContractWrappers(provider, config); - exchangeContractAddress = contractWrappers.exchange.address; - userAddresses = await web3Wrapper.getAvailableAddressesAsync(); - [, makerAddress, takerAddress] = userAddresses; - [makerTokenAddress, takerTokenAddress] = tokenUtils.getDummyERC20TokenAddresses(); - // construct asset data for tokens being swapped - [makerTokenAssetData, takerTokenAssetData] = [ - assetDataUtils.encodeERC20AssetData(makerTokenAddress), - assetDataUtils.encodeERC20AssetData(takerTokenAddress), - ]; - // setup auction details in maker asset data - const currentBlockTimestamp: number = await getLatestBlockTimestampAsync(); - auctionBeginTimeSeconds = new BigNumber(currentBlockTimestamp - tenMinutesInSeconds); - auctionEndTimeSeconds = new BigNumber(currentBlockTimestamp + tenMinutesInSeconds); - // create auction orders - const coinbase = userAddresses[0]; - const dutchAuctionUtils = new DutchAuctionUtils( - web3Wrapper, - coinbase, - exchangeContractAddress, - contractWrappers.erc20Proxy.address, - ); - sellOrder = await dutchAuctionUtils.createSignedSellOrderAsync( - auctionBeginTimeSeconds, - auctionEndTimeSeconds, - auctionBeginTakerAmount, - auctionEndTakerAmount, - makerAssetAmount, - makerTokenAssetData, - takerTokenAssetData, - makerAddress, - constants.NULL_ADDRESS, - ); - buyOrder = await dutchAuctionUtils.createSignedBuyOrderAsync(sellOrder, takerAddress); - }); - after(async () => { - await blockchainLifecycle.revertAsync(); - }); - beforeEach(async () => { - await blockchainLifecycle.startAsync(); - }); - afterEach(async () => { - await blockchainLifecycle.revertAsync(); - }); - describe('.decodeDutchAuctionAssetData', () => { - it('decodes to the encoded values', async () => { - const encodedAssetData = DutchAuctionWrapper.encodeDutchAuctionAssetData( - makerTokenAssetData, - auctionBeginTimeSeconds, - makerAssetAmount, - ); - const decodedAssetData = DutchAuctionWrapper.decodeDutchAuctionData(encodedAssetData); - // tslint:disable-next-line:no-unnecessary-type-assertion - const erc20AssetData = decodedAssetData.assetData as ERC20AssetData; - expect(erc20AssetData.tokenAddress).to.eq(makerTokenAddress); - expect(decodedAssetData.beginAmount).to.be.bignumber.eq(makerAssetAmount); - expect(decodedAssetData.beginTimeSeconds).to.be.bignumber.eq(auctionBeginTimeSeconds); - }); - }); - describe('#matchOrdersAsync', () => { - it('should match two orders', async () => { - const txHash = await contractWrappers.dutchAuction.matchOrdersAsync(buyOrder, sellOrder, takerAddress); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - }); - it('should throw when invalid transaction and shouldValidate is true', async () => { - // request match with bad buy/sell orders - const badSellOrder = buyOrder; - const badBuyOrder = sellOrder; - return expectTransactionFailedAsync( - contractWrappers.dutchAuction.matchOrdersAsync(badBuyOrder, badSellOrder, takerAddress, { - shouldValidate: true, - }), - RevertReason.InvalidAssetData, - ); - }); - }); - - describe('#getAuctionDetailsAsync', () => { - it('should get auction details', async () => { - // get auction details - const auctionDetails = await contractWrappers.dutchAuction.getAuctionDetailsAsync(sellOrder); - // run some basic sanity checks on the return value - expect(auctionDetails.beginTimeSeconds, 'auctionDetails.beginTimeSeconds').to.be.bignumber.equal( - auctionBeginTimeSeconds, - ); - expect(auctionDetails.beginAmount, 'auctionDetails.beginAmount').to.be.bignumber.equal( - auctionBeginTakerAmount, - ); - expect(auctionDetails.endTimeSeconds, 'auctionDetails.endTimeSeconds').to.be.bignumber.equal( - auctionEndTimeSeconds, - ); - }); - }); -}); diff --git a/packages/contract-wrappers/test/erc20_proxy_wrapper_test.ts b/packages/contract-wrappers/test/erc20_proxy_wrapper_test.ts deleted file mode 100644 index d8dfa42047..0000000000 --- a/packages/contract-wrappers/test/erc20_proxy_wrapper_test.ts +++ /dev/null @@ -1,39 +0,0 @@ -import * as chai from 'chai'; - -import { ContractWrappers } from '../src'; - -import { chaiSetup } from './utils/chai_setup'; -import { constants } from './utils/constants'; -import { migrateOnceAsync } from './utils/migrate'; -import { provider } from './utils/web3_wrapper'; - -chaiSetup.configure(); -const expect = chai.expect; - -describe('ERC20ProxyWrapper', () => { - let contractWrappers: ContractWrappers; - before(async () => { - const contractAddresses = await migrateOnceAsync(); - const config = { - networkId: constants.TESTRPC_NETWORK_ID, - contractAddresses, - blockPollingIntervalMs: 10, - }; - contractWrappers = new ContractWrappers(provider, config); - }); - describe('#isAuthorizedAsync', () => { - it('should return false if the address is not authorized', async () => { - const isAuthorized = await contractWrappers.erc20Proxy.isAuthorizedAsync(constants.NULL_ADDRESS); - expect(isAuthorized).to.be.false(); - }); - }); - describe('#getAuthorizedAddressesAsync', () => { - it('should return the list of authorized addresses', async () => { - const authorizedAddresses = await contractWrappers.erc20Proxy.getAuthorizedAddressesAsync(); - for (const authorizedAddress of authorizedAddresses) { - const isAuthorized = await contractWrappers.erc20Proxy.isAuthorizedAsync(authorizedAddress); - expect(isAuthorized).to.be.true(); - } - }); - }); -}); diff --git a/packages/contract-wrappers/test/erc20_wrapper_test.ts b/packages/contract-wrappers/test/erc20_wrapper_test.ts deleted file mode 100644 index bfbb2196d6..0000000000 --- a/packages/contract-wrappers/test/erc20_wrapper_test.ts +++ /dev/null @@ -1,633 +0,0 @@ -import { ContractAddresses } from '@0x/contract-addresses'; -import { BlockchainLifecycle, callbackErrorReporter } from '@0x/dev-utils'; -import { EmptyWalletSubprovider, Web3ProviderEngine } from '@0x/subproviders'; -import { DoneCallback } from '@0x/types'; -import { BigNumber, providerUtils } from '@0x/utils'; -import * as chai from 'chai'; -import 'mocha'; - -import { - BlockParamLiteral, - BlockRange, - ContractWrappers, - ContractWrappersConfig, - ContractWrappersError, - DecodedLogEvent, - ERC20TokenApprovalEventArgs, - ERC20TokenEvents, - ERC20TokenTransferEventArgs, -} from '../src'; - -import { chaiSetup } from './utils/chai_setup'; -import { constants } from './utils/constants'; -import { migrateOnceAsync } from './utils/migrate'; -import { tokenUtils } from './utils/token_utils'; -import { provider, web3Wrapper } from './utils/web3_wrapper'; - -chaiSetup.configure(); -const expect = chai.expect; -const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper); - -describe('ERC20Wrapper', () => { - let contractWrappers: ContractWrappers; - let contractAddresses: ContractAddresses; - let userAddresses: string[]; - let tokens: string[]; - let coinbase: string; - let addressWithoutFunds: string; - let config: ContractWrappersConfig; - - before(async () => { - contractAddresses = await migrateOnceAsync(); - config = { - networkId: constants.TESTRPC_NETWORK_ID, - contractAddresses, - blockPollingIntervalMs: 10, - }; - contractWrappers = new ContractWrappers(provider, config); - userAddresses = await web3Wrapper.getAvailableAddressesAsync(); - tokens = tokenUtils.getDummyERC20TokenAddresses(); - coinbase = userAddresses[0]; - addressWithoutFunds = userAddresses[1]; - }); - beforeEach(async () => { - await blockchainLifecycle.startAsync(); - }); - afterEach(async () => { - await blockchainLifecycle.revertAsync(); - }); - describe('#transferAsync', () => { - let tokenAddress: string; - let transferAmount: BigNumber; - before(() => { - tokenAddress = tokens[0]; - transferAmount = new BigNumber(42); - }); - it('should successfully transfer tokens', async () => { - const fromAddress = coinbase; - const toAddress = addressWithoutFunds; - const preBalance = await contractWrappers.erc20Token.getBalanceAsync(tokenAddress, toAddress); - expect(preBalance).to.be.bignumber.equal(0); - await contractWrappers.erc20Token.transferAsync(tokenAddress, fromAddress, toAddress, transferAmount); - const postBalance = await contractWrappers.erc20Token.getBalanceAsync(tokenAddress, toAddress); - return expect(postBalance).to.be.bignumber.equal(transferAmount); - }); - it('should fail to transfer tokens if fromAddress has an insufficient balance', async () => { - const fromAddress = addressWithoutFunds; - const toAddress = coinbase; - return expect( - contractWrappers.erc20Token.transferAsync(tokenAddress, fromAddress, toAddress, transferAmount), - ).to.be.rejectedWith(ContractWrappersError.InsufficientBalanceForTransfer); - }); - }); - describe('#transferFromAsync', () => { - let tokenAddress: string; - let toAddress: string; - let senderAddress: string; - before(async () => { - tokenAddress = tokens[0]; - toAddress = addressWithoutFunds; - senderAddress = userAddresses[2]; - }); - it('should fail to transfer tokens if fromAddress has insufficient allowance set', async () => { - const fromAddress = coinbase; - const transferAmount = new BigNumber(42); - - const fromAddressBalance = await contractWrappers.erc20Token.getBalanceAsync(tokenAddress, fromAddress); - expect(fromAddressBalance).to.be.bignumber.greaterThan(transferAmount); - - const fromAddressAllowance = await contractWrappers.erc20Token.getAllowanceAsync( - tokenAddress, - fromAddress, - toAddress, - ); - expect(fromAddressAllowance).to.be.bignumber.equal(0); - - return expect( - contractWrappers.erc20Token.transferFromAsync( - tokenAddress, - fromAddress, - toAddress, - senderAddress, - transferAmount, - ), - ).to.be.rejectedWith(ContractWrappersError.InsufficientAllowanceForTransfer); - }); - it('[regression] should fail to transfer tokens if set allowance for toAddress instead of senderAddress', async () => { - const fromAddress = coinbase; - const transferAmount = new BigNumber(42); - - await contractWrappers.erc20Token.setAllowanceAsync(tokenAddress, fromAddress, toAddress, transferAmount); - - return expect( - contractWrappers.erc20Token.transferFromAsync( - tokenAddress, - fromAddress, - toAddress, - senderAddress, - transferAmount, - ), - ).to.be.rejectedWith(ContractWrappersError.InsufficientAllowanceForTransfer); - }); - it('should fail to transfer tokens if fromAddress has insufficient balance', async () => { - const fromAddress = addressWithoutFunds; - const transferAmount = new BigNumber(42); - - const fromAddressBalance = await contractWrappers.erc20Token.getBalanceAsync(tokenAddress, fromAddress); - expect(fromAddressBalance).to.be.bignumber.equal(0); - - await contractWrappers.erc20Token.setAllowanceAsync( - tokenAddress, - fromAddress, - senderAddress, - transferAmount, - ); - const fromAddressAllowance = await contractWrappers.erc20Token.getAllowanceAsync( - tokenAddress, - fromAddress, - senderAddress, - ); - expect(fromAddressAllowance).to.be.bignumber.equal(transferAmount); - - return expect( - contractWrappers.erc20Token.transferFromAsync( - tokenAddress, - fromAddress, - toAddress, - senderAddress, - transferAmount, - ), - ).to.be.rejectedWith(ContractWrappersError.InsufficientBalanceForTransfer); - }); - it('should successfully transfer tokens', async () => { - const fromAddress = coinbase; - - const preBalance = await contractWrappers.erc20Token.getBalanceAsync(tokenAddress, toAddress); - expect(preBalance).to.be.bignumber.equal(0); - - const transferAmount = new BigNumber(42); - await contractWrappers.erc20Token.setAllowanceAsync( - tokenAddress, - fromAddress, - senderAddress, - transferAmount, - ); - - await contractWrappers.erc20Token.transferFromAsync( - tokenAddress, - fromAddress, - toAddress, - senderAddress, - transferAmount, - ); - const postBalance = await contractWrappers.erc20Token.getBalanceAsync(tokenAddress, toAddress); - return expect(postBalance).to.be.bignumber.equal(transferAmount); - }); - }); - describe('#getBalanceAsync', () => { - describe('With provider with accounts', () => { - it('should return the balance for an existing ERC20 token', async () => { - const tokenAddress = tokens[0]; - const ownerAddress = coinbase; - const balance = await contractWrappers.erc20Token.getBalanceAsync(tokenAddress, ownerAddress); - const expectedBalance = new BigNumber('1000000000000000000000000000'); - return expect(balance).to.be.bignumber.equal(expectedBalance); - }); - it('should return a balance of 0 for a non-existent owner address', async () => { - const tokenAddress = tokens[0]; - const nonExistentOwner = '0x198c6ad858f213fb31b6fe809e25040e6b964593'; - const balance = await contractWrappers.erc20Token.getBalanceAsync(tokenAddress, nonExistentOwner); - const expectedBalance = new BigNumber(0); - return expect(balance).to.be.bignumber.equal(expectedBalance); - }); - }); - describe('With provider without accounts', () => { - let zeroExContractWithoutAccounts: ContractWrappers; - before(async () => { - const emptyWalletProvider = addEmptyWalletSubprovider(provider); - zeroExContractWithoutAccounts = new ContractWrappers(emptyWalletProvider, config); - }); - it('should return balance even when called with provider instance without addresses', async () => { - const tokenAddress = tokens[0]; - const ownerAddress = coinbase; - const balance = await zeroExContractWithoutAccounts.erc20Token.getBalanceAsync( - tokenAddress, - ownerAddress, - ); - const expectedBalance = new BigNumber('1000000000000000000000000000'); - return expect(balance).to.be.bignumber.equal(expectedBalance); - }); - }); - }); - describe('#setAllowanceAsync', () => { - it("should set the spender's allowance", async () => { - const tokenAddress = tokens[0]; - const ownerAddress = coinbase; - const spenderAddress = addressWithoutFunds; - - const allowanceBeforeSet = await contractWrappers.erc20Token.getAllowanceAsync( - tokenAddress, - ownerAddress, - spenderAddress, - ); - const expectedAllowanceBeforeAllowanceSet = new BigNumber(0); - expect(allowanceBeforeSet).to.be.bignumber.equal(expectedAllowanceBeforeAllowanceSet); - - const amountInBaseUnits = new BigNumber(50); - await contractWrappers.erc20Token.setAllowanceAsync( - tokenAddress, - ownerAddress, - spenderAddress, - amountInBaseUnits, - ); - - const allowanceAfterSet = await contractWrappers.erc20Token.getAllowanceAsync( - tokenAddress, - ownerAddress, - spenderAddress, - ); - const expectedAllowanceAfterAllowanceSet = amountInBaseUnits; - return expect(allowanceAfterSet).to.be.bignumber.equal(expectedAllowanceAfterAllowanceSet); - }); - }); - describe('#setUnlimitedAllowanceAsync', () => { - it("should set the unlimited spender's allowance", async () => { - const tokenAddress = tokens[0]; - const ownerAddress = coinbase; - const spenderAddress = addressWithoutFunds; - - await contractWrappers.erc20Token.setUnlimitedAllowanceAsync(tokenAddress, ownerAddress, spenderAddress); - const allowance = await contractWrappers.erc20Token.getAllowanceAsync( - tokenAddress, - ownerAddress, - spenderAddress, - ); - return expect(allowance).to.be.bignumber.equal( - contractWrappers.erc20Token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS, - ); - }); - it('should reduce the gas cost for transfers including tokens with unlimited allowance support', async () => { - const transferAmount = new BigNumber(5); - const zrxAddress = contractAddresses.zrxToken; - const [, userWithNormalAllowance, userWithUnlimitedAllowance] = userAddresses; - await contractWrappers.erc20Token.setAllowanceAsync( - zrxAddress, - coinbase, - userWithNormalAllowance, - transferAmount, - ); - await contractWrappers.erc20Token.setUnlimitedAllowanceAsync( - zrxAddress, - coinbase, - userWithUnlimitedAllowance, - ); - - const initBalanceWithNormalAllowance = await web3Wrapper.getBalanceInWeiAsync(userWithNormalAllowance); - const initBalanceWithUnlimitedAllowance = await web3Wrapper.getBalanceInWeiAsync( - userWithUnlimitedAllowance, - ); - - await contractWrappers.erc20Token.transferFromAsync( - zrxAddress, - coinbase, - userWithNormalAllowance, - userWithNormalAllowance, - transferAmount, - ); - await contractWrappers.erc20Token.transferFromAsync( - zrxAddress, - coinbase, - userWithUnlimitedAllowance, - userWithUnlimitedAllowance, - transferAmount, - ); - - const finalBalanceWithNormalAllowance = await web3Wrapper.getBalanceInWeiAsync(userWithNormalAllowance); - const finalBalanceWithUnlimitedAllowance = await web3Wrapper.getBalanceInWeiAsync( - userWithUnlimitedAllowance, - ); - - const normalGasCost = initBalanceWithNormalAllowance.minus(finalBalanceWithNormalAllowance); - const unlimitedGasCost = initBalanceWithUnlimitedAllowance.minus(finalBalanceWithUnlimitedAllowance); - - // In theory the gas cost with unlimited allowance should be smaller, but with testrpc it's actually bigger. - // This needs to be investigated in ethereumjs-vm. This test is essentially a repro. - // TODO: Make this test pass with inverted assertion. - expect(unlimitedGasCost.toNumber()).to.be.gt(normalGasCost.toNumber()); - }); - }); - describe('#getAllowanceAsync', () => { - describe('With provider with accounts', () => { - it('should get the proxy allowance', async () => { - const tokenAddress = tokens[0]; - const ownerAddress = coinbase; - const spenderAddress = addressWithoutFunds; - - const amountInBaseUnits = new BigNumber(50); - await contractWrappers.erc20Token.setAllowanceAsync( - tokenAddress, - ownerAddress, - spenderAddress, - amountInBaseUnits, - ); - - const allowance = await contractWrappers.erc20Token.getAllowanceAsync( - tokenAddress, - ownerAddress, - spenderAddress, - ); - const expectedAllowance = amountInBaseUnits; - return expect(allowance).to.be.bignumber.equal(expectedAllowance); - }); - it('should return 0 if no allowance set yet', async () => { - const tokenAddress = tokens[0]; - const ownerAddress = coinbase; - const spenderAddress = addressWithoutFunds; - const allowance = await contractWrappers.erc20Token.getAllowanceAsync( - tokenAddress, - ownerAddress, - spenderAddress, - ); - const expectedAllowance = new BigNumber(0); - return expect(allowance).to.be.bignumber.equal(expectedAllowance); - }); - }); - describe('With provider without accounts', () => { - let zeroExContractWithoutAccounts: ContractWrappers; - before(async () => { - const emptyWalletProvider = addEmptyWalletSubprovider(provider); - zeroExContractWithoutAccounts = new ContractWrappers(emptyWalletProvider, config); - }); - it('should get the proxy allowance', async () => { - const tokenAddress = tokens[0]; - const ownerAddress = coinbase; - const spenderAddress = addressWithoutFunds; - - const amountInBaseUnits = new BigNumber(50); - await contractWrappers.erc20Token.setAllowanceAsync( - tokenAddress, - ownerAddress, - spenderAddress, - amountInBaseUnits, - ); - - const allowance = await zeroExContractWithoutAccounts.erc20Token.getAllowanceAsync( - tokenAddress, - ownerAddress, - spenderAddress, - ); - const expectedAllowance = amountInBaseUnits; - return expect(allowance).to.be.bignumber.equal(expectedAllowance); - }); - }); - }); - describe('#getProxyAllowanceAsync', () => { - it('should get the proxy allowance', async () => { - const tokenAddress = tokens[0]; - const ownerAddress = coinbase; - - const amountInBaseUnits = new BigNumber(50); - await contractWrappers.erc20Token.setProxyAllowanceAsync(tokenAddress, ownerAddress, amountInBaseUnits); - - const allowance = await contractWrappers.erc20Token.getProxyAllowanceAsync(tokenAddress, ownerAddress); - const expectedAllowance = amountInBaseUnits; - return expect(allowance).to.be.bignumber.equal(expectedAllowance); - }); - }); - describe('#setProxyAllowanceAsync', () => { - it('should set the proxy allowance', async () => { - const tokenAddress = tokens[0]; - const ownerAddress = coinbase; - - const allowanceBeforeSet = await contractWrappers.erc20Token.getProxyAllowanceAsync( - tokenAddress, - ownerAddress, - ); - const expectedAllowanceBeforeAllowanceSet = new BigNumber(0); - expect(allowanceBeforeSet).to.be.bignumber.equal(expectedAllowanceBeforeAllowanceSet); - - const amountInBaseUnits = new BigNumber(50); - await contractWrappers.erc20Token.setProxyAllowanceAsync(tokenAddress, ownerAddress, amountInBaseUnits); - - const allowanceAfterSet = await contractWrappers.erc20Token.getProxyAllowanceAsync( - tokenAddress, - ownerAddress, - ); - const expectedAllowanceAfterAllowanceSet = amountInBaseUnits; - return expect(allowanceAfterSet).to.be.bignumber.equal(expectedAllowanceAfterAllowanceSet); - }); - }); - describe('#setUnlimitedProxyAllowanceAsync', () => { - it('should set the unlimited proxy allowance', async () => { - const tokenAddress = tokens[0]; - const ownerAddress = coinbase; - - await contractWrappers.erc20Token.setUnlimitedProxyAllowanceAsync(tokenAddress, ownerAddress); - const allowance = await contractWrappers.erc20Token.getProxyAllowanceAsync(tokenAddress, ownerAddress); - return expect(allowance).to.be.bignumber.equal( - contractWrappers.erc20Token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS, - ); - }); - }); - describe('#subscribe', () => { - const indexFilterValues = {}; - let tokenAddress: string; - const transferAmount = new BigNumber(42); - const allowanceAmount = new BigNumber(42); - before(() => { - tokenAddress = tokens[0]; - }); - afterEach(() => { - contractWrappers.erc20Token.unsubscribeAll(); - }); - // Hack: Mocha does not allow a test to be both async and have a `done` callback - // Since we need to await the receipt of the event in the `subscribe` callback, - // we do need both. A hack is to make the top-level a sync fn w/ a done callback and then - // wrap the rest of the test in an async block - // Source: https://github.com/mochajs/mocha/issues/2407 - it('Should receive the Transfer event when tokens are transfered', (done: DoneCallback) => { - (async () => { - const callback = callbackErrorReporter.reportNodeCallbackErrors(done)( - (logEvent: DecodedLogEvent) => { - expect(logEvent.isRemoved).to.be.false(); - expect(logEvent.log.logIndex).to.be.equal(0); - expect(logEvent.log.transactionIndex).to.be.equal(0); - expect(logEvent.log.blockNumber).to.be.a('number'); - const args = logEvent.log.args; - expect(args._from).to.be.equal(coinbase); - expect(args._to).to.be.equal(addressWithoutFunds); - expect(args._value).to.be.bignumber.equal(transferAmount); - }, - ); - contractWrappers.erc20Token.subscribe( - tokenAddress, - ERC20TokenEvents.Transfer, - indexFilterValues, - callback, - ); - await contractWrappers.erc20Token.transferAsync( - tokenAddress, - coinbase, - addressWithoutFunds, - transferAmount, - ); - })().catch(done); - }); - it('Should receive the Approval event when allowance is being set', (done: DoneCallback) => { - (async () => { - const callback = callbackErrorReporter.reportNodeCallbackErrors(done)( - (logEvent: DecodedLogEvent) => { - expect(logEvent).to.not.be.undefined(); - expect(logEvent.isRemoved).to.be.false(); - const args = logEvent.log.args; - expect(args._owner).to.be.equal(coinbase); - expect(args._spender).to.be.equal(addressWithoutFunds); - expect(args._value).to.be.bignumber.equal(allowanceAmount); - }, - ); - contractWrappers.erc20Token.subscribe( - tokenAddress, - ERC20TokenEvents.Approval, - indexFilterValues, - callback, - ); - await contractWrappers.erc20Token.setAllowanceAsync( - tokenAddress, - coinbase, - addressWithoutFunds, - allowanceAmount, - ); - })().catch(done); - }); - it('Outstanding subscriptions are cancelled when contractWrappers.unsubscribeAll called', (done: DoneCallback) => { - (async () => { - const callbackNeverToBeCalled = callbackErrorReporter.reportNodeCallbackErrors(done)( - (_logEvent: DecodedLogEvent) => { - done(new Error('Expected this subscription to have been cancelled')); - }, - ); - contractWrappers.erc20Token.subscribe( - tokenAddress, - ERC20TokenEvents.Transfer, - indexFilterValues, - callbackNeverToBeCalled, - ); - const callbackToBeCalled = callbackErrorReporter.reportNodeCallbackErrors(done)(); - contractWrappers.unsubscribeAll(); - contractWrappers.erc20Token.subscribe( - tokenAddress, - ERC20TokenEvents.Transfer, - indexFilterValues, - callbackToBeCalled, - ); - await contractWrappers.erc20Token.transferAsync( - tokenAddress, - coinbase, - addressWithoutFunds, - transferAmount, - ); - })().catch(done); - }); - it('Should cancel subscription when unsubscribe called', (done: DoneCallback) => { - (async () => { - const callbackNeverToBeCalled = callbackErrorReporter.reportNodeCallbackErrors(done)( - (_logEvent: DecodedLogEvent) => { - done(new Error('Expected this subscription to have been cancelled')); - }, - ); - const subscriptionToken = contractWrappers.erc20Token.subscribe( - tokenAddress, - ERC20TokenEvents.Transfer, - indexFilterValues, - callbackNeverToBeCalled, - ); - contractWrappers.erc20Token.unsubscribe(subscriptionToken); - await contractWrappers.erc20Token.transferAsync( - tokenAddress, - coinbase, - addressWithoutFunds, - transferAmount, - ); - done(); - })().catch(done); - }); - }); - describe('#getLogsAsync', () => { - let tokenAddress: string; - let tokenTransferProxyAddress: string; - const blockRange: BlockRange = { - fromBlock: 0, - toBlock: BlockParamLiteral.Latest, - }; - let txHash: string; - before(() => { - tokenAddress = tokens[0]; - tokenTransferProxyAddress = contractWrappers.erc20Proxy.address; - }); - it('should get logs with decoded args emitted by Approval', async () => { - txHash = await contractWrappers.erc20Token.setUnlimitedProxyAllowanceAsync(tokenAddress, coinbase); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - const eventName = ERC20TokenEvents.Approval; - const indexFilterValues = {}; - const logs = await contractWrappers.erc20Token.getLogsAsync( - tokenAddress, - eventName, - blockRange, - indexFilterValues, - ); - expect(logs).to.have.length(1); - const args = logs[0].args; - expect(logs[0].event).to.be.equal(eventName); - expect(args._owner).to.be.equal(coinbase); - expect(args._spender).to.be.equal(tokenTransferProxyAddress); - expect(args._value).to.be.bignumber.equal(contractWrappers.erc20Token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS); - }); - it('should only get the logs with the correct event name', async () => { - txHash = await contractWrappers.erc20Token.setUnlimitedProxyAllowanceAsync(tokenAddress, coinbase); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - const differentEventName = ERC20TokenEvents.Transfer; - const indexFilterValues = {}; - const logs = await contractWrappers.erc20Token.getLogsAsync( - tokenAddress, - differentEventName, - blockRange, - indexFilterValues, - ); - expect(logs).to.have.length(0); - }); - it('should only get the logs with the correct indexed fields', async () => { - txHash = await contractWrappers.erc20Token.setUnlimitedProxyAllowanceAsync(tokenAddress, coinbase); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - txHash = await contractWrappers.erc20Token.setUnlimitedProxyAllowanceAsync( - tokenAddress, - addressWithoutFunds, - ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - const eventName = ERC20TokenEvents.Approval; - const indexFilterValues = { - _owner: coinbase, - }; - const logs = await contractWrappers.erc20Token.getLogsAsync( - tokenAddress, - eventName, - blockRange, - indexFilterValues, - ); - expect(logs).to.have.length(1); - const args = logs[0].args; - expect(args._owner).to.be.equal(coinbase); - }); - }); -}); -// tslint:disable:max-file-line-count - -function addEmptyWalletSubprovider(p: Web3ProviderEngine): Web3ProviderEngine { - const providerEngine = new Web3ProviderEngine(); - providerEngine.addProvider(new EmptyWalletSubprovider()); - const currentSubproviders = (p as any)._providers; - for (const subprovider of currentSubproviders) { - providerEngine.addProvider(subprovider); - } - providerUtils.startProviderEngine(providerEngine); - return providerEngine; -} diff --git a/packages/contract-wrappers/test/erc721_proxy_wrapper_test.ts b/packages/contract-wrappers/test/erc721_proxy_wrapper_test.ts deleted file mode 100644 index 9b0fe88172..0000000000 --- a/packages/contract-wrappers/test/erc721_proxy_wrapper_test.ts +++ /dev/null @@ -1,39 +0,0 @@ -import * as chai from 'chai'; - -import { ContractWrappers } from '../src'; - -import { chaiSetup } from './utils/chai_setup'; -import { constants } from './utils/constants'; -import { migrateOnceAsync } from './utils/migrate'; -import { provider } from './utils/web3_wrapper'; - -chaiSetup.configure(); -const expect = chai.expect; - -describe('ERC721ProxyWrapper', () => { - let contractWrappers: ContractWrappers; - before(async () => { - const contractAddresses = await migrateOnceAsync(); - const config = { - networkId: constants.TESTRPC_NETWORK_ID, - contractAddresses, - blockPollingIntervalMs: 10, - }; - contractWrappers = new ContractWrappers(provider, config); - }); - describe('#isAuthorizedAsync', () => { - it('should return false if the address is not authorized', async () => { - const isAuthorized = await contractWrappers.erc721Proxy.isAuthorizedAsync(constants.NULL_ADDRESS); - expect(isAuthorized).to.be.false(); - }); - }); - describe('#getAuthorizedAddressesAsync', () => { - it('should return the list of authorized addresses', async () => { - const authorizedAddresses = await contractWrappers.erc721Proxy.getAuthorizedAddressesAsync(); - for (const authorizedAddress of authorizedAddresses) { - const isAuthorized = await contractWrappers.erc721Proxy.isAuthorizedAsync(authorizedAddress); - expect(isAuthorized).to.be.true(); - } - }); - }); -}); diff --git a/packages/contract-wrappers/test/erc721_wrapper_test.ts b/packages/contract-wrappers/test/erc721_wrapper_test.ts deleted file mode 100644 index 2679ef8d3b..0000000000 --- a/packages/contract-wrappers/test/erc721_wrapper_test.ts +++ /dev/null @@ -1,465 +0,0 @@ -import { BlockchainLifecycle, callbackErrorReporter } from '@0x/dev-utils'; -import { EmptyWalletSubprovider, Web3ProviderEngine } from '@0x/subproviders'; -import { DoneCallback } from '@0x/types'; -import { BigNumber, providerUtils } from '@0x/utils'; -import * as chai from 'chai'; -import 'mocha'; - -import { - BlockParamLiteral, - BlockRange, - ContractWrappers, - ContractWrappersConfig, - ContractWrappersError, - DecodedLogEvent, - ERC721TokenApprovalEventArgs, - ERC721TokenApprovalForAllEventArgs, - ERC721TokenEvents, - ERC721TokenTransferEventArgs, -} from '../src'; - -import { chaiSetup } from './utils/chai_setup'; -import { constants } from './utils/constants'; -import { migrateOnceAsync } from './utils/migrate'; -import { tokenUtils } from './utils/token_utils'; -import { provider, web3Wrapper } from './utils/web3_wrapper'; - -chaiSetup.configure(); -const expect = chai.expect; -const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper); - -describe('ERC721Wrapper', () => { - let contractWrappers: ContractWrappers; - let userAddresses: string[]; - let tokens: string[]; - let ownerAddress: string; - let tokenAddress: string; - let anotherOwnerAddress: string; - let operatorAddress: string; - let approvedAddress: string; - let receiverAddress: string; - let config: ContractWrappersConfig; - - before(async () => { - const contractAddresses = await migrateOnceAsync(); - config = { - networkId: constants.TESTRPC_NETWORK_ID, - contractAddresses, - blockPollingIntervalMs: 10, - }; - contractWrappers = new ContractWrappers(provider, config); - userAddresses = await web3Wrapper.getAvailableAddressesAsync(); - tokens = tokenUtils.getDummyERC721TokenAddresses(); - tokenAddress = tokens[0]; - [ownerAddress, operatorAddress, anotherOwnerAddress, approvedAddress, receiverAddress] = userAddresses; - }); - beforeEach(async () => { - await blockchainLifecycle.startAsync(); - }); - afterEach(async () => { - await blockchainLifecycle.revertAsync(); - }); - describe('#transferFromAsync', () => { - it('should fail to transfer NFT if fromAddress has no approvals set', async () => { - const tokenId = await tokenUtils.mintDummyERC721Async(tokenAddress, ownerAddress); - return expect( - contractWrappers.erc721Token.transferFromAsync(tokenAddress, receiverAddress, approvedAddress, tokenId), - ).to.be.rejectedWith(ContractWrappersError.ERC721NoApproval); - }); - it('should successfully transfer tokens when sender is an approved address', async () => { - const tokenId = await tokenUtils.mintDummyERC721Async(tokenAddress, ownerAddress); - let txHash = await contractWrappers.erc721Token.setApprovalAsync(tokenAddress, approvedAddress, tokenId); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - const owner = await contractWrappers.erc721Token.getOwnerOfAsync(tokenAddress, tokenId); - expect(owner).to.be.equal(ownerAddress); - txHash = await contractWrappers.erc721Token.transferFromAsync( - tokenAddress, - receiverAddress, - approvedAddress, - tokenId, - ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - const newOwner = await contractWrappers.erc721Token.getOwnerOfAsync(tokenAddress, tokenId); - expect(newOwner).to.be.equal(receiverAddress); - }); - it('should successfully transfer tokens when sender is an approved operator', async () => { - const tokenId = await tokenUtils.mintDummyERC721Async(tokenAddress, ownerAddress); - const isApprovedForAll = true; - let txHash = await contractWrappers.erc721Token.setApprovalForAllAsync( - tokenAddress, - ownerAddress, - operatorAddress, - isApprovedForAll, - ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - const owner = await contractWrappers.erc721Token.getOwnerOfAsync(tokenAddress, tokenId); - expect(owner).to.be.equal(ownerAddress); - txHash = await contractWrappers.erc721Token.transferFromAsync( - tokenAddress, - receiverAddress, - operatorAddress, - tokenId, - ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - const newOwner = await contractWrappers.erc721Token.getOwnerOfAsync(tokenAddress, tokenId); - expect(newOwner).to.be.equal(receiverAddress); - }); - }); - describe('#getTokenCountAsync', () => { - describe('With provider with accounts', () => { - it('should return the count for an existing ERC721 token', async () => { - let tokenCount = await contractWrappers.erc721Token.getTokenCountAsync(tokenAddress, ownerAddress); - expect(tokenCount).to.be.bignumber.equal(0); - await tokenUtils.mintDummyERC721Async(tokenAddress, ownerAddress); - tokenCount = await contractWrappers.erc721Token.getTokenCountAsync(tokenAddress, ownerAddress); - expect(tokenCount).to.be.bignumber.equal(1); - }); - it('should return a balance of 0 for a non-existent owner address', async () => { - const nonExistentOwner = '0x198c6ad858f213fb31b6fe809e25040e6b964593'; - const balance = await contractWrappers.erc721Token.getTokenCountAsync(tokenAddress, nonExistentOwner); - const expectedBalance = new BigNumber(0); - return expect(balance).to.be.bignumber.equal(expectedBalance); - }); - }); - describe('With provider without accounts', () => { - let zeroExContractWithoutAccounts: ContractWrappers; - before(async () => { - const emptyWalletProvider = addEmptyWalletSubprovider(provider); - zeroExContractWithoutAccounts = new ContractWrappers(emptyWalletProvider, config); - }); - it('should return balance even when called with provider instance without addresses', async () => { - const balance = await zeroExContractWithoutAccounts.erc721Token.getTokenCountAsync( - tokenAddress, - ownerAddress, - ); - return expect(balance).to.be.bignumber.equal(0); - }); - }); - }); - describe('#getOwnerOfAsync', () => { - it('should return the owner for an existing ERC721 token', async () => { - const tokenId = await tokenUtils.mintDummyERC721Async(tokenAddress, ownerAddress); - const tokenOwner = await contractWrappers.erc721Token.getOwnerOfAsync(tokenAddress, tokenId); - expect(tokenOwner).to.be.bignumber.equal(ownerAddress); - }); - it('should return undefined not 0 for a non-existent ERC721', async () => { - const fakeTokenId = new BigNumber(42); - return expect(contractWrappers.erc721Token.getOwnerOfAsync(tokenAddress, fakeTokenId)).to.be.rejectedWith( - ContractWrappersError.ERC721OwnerNotFound, - ); - }); - }); - describe('#setApprovalForAllAsync/isApprovedForAllAsync', () => { - it('should check if operator address is approved', async () => { - let isApprovedForAll = await contractWrappers.erc721Token.isApprovedForAllAsync( - tokenAddress, - ownerAddress, - operatorAddress, - ); - expect(isApprovedForAll).to.be.false(); - // set - isApprovedForAll = true; - let txHash = await contractWrappers.erc721Token.setApprovalForAllAsync( - tokenAddress, - ownerAddress, - operatorAddress, - isApprovedForAll, - ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - isApprovedForAll = await contractWrappers.erc721Token.isApprovedForAllAsync( - tokenAddress, - ownerAddress, - operatorAddress, - ); - expect(isApprovedForAll).to.be.true(); - // unset - txHash = await contractWrappers.erc721Token.setApprovalForAllAsync( - tokenAddress, - ownerAddress, - operatorAddress, - false, - ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - isApprovedForAll = await contractWrappers.erc721Token.isApprovedForAllAsync( - tokenAddress, - ownerAddress, - operatorAddress, - ); - expect(isApprovedForAll).to.be.false(); - }); - }); - describe('#setProxyApprovalForAllAsync/isProxyApprovedForAllAsync', () => { - it('should check if proxy address is approved', async () => { - let isApprovedForAll = true; - const txHash = await contractWrappers.erc721Token.setProxyApprovalForAllAsync( - tokenAddress, - ownerAddress, - isApprovedForAll, - ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - isApprovedForAll = await contractWrappers.erc721Token.isProxyApprovedForAllAsync( - tokenAddress, - ownerAddress, - ); - expect(isApprovedForAll).to.be.true(); - }); - }); - describe('#setApprovalAsync/getApprovedIfExistsAsync', () => { - it("should set the spender's approval", async () => { - const tokenId = await tokenUtils.mintDummyERC721Async(tokenAddress, ownerAddress); - - const approvalBeforeSet = await contractWrappers.erc721Token.getApprovedIfExistsAsync( - tokenAddress, - tokenId, - ); - expect(approvalBeforeSet).to.be.undefined(); - await contractWrappers.erc721Token.setApprovalAsync(tokenAddress, approvedAddress, tokenId); - const approvalAfterSet = await contractWrappers.erc721Token.getApprovedIfExistsAsync(tokenAddress, tokenId); - expect(approvalAfterSet).to.be.equal(approvedAddress); - }); - }); - describe('#setProxyApprovalAsync/isProxyApprovedAsync', () => { - it('should set the proxy approval', async () => { - const tokenId = await tokenUtils.mintDummyERC721Async(tokenAddress, ownerAddress); - - const isProxyApprovedBeforeSet = await contractWrappers.erc721Token.isProxyApprovedAsync( - tokenAddress, - tokenId, - ); - expect(isProxyApprovedBeforeSet).to.be.false(); - await contractWrappers.erc721Token.setProxyApprovalAsync(tokenAddress, tokenId); - const isProxyApprovedAfterSet = await contractWrappers.erc721Token.isProxyApprovedAsync( - tokenAddress, - tokenId, - ); - expect(isProxyApprovedAfterSet).to.be.true(); - }); - }); - describe('#subscribe', () => { - const indexFilterValues = {}; - afterEach(() => { - contractWrappers.erc721Token.unsubscribeAll(); - }); - // Hack: Mocha does not allow a test to be both async and have a `done` callback - // Since we need to await the receipt of the event in the `subscribe` callback, - // we do need both. A hack is to make the top-level a sync fn w/ a done callback and then - // wrap the rest of the test in an async block - // Source: https://github.com/mochajs/mocha/issues/2407 - it('Should receive the Transfer event when tokens are transfered', (done: DoneCallback) => { - (async () => { - const callback = callbackErrorReporter.reportNodeCallbackErrors(done)( - (logEvent: DecodedLogEvent) => { - expect(logEvent.isRemoved).to.be.false(); - expect(logEvent.log.logIndex).to.be.equal(0); - expect(logEvent.log.transactionIndex).to.be.equal(0); - expect(logEvent.log.blockNumber).to.be.a('number'); - const args = logEvent.log.args; - expect(args._from).to.be.equal(ownerAddress); - expect(args._to).to.be.equal(receiverAddress); - expect(args._tokenId).to.be.bignumber.equal(tokenId); - }, - ); - const tokenId = await tokenUtils.mintDummyERC721Async(tokenAddress, ownerAddress); - const isApprovedForAll = true; - await web3Wrapper.awaitTransactionSuccessAsync( - await contractWrappers.erc721Token.setApprovalForAllAsync( - tokenAddress, - ownerAddress, - operatorAddress, - isApprovedForAll, - ), - constants.AWAIT_TRANSACTION_MINED_MS, - ); - contractWrappers.erc721Token.subscribe( - tokenAddress, - ERC721TokenEvents.Transfer, - indexFilterValues, - callback, - ); - await web3Wrapper.awaitTransactionSuccessAsync( - await contractWrappers.erc721Token.transferFromAsync( - tokenAddress, - receiverAddress, - operatorAddress, - tokenId, - ), - constants.AWAIT_TRANSACTION_MINED_MS, - ); - })().catch(done); - }); - it('Should receive the Approval event when allowance is being set', (done: DoneCallback) => { - (async () => { - const callback = callbackErrorReporter.reportNodeCallbackErrors(done)( - (logEvent: DecodedLogEvent) => { - expect(logEvent).to.not.be.undefined(); - expect(logEvent.isRemoved).to.be.false(); - const args = logEvent.log.args; - expect(args._owner).to.be.equal(ownerAddress); - expect(args._approved).to.be.equal(approvedAddress); - expect(args._tokenId).to.be.bignumber.equal(tokenId); - }, - ); - contractWrappers.erc721Token.subscribe( - tokenAddress, - ERC721TokenEvents.Approval, - indexFilterValues, - callback, - ); - const tokenId = await tokenUtils.mintDummyERC721Async(tokenAddress, ownerAddress); - await web3Wrapper.awaitTransactionSuccessAsync( - await contractWrappers.erc721Token.setApprovalAsync(tokenAddress, approvedAddress, tokenId), - constants.AWAIT_TRANSACTION_MINED_MS, - ); - })().catch(done); - }); - it('Outstanding subscriptions are cancelled when contractWrappers.unsubscribeAll called', (done: DoneCallback) => { - (async () => { - const callbackNeverToBeCalled = callbackErrorReporter.reportNodeCallbackErrors(done)( - (logEvent: DecodedLogEvent) => { - done(new Error('Expected this subscription to have been cancelled')); - }, - ); - contractWrappers.erc721Token.subscribe( - tokenAddress, - ERC721TokenEvents.Transfer, - indexFilterValues, - callbackNeverToBeCalled, - ); - const callbackToBeCalled = callbackErrorReporter.reportNodeCallbackErrors(done)(); - contractWrappers.unsubscribeAll(); - contractWrappers.erc721Token.subscribe( - tokenAddress, - ERC721TokenEvents.Approval, - indexFilterValues, - callbackToBeCalled, - ); - const tokenId = await tokenUtils.mintDummyERC721Async(tokenAddress, ownerAddress); - await web3Wrapper.awaitTransactionSuccessAsync( - await contractWrappers.erc721Token.setApprovalAsync(tokenAddress, approvedAddress, tokenId), - constants.AWAIT_TRANSACTION_MINED_MS, - ); - done(); - })().catch(done); - }); - it('Should cancel subscription when unsubscribe called', (done: DoneCallback) => { - (async () => { - const callbackNeverToBeCalled = callbackErrorReporter.reportNodeCallbackErrors(done)( - (logEvent: DecodedLogEvent) => { - done(new Error('Expected this subscription to have been cancelled')); - }, - ); - const subscriptionToken = contractWrappers.erc721Token.subscribe( - tokenAddress, - ERC721TokenEvents.ApprovalForAll, - indexFilterValues, - callbackNeverToBeCalled, - ); - contractWrappers.erc721Token.unsubscribe(subscriptionToken); - - const isApproved = true; - await web3Wrapper.awaitTransactionSuccessAsync( - await contractWrappers.erc721Token.setApprovalForAllAsync( - tokenAddress, - ownerAddress, - operatorAddress, - isApproved, - ), - constants.AWAIT_TRANSACTION_MINED_MS, - ); - done(); - })().catch(done); - }); - }); - describe('#getLogsAsync', () => { - const blockRange: BlockRange = { - fromBlock: 0, - toBlock: BlockParamLiteral.Latest, - }; - let txHash: string; - it('should get logs with decoded args emitted by ApprovalForAll', async () => { - const isApprovedForAll = true; - txHash = await contractWrappers.erc721Token.setApprovalForAllAsync( - tokenAddress, - ownerAddress, - operatorAddress, - isApprovedForAll, - ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - const eventName = ERC721TokenEvents.ApprovalForAll; - const indexFilterValues = {}; - const logs = await contractWrappers.erc721Token.getLogsAsync( - tokenAddress, - eventName, - blockRange, - indexFilterValues, - ); - expect(logs).to.have.length(1); - const args = logs[0].args; - expect(logs[0].event).to.be.equal(eventName); - expect(args._owner).to.be.equal(ownerAddress); - expect(args._operator).to.be.equal(operatorAddress); - expect(args._approved).to.be.equal(isApprovedForAll); - }); - it('should only get the logs with the correct event name', async () => { - const isApprovedForAll = true; - txHash = await contractWrappers.erc721Token.setApprovalForAllAsync( - tokenAddress, - ownerAddress, - operatorAddress, - isApprovedForAll, - ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - const differentEventName = ERC721TokenEvents.Transfer; - const indexFilterValues = {}; - const logs = await contractWrappers.erc721Token.getLogsAsync( - tokenAddress, - differentEventName, - blockRange, - indexFilterValues, - ); - expect(logs).to.have.length(0); - }); - it('should only get the logs with the correct indexed fields', async () => { - const isApprovedForAll = true; - txHash = await contractWrappers.erc721Token.setApprovalForAllAsync( - tokenAddress, - ownerAddress, - operatorAddress, - isApprovedForAll, - ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - txHash = await contractWrappers.erc721Token.setApprovalForAllAsync( - tokenAddress, - anotherOwnerAddress, - operatorAddress, - isApprovedForAll, - ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - const eventName = ERC721TokenEvents.ApprovalForAll; - const indexFilterValues = { - _owner: anotherOwnerAddress, - }; - const logs = await contractWrappers.erc721Token.getLogsAsync( - tokenAddress, - eventName, - blockRange, - indexFilterValues, - ); - expect(logs).to.have.length(1); - const args = logs[0].args; - expect(args._owner).to.be.equal(anotherOwnerAddress); - }); - }); -}); -// tslint:disable:max-file-line-count - -function addEmptyWalletSubprovider(p: Web3ProviderEngine): Web3ProviderEngine { - const providerEngine = new Web3ProviderEngine(); - providerEngine.addProvider(new EmptyWalletSubprovider()); - const currentSubproviders = (p as any)._providers; - for (const subprovider of currentSubproviders) { - providerEngine.addProvider(subprovider); - } - providerUtils.startProviderEngine(providerEngine); - return providerEngine; -} diff --git a/packages/contract-wrappers/test/ether_token_wrapper_test.ts b/packages/contract-wrappers/test/ether_token_wrapper_test.ts deleted file mode 100644 index cc2419aa25..0000000000 --- a/packages/contract-wrappers/test/ether_token_wrapper_test.ts +++ /dev/null @@ -1,437 +0,0 @@ -import { ContractAddresses } from '@0x/contract-addresses'; -import { BlockchainLifecycle, callbackErrorReporter } from '@0x/dev-utils'; -import { DoneCallback } from '@0x/types'; -import { BigNumber } from '@0x/utils'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import * as chai from 'chai'; -import 'mocha'; - -import { - BlockParamLiteral, - BlockRange, - ContractWrappers, - ContractWrappersError, - WETH9ApprovalEventArgs, - WETH9DepositEventArgs, - WETH9Events, - WETH9TransferEventArgs, - WETH9WithdrawalEventArgs, -} from '../src'; -import { DecodedLogEvent } from '../src/types'; - -import { chaiSetup } from './utils/chai_setup'; -import { constants } from './utils/constants'; -import { migrateOnceAsync } from './utils/migrate'; -import { provider, web3Wrapper } from './utils/web3_wrapper'; - -chaiSetup.configure(); -const expect = chai.expect; -const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper); - -// Since the address depositing/withdrawing ETH/WETH also needs to pay gas costs for the transaction, -// a small amount of ETH will be used to pay this gas cost. We therefore check that the difference between -// the expected balance and actual balance (given the amount of ETH deposited), only deviates by the amount -// required to pay gas costs. -const MAX_REASONABLE_GAS_COST_IN_WEI = 62517; - -describe('EtherTokenWrapper', () => { - let contractWrappers: ContractWrappers; - let contractAddresses: ContractAddresses; - let userAddresses: string[]; - let addressWithETH: string; - let wethContractAddress: string; - let depositWeiAmount: BigNumber; - const decimalPlaces = 7; - let addressWithoutFunds: string; - const gasPrice = new BigNumber(1); - const transferAmount = new BigNumber(42); - const allowanceAmount = new BigNumber(42); - const depositAmount = new BigNumber(42); - const withdrawalAmount = new BigNumber(42); - before(async () => { - contractAddresses = await migrateOnceAsync(); - const config = { - gasPrice, - networkId: constants.TESTRPC_NETWORK_ID, - contractAddresses, - blockPollingIntervalMs: 10, - }; - contractWrappers = new ContractWrappers(provider, config); - userAddresses = await web3Wrapper.getAvailableAddressesAsync(); - addressWithETH = userAddresses[0]; - wethContractAddress = contractAddresses.etherToken; - depositWeiAmount = Web3Wrapper.toWei(new BigNumber(5)); - addressWithoutFunds = userAddresses[1]; - }); - beforeEach(async () => { - await blockchainLifecycle.startAsync(); - }); - afterEach(async () => { - await blockchainLifecycle.revertAsync(); - }); - describe('#getContractAddressIfExists', async () => { - it('should return contract address if connected to a known network', () => { - const contractAddressIfExists = contractAddresses.etherToken; - expect(contractAddressIfExists).to.not.be.undefined(); - }); - it('should throw if connected to a private network and contract addresses are not specified', () => { - const UNKNOWN_NETWORK_NETWORK_ID = 10; - expect( - () => - new ContractWrappers(provider, { - networkId: UNKNOWN_NETWORK_NETWORK_ID, - } as any), - ).to.throw(); - }); - }); - describe('#depositAsync', () => { - it('should successfully deposit ETH and issue Wrapped ETH tokens', async () => { - const preETHBalance = await web3Wrapper.getBalanceInWeiAsync(addressWithETH); - const preWETHBalance = await contractWrappers.erc20Token.getBalanceAsync( - wethContractAddress, - addressWithETH, - ); - expect(preETHBalance).to.be.bignumber.gt(0); - expect(preWETHBalance).to.be.bignumber.equal(0); - - const txHash = await contractWrappers.etherToken.depositAsync( - wethContractAddress, - depositWeiAmount, - addressWithETH, - ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - - const postETHBalanceInWei = await web3Wrapper.getBalanceInWeiAsync(addressWithETH); - const postWETHBalanceInBaseUnits = await contractWrappers.erc20Token.getBalanceAsync( - wethContractAddress, - addressWithETH, - ); - - expect(postWETHBalanceInBaseUnits).to.be.bignumber.equal(depositWeiAmount); - const remainingETHInWei = preETHBalance.minus(depositWeiAmount); - const gasCost = remainingETHInWei.minus(postETHBalanceInWei); - expect(gasCost).to.be.bignumber.lte(MAX_REASONABLE_GAS_COST_IN_WEI); - }); - it('should throw if user has insufficient ETH balance for deposit', async () => { - const preETHBalance = await web3Wrapper.getBalanceInWeiAsync(addressWithETH); - - const extraETHBalance = Web3Wrapper.toWei(new BigNumber(5)); - const overETHBalanceinWei = preETHBalance.plus(extraETHBalance); - - return expect( - contractWrappers.etherToken.depositAsync(wethContractAddress, overETHBalanceinWei, addressWithETH), - ).to.be.rejectedWith(ContractWrappersError.InsufficientEthBalanceForDeposit); - }); - }); - describe('#withdrawAsync', () => { - it('should successfully withdraw ETH in return for Wrapped ETH tokens', async () => { - const ETHBalanceInWei = await web3Wrapper.getBalanceInWeiAsync(addressWithETH); - - await contractWrappers.etherToken.depositAsync(wethContractAddress, depositWeiAmount, addressWithETH); - - const expectedPreETHBalance = ETHBalanceInWei.minus(depositWeiAmount); - const preETHBalance = await web3Wrapper.getBalanceInWeiAsync(addressWithETH); - const preWETHBalance = await contractWrappers.erc20Token.getBalanceAsync( - wethContractAddress, - addressWithETH, - ); - let gasCost = expectedPreETHBalance.minus(preETHBalance); - expect(gasCost).to.be.bignumber.lte(MAX_REASONABLE_GAS_COST_IN_WEI); - expect(preWETHBalance).to.be.bignumber.equal(depositWeiAmount); - - const txHash = await contractWrappers.etherToken.withdrawAsync( - wethContractAddress, - depositWeiAmount, - addressWithETH, - ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - - const postETHBalance = await web3Wrapper.getBalanceInWeiAsync(addressWithETH); - const postWETHBalanceInBaseUnits = await contractWrappers.erc20Token.getBalanceAsync( - wethContractAddress, - addressWithETH, - ); - - expect(postWETHBalanceInBaseUnits).to.be.bignumber.equal(0); - const expectedETHBalance = preETHBalance.plus(depositWeiAmount).integerValue(decimalPlaces); - gasCost = expectedETHBalance.minus(postETHBalance); - expect(gasCost).to.be.bignumber.lte(MAX_REASONABLE_GAS_COST_IN_WEI); - }); - it('should throw if user has insufficient WETH balance for withdrawal', async () => { - const preWETHBalance = await contractWrappers.erc20Token.getBalanceAsync( - wethContractAddress, - addressWithETH, - ); - expect(preWETHBalance).to.be.bignumber.equal(0); - - // tslint:disable-next-line:custom-no-magic-numbers - const overWETHBalance = preWETHBalance.plus(999999999); - - return expect( - contractWrappers.etherToken.withdrawAsync(wethContractAddress, overWETHBalance, addressWithETH), - ).to.be.rejectedWith(ContractWrappersError.InsufficientWEthBalanceForWithdrawal); - }); - }); - describe('#subscribe', () => { - const indexFilterValues = {}; - let etherTokenAddress: string; - before(async () => { - etherTokenAddress = contractAddresses.etherToken; - }); - afterEach(() => { - contractWrappers.etherToken.unsubscribeAll(); - }); - // Hack: Mocha does not allow a test to be both async and have a `done` callback - // Since we need to await the receipt of the event in the `subscribe` callback, - // we do need both. A hack is to make the top-level async fn w/ a done callback and then - // wrap the rest of the test in an async block - // Source: https://github.com/mochajs/mocha/issues/2407 - it('Should receive the Transfer event when tokens are transfered', (done: DoneCallback) => { - (async () => { - const callback = callbackErrorReporter.reportNodeCallbackErrors(done)( - (logEvent: DecodedLogEvent) => { - expect(logEvent).to.not.be.undefined(); - expect(logEvent.isRemoved).to.be.false(); - expect(logEvent.log.logIndex).to.be.equal(0); - expect(logEvent.log.transactionIndex).to.be.equal(0); - expect(logEvent.log.blockNumber).to.be.a('number'); - const args = logEvent.log.args; - expect(args._from).to.be.equal(addressWithETH); - expect(args._to).to.be.equal(addressWithoutFunds); - expect(args._value).to.be.bignumber.equal(transferAmount); - }, - ); - await contractWrappers.etherToken.depositAsync(etherTokenAddress, transferAmount, addressWithETH); - contractWrappers.etherToken.subscribe( - etherTokenAddress, - WETH9Events.Transfer, - indexFilterValues, - callback, - ); - await contractWrappers.erc20Token.transferAsync( - etherTokenAddress, - addressWithETH, - addressWithoutFunds, - transferAmount, - ); - })().catch(done); - }); - it('Should receive the Approval event when allowance is being set', (done: DoneCallback) => { - (async () => { - const callback = callbackErrorReporter.reportNodeCallbackErrors(done)( - (logEvent: DecodedLogEvent) => { - expect(logEvent).to.not.be.undefined(); - expect(logEvent.isRemoved).to.be.false(); - const args = logEvent.log.args; - expect(args._owner).to.be.equal(addressWithETH); - expect(args._spender).to.be.equal(addressWithoutFunds); - expect(args._value).to.be.bignumber.equal(allowanceAmount); - }, - ); - contractWrappers.etherToken.subscribe( - etherTokenAddress, - WETH9Events.Approval, - indexFilterValues, - callback, - ); - await contractWrappers.erc20Token.setAllowanceAsync( - etherTokenAddress, - addressWithETH, - addressWithoutFunds, - allowanceAmount, - ); - })().catch(done); - }); - it('Should receive the Deposit event when ether is being deposited', (done: DoneCallback) => { - (async () => { - const callback = callbackErrorReporter.reportNodeCallbackErrors(done)( - (logEvent: DecodedLogEvent) => { - expect(logEvent).to.not.be.undefined(); - expect(logEvent.isRemoved).to.be.false(); - const args = logEvent.log.args; - expect(args._owner).to.be.equal(addressWithETH); - expect(args._value).to.be.bignumber.equal(depositAmount); - }, - ); - contractWrappers.etherToken.subscribe( - etherTokenAddress, - WETH9Events.Deposit, - indexFilterValues, - callback, - ); - await contractWrappers.etherToken.depositAsync(etherTokenAddress, depositAmount, addressWithETH); - })().catch(done); - }); - it('Should receive the Withdrawal event when ether is being withdrawn', (done: DoneCallback) => { - (async () => { - const callback = callbackErrorReporter.reportNodeCallbackErrors(done)( - (logEvent: DecodedLogEvent) => { - expect(logEvent).to.not.be.undefined(); - expect(logEvent.isRemoved).to.be.false(); - const args = logEvent.log.args; - expect(args._owner).to.be.equal(addressWithETH); - expect(args._value).to.be.bignumber.equal(depositAmount); - }, - ); - await contractWrappers.etherToken.depositAsync(etherTokenAddress, depositAmount, addressWithETH); - contractWrappers.etherToken.subscribe( - etherTokenAddress, - WETH9Events.Withdrawal, - indexFilterValues, - callback, - ); - await contractWrappers.etherToken.withdrawAsync(etherTokenAddress, withdrawalAmount, addressWithETH); - })().catch(done); - }); - it('should cancel outstanding subscriptions when contractWrappers.unsubscribeAll is called', (done: DoneCallback) => { - (async () => { - const callbackNeverToBeCalled = callbackErrorReporter.reportNodeCallbackErrors(done)( - (_logEvent: DecodedLogEvent) => { - done(new Error('Expected this subscription to have been cancelled')); - }, - ); - contractWrappers.etherToken.subscribe( - etherTokenAddress, - WETH9Events.Transfer, - indexFilterValues, - callbackNeverToBeCalled, - ); - const callbackToBeCalled = callbackErrorReporter.reportNodeCallbackErrors(done)(); - contractWrappers.unsubscribeAll(); - await contractWrappers.etherToken.depositAsync(etherTokenAddress, transferAmount, addressWithETH); - contractWrappers.etherToken.subscribe( - etherTokenAddress, - WETH9Events.Transfer, - indexFilterValues, - callbackToBeCalled, - ); - await contractWrappers.erc20Token.transferAsync( - etherTokenAddress, - addressWithETH, - addressWithoutFunds, - transferAmount, - ); - })().catch(done); - }); - it('Should cancel subscription when unsubscribe called', (done: DoneCallback) => { - (async () => { - const callbackNeverToBeCalled = callbackErrorReporter.reportNodeCallbackErrors(done)( - (_logEvent: DecodedLogEvent) => { - done(new Error('Expected this subscription to have been cancelled')); - }, - ); - await contractWrappers.etherToken.depositAsync(etherTokenAddress, transferAmount, addressWithETH); - const subscriptionToken = contractWrappers.etherToken.subscribe( - etherTokenAddress, - WETH9Events.Transfer, - indexFilterValues, - callbackNeverToBeCalled, - ); - contractWrappers.etherToken.unsubscribe(subscriptionToken); - await contractWrappers.erc20Token.transferAsync( - etherTokenAddress, - addressWithETH, - addressWithoutFunds, - transferAmount, - ); - done(); - })().catch(done); - }); - }); - describe('#getLogsAsync', () => { - let etherTokenAddress: string; - let erc20ProxyAddress: string; - let blockRange: BlockRange; - let txHash: string; - before(async () => { - addressWithETH = userAddresses[0]; - etherTokenAddress = contractAddresses.etherToken; - erc20ProxyAddress = contractWrappers.erc20Proxy.address; - // Start the block range after all migrations to avoid unexpected logs - const currentBlock: number = await web3Wrapper.getBlockNumberAsync(); - const fromBlock = currentBlock + 1; - blockRange = { - fromBlock, - toBlock: BlockParamLiteral.Latest, - }; - }); - it('should get logs with decoded args emitted by Approval', async () => { - txHash = await contractWrappers.erc20Token.setUnlimitedProxyAllowanceAsync( - etherTokenAddress, - addressWithETH, - ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - const eventName = WETH9Events.Approval; - const indexFilterValues = {}; - const logs = await contractWrappers.etherToken.getLogsAsync( - etherTokenAddress, - eventName, - blockRange, - indexFilterValues, - ); - expect(logs).to.have.length(1); - const args = logs[0].args; - expect(logs[0].event).to.be.equal(eventName); - expect(args._owner).to.be.equal(addressWithETH); - expect(args._spender).to.be.equal(erc20ProxyAddress); - expect(args._value).to.be.bignumber.equal(contractWrappers.erc20Token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS); - }); - it('should get logs with decoded args emitted by Deposit', async () => { - await contractWrappers.etherToken.depositAsync(etherTokenAddress, depositAmount, addressWithETH); - const eventName = WETH9Events.Deposit; - const indexFilterValues = {}; - const logs = await contractWrappers.etherToken.getLogsAsync( - etherTokenAddress, - eventName, - blockRange, - indexFilterValues, - ); - expect(logs).to.have.length(1); - const args = logs[0].args; - expect(logs[0].event).to.be.equal(eventName); - expect(args._owner).to.be.equal(addressWithETH); - expect(args._value).to.be.bignumber.equal(depositAmount); - }); - it('should only get the logs with the correct event name', async () => { - txHash = await contractWrappers.erc20Token.setUnlimitedProxyAllowanceAsync( - etherTokenAddress, - addressWithETH, - ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - const differentEventName = WETH9Events.Transfer; - const indexFilterValues = {}; - const logs = await contractWrappers.etherToken.getLogsAsync( - etherTokenAddress, - differentEventName, - blockRange, - indexFilterValues, - ); - expect(logs).to.have.length(0); - }); - it('should only get the logs with the correct indexed fields', async () => { - txHash = await contractWrappers.erc20Token.setUnlimitedProxyAllowanceAsync( - etherTokenAddress, - addressWithETH, - ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - txHash = await contractWrappers.erc20Token.setUnlimitedProxyAllowanceAsync( - etherTokenAddress, - addressWithoutFunds, - ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - const eventName = WETH9Events.Approval; - const indexFilterValues = { - _owner: addressWithETH, - }; - const logs = await contractWrappers.etherToken.getLogsAsync( - etherTokenAddress, - eventName, - blockRange, - indexFilterValues, - ); - expect(logs).to.have.length(1); - const args = logs[0].args; - expect(args._owner).to.be.equal(addressWithETH); - }); - }); -}); diff --git a/packages/contract-wrappers/test/exchange_wrapper_test.ts b/packages/contract-wrappers/test/exchange_wrapper_test.ts index bcb226e2ff..29853d63bb 100644 --- a/packages/contract-wrappers/test/exchange_wrapper_test.ts +++ b/packages/contract-wrappers/test/exchange_wrapper_test.ts @@ -1,8 +1,7 @@ -import { DummyERC20TokenContract } from '@0x/abi-gen-wrappers'; import { BlockchainLifecycle, callbackErrorReporter } from '@0x/dev-utils'; import { FillScenarios } from '@0x/fill-scenarios'; import { assetDataUtils, orderHashUtils, signatureUtils } from '@0x/order-utils'; -import { DoneCallback, RevertReason, SignedOrder } from '@0x/types'; +import { DoneCallback, SignedOrder } from '@0x/types'; import { BigNumber } from '@0x/utils'; import * as chai from 'chai'; import { BlockParamLiteral } from 'ethereum-types'; @@ -10,8 +9,8 @@ import 'mocha'; import { ContractWrappers, ExchangeCancelEventArgs, ExchangeEvents, ExchangeFillEventArgs, OrderStatus } from '../src'; import { DecodedLogEvent } from '../src/types'; +import { _getDefaultContractAddresses } from '../src/utils/contract_addresses'; -import { UntransferrableDummyERC20Token } from './artifacts/UntransferrableDummyERC20Token'; import { chaiSetup } from './utils/chai_setup'; import { constants } from './utils/constants'; import { migrateOnceAsync } from './utils/migrate'; @@ -35,7 +34,6 @@ describe('ExchangeWrapper', () => { let takerAddress: string; let makerAssetData: string; let takerAssetData: string; - let txHash: string; const fillableAmount = new BigNumber(5); const takerTokenFillAmount = new BigNumber(5); let signedOrder: SignedOrder; @@ -52,7 +50,7 @@ describe('ExchangeWrapper', () => { contractWrappers = new ContractWrappers(provider, config); exchangeContractAddress = contractWrappers.exchange.address; userAddresses = await web3Wrapper.getAvailableAddressesAsync(); - zrxTokenAddress = contractWrappers.exchange.zrxTokenAddress; + zrxTokenAddress = contractAddresses.zrxToken; fillScenarios = new FillScenarios( provider, userAddresses, @@ -94,71 +92,71 @@ describe('ExchangeWrapper', () => { describe('fill order(s)', () => { describe('#fillOrderAsync', () => { it('should fill a valid order', async () => { - txHash = await contractWrappers.exchange.fillOrderAsync( + await contractWrappers.exchange.fillOrder.awaitTransactionSuccessAsync( signedOrder, takerTokenFillAmount, - takerAddress, + signedOrder.signature, + { from: takerAddress }, ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); }); }); describe('#fillOrderNoThrowAsync', () => { it('should fill a valid order', async () => { - txHash = await contractWrappers.exchange.fillOrderNoThrowAsync( + await contractWrappers.exchange.fillOrderNoThrow.awaitTransactionSuccessAsync( signedOrder, takerTokenFillAmount, - takerAddress, + signedOrder.signature, + { from: takerAddress }, ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - const orderInfo = await contractWrappers.exchange.getOrderInfoAsync(signedOrder); + const orderInfo = await contractWrappers.exchange.getOrderInfo.callAsync(signedOrder); expect(orderInfo.orderStatus).to.be.equal(OrderStatus.FullyFilled); }); }); describe('#fillOrKillOrderAsync', () => { it('should fill or kill a valid order', async () => { - txHash = await contractWrappers.exchange.fillOrKillOrderAsync( + await contractWrappers.exchange.fillOrKillOrder.awaitTransactionSuccessAsync( signedOrder, takerTokenFillAmount, - takerAddress, + signedOrder.signature, + { from: takerAddress }, ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); }); }); describe('#batchFillOrdersAsync', () => { it('should fill a batch of valid orders', async () => { const signedOrders = [signedOrder, anotherSignedOrder]; const takerAssetFillAmounts = [takerTokenFillAmount, takerTokenFillAmount]; - txHash = await contractWrappers.exchange.batchFillOrdersAsync( + await contractWrappers.exchange.batchFillOrders.awaitTransactionSuccessAsync( signedOrders, takerAssetFillAmounts, - takerAddress, + signedOrders.map(o => o.signature), + { from: takerAddress }, ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); }); }); describe('#marketBuyOrdersAsync', () => { it('should maker buy', async () => { const signedOrders = [signedOrder, anotherSignedOrder]; const makerAssetFillAmount = takerTokenFillAmount; - txHash = await contractWrappers.exchange.marketBuyOrdersAsync( + await contractWrappers.exchange.marketBuyOrders.awaitTransactionSuccessAsync( signedOrders, makerAssetFillAmount, - takerAddress, + signedOrders.map(o => o.signature), + { from: takerAddress }, ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); }); }); describe('#marketBuyOrdersNoThrowAsync', () => { it('should no throw maker buy', async () => { const signedOrders = [signedOrder, anotherSignedOrder]; const makerAssetFillAmount = takerTokenFillAmount; - txHash = await contractWrappers.exchange.marketBuyOrdersNoThrowAsync( + await contractWrappers.exchange.marketBuyOrdersNoThrow.awaitTransactionSuccessAsync( signedOrders, makerAssetFillAmount, - takerAddress, + signedOrders.map(o => o.signature), + { from: takerAddress }, ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - const orderInfo = await contractWrappers.exchange.getOrderInfoAsync(signedOrder); + const orderInfo = await contractWrappers.exchange.getOrderInfo.callAsync(signedOrder); expect(orderInfo.orderStatus).to.be.equal(OrderStatus.FullyFilled); }); }); @@ -166,25 +164,25 @@ describe('ExchangeWrapper', () => { it('should maker sell', async () => { const signedOrders = [signedOrder, anotherSignedOrder]; const takerAssetFillAmount = takerTokenFillAmount; - txHash = await contractWrappers.exchange.marketSellOrdersAsync( + await contractWrappers.exchange.marketSellOrders.awaitTransactionSuccessAsync( signedOrders, takerAssetFillAmount, - takerAddress, + signedOrders.map(o => o.signature), + { from: takerAddress }, ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); }); }); describe('#marketSellOrdersNoThrowAsync', () => { it('should no throw maker sell', async () => { const signedOrders = [signedOrder, anotherSignedOrder]; const takerAssetFillAmount = takerTokenFillAmount; - txHash = await contractWrappers.exchange.marketSellOrdersNoThrowAsync( + await contractWrappers.exchange.marketSellOrdersNoThrow.awaitTransactionSuccessAsync( signedOrders, takerAssetFillAmount, - takerAddress, + signedOrders.map(o => o.signature), + { from: takerAddress }, ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - const orderInfo = await contractWrappers.exchange.getOrderInfoAsync(signedOrder); + const orderInfo = await contractWrappers.exchange.getOrderInfo.callAsync(signedOrder); expect(orderInfo.orderStatus).to.be.equal(OrderStatus.FullyFilled); }); }); @@ -192,15 +190,15 @@ describe('ExchangeWrapper', () => { it('should fill a batch of valid orders', async () => { const signedOrders = [signedOrder, anotherSignedOrder]; const takerAssetFillAmounts = [takerTokenFillAmount, takerTokenFillAmount]; - txHash = await contractWrappers.exchange.batchFillOrdersNoThrowAsync( + await contractWrappers.exchange.batchFillOrdersNoThrow.awaitTransactionSuccessAsync( signedOrders, takerAssetFillAmounts, - takerAddress, + signedOrders.map(o => o.signature), + { from: takerAddress }, ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - let orderInfo = await contractWrappers.exchange.getOrderInfoAsync(signedOrder); + let orderInfo = await contractWrappers.exchange.getOrderInfo.callAsync(signedOrder); expect(orderInfo.orderStatus).to.be.equal(OrderStatus.FullyFilled); - orderInfo = await contractWrappers.exchange.getOrderInfoAsync(anotherSignedOrder); + orderInfo = await contractWrappers.exchange.getOrderInfo.callAsync(anotherSignedOrder); expect(orderInfo.orderStatus).to.be.equal(OrderStatus.FullyFilled); }); }); @@ -208,12 +206,12 @@ describe('ExchangeWrapper', () => { it('should fill or kill a batch of valid orders', async () => { const signedOrders = [signedOrder, anotherSignedOrder]; const takerAssetFillAmounts = [takerTokenFillAmount, takerTokenFillAmount]; - txHash = await contractWrappers.exchange.batchFillOrKillOrdersAsync( + await contractWrappers.exchange.batchFillOrKillOrders.awaitTransactionSuccessAsync( signedOrders, takerAssetFillAmounts, - takerAddress, + signedOrders.map(o => o.signature), + { from: takerAddress }, ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); }); }); describe('#matchOrdersAsync', () => { @@ -225,35 +223,39 @@ describe('ExchangeWrapper', () => { takerAddress, fillableAmount, ); - txHash = await contractWrappers.exchange.matchOrdersAsync( + await contractWrappers.exchange.matchOrders.awaitTransactionSuccessAsync( signedOrder, matchingSignedOrder, - takerAddress, + signedOrder.signature, + matchingSignedOrder.signature, + { from: takerAddress }, ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); }); }); }); describe('cancel order(s)', () => { describe('#cancelOrderAsync', () => { it('should cancel a valid order', async () => { - txHash = await contractWrappers.exchange.cancelOrderAsync(signedOrder); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); + await contractWrappers.exchange.cancelOrder.awaitTransactionSuccessAsync(signedOrder, { + from: makerAddress, + }); }); }); describe('#batchCancelOrdersAsync', () => { it('should cancel a batch of valid orders', async () => { const orders = [signedOrder, anotherSignedOrder]; - txHash = await contractWrappers.exchange.batchCancelOrdersAsync(orders); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); + await contractWrappers.exchange.batchCancelOrders.awaitTransactionSuccessAsync(orders, { + from: makerAddress, + }); }); }); describe('#cancelOrdersUpTo/getOrderEpochAsync', () => { it('should cancel orders up to target order epoch', async () => { const targetOrderEpoch = new BigNumber(42); - txHash = await contractWrappers.exchange.cancelOrdersUpToAsync(targetOrderEpoch, makerAddress); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - const orderEpoch = await contractWrappers.exchange.getOrderEpochAsync( + await contractWrappers.exchange.cancelOrdersUpTo.awaitTransactionSuccessAsync(targetOrderEpoch, { + from: makerAddress, + }); + const orderEpoch = await contractWrappers.exchange.orderEpoch.callAsync( makerAddress, constants.NULL_ADDRESS, ); @@ -261,138 +263,35 @@ describe('ExchangeWrapper', () => { }); }); }); - describe('#getZRXAssetData', () => { - it('should get the asset data', () => { - const ZRX_ASSET_DATA = contractWrappers.exchange.getZRXAssetData(); - const ASSET_DATA_HEX_LENGTH = 74; - expect(ZRX_ASSET_DATA).to.have.length(ASSET_DATA_HEX_LENGTH); - }); - }); describe('#getOrderInfoAsync', () => { it('should get the order info', async () => { - const orderInfo = await contractWrappers.exchange.getOrderInfoAsync(signedOrder); + const orderInfo = await contractWrappers.exchange.getOrderInfo.callAsync(signedOrder); const orderHash = orderHashUtils.getOrderHashHex(signedOrder); expect(orderInfo.orderHash).to.be.equal(orderHash); }); }); describe('#getOrdersInfoAsync', () => { it('should get the orders info', async () => { - const ordersInfo = await contractWrappers.exchange.getOrdersInfoAsync([signedOrder, anotherSignedOrder]); + const ordersInfo = await contractWrappers.exchange.getOrdersInfo.callAsync([ + signedOrder, + anotherSignedOrder, + ]); const orderHash = orderHashUtils.getOrderHashHex(signedOrder); expect(ordersInfo[0].orderHash).to.be.equal(orderHash); const anotherOrderHash = orderHashUtils.getOrderHashHex(anotherSignedOrder); expect(ordersInfo[1].orderHash).to.be.equal(anotherOrderHash); }); }); - describe('#validateOrderFillableOrThrowAsync', () => { - it('should throw if signature is invalid', async () => { - const signedOrderWithInvalidSignature = { - ...signedOrder, - signature: - '0x1b61a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351bc3340349190569279751135161d22529dc25add4f6069af05be04cacbda2ace225403', - }; - - return expect( - contractWrappers.exchange.validateOrderFillableOrThrowAsync(signedOrderWithInvalidSignature), - ).to.eventually.to.be.rejectedWith(RevertReason.InvalidOrderSignature); - }); - it('should validate the order with the current balances and allowances for the maker', async () => { - await contractWrappers.exchange.validateOrderFillableOrThrowAsync(signedOrder, { - validateRemainingOrderAmountIsFillable: false, - }); - }); - it('should validate the order with remaining fillable amount for the order', async () => { - await contractWrappers.exchange.validateOrderFillableOrThrowAsync(signedOrder); - }); - it('should validate the order with specified amount', async () => { - await contractWrappers.exchange.validateOrderFillableOrThrowAsync(signedOrder, { - expectedFillTakerTokenAmount: signedOrder.takerAssetAmount, - }); - }); - it('should throw if the amount is greater than the allowance/balance', async () => { - return expect( - contractWrappers.exchange.validateOrderFillableOrThrowAsync(signedOrder, { - // tslint:disable-next-line:custom-no-magic-numbers - expectedFillTakerTokenAmount: new BigNumber(2).pow(256).minus(1), - }), - ).to.eventually.to.be.rejected(); - }); - it('should throw when the maker does not have enough balance for the remaining order amount', async () => { - const makerBalance = await contractWrappers.erc20Token.getBalanceAsync(makerTokenAddress, makerAddress); - // Change maker balance to have less than the order amount - const remainingBalance = makerBalance.minus(signedOrder.makerAssetAmount.minus(1)); - await web3Wrapper.awaitTransactionSuccessAsync( - await contractWrappers.erc20Token.transferAsync( - makerTokenAddress, - makerAddress, - constants.NULL_ADDRESS, - remainingBalance, - ), - ); - return expect( - contractWrappers.exchange.validateOrderFillableOrThrowAsync(signedOrder), - ).to.eventually.to.be.rejected(); - }); - it('should validate the order when remaining order amount has some fillable amount', async () => { - const makerBalance = await contractWrappers.erc20Token.getBalanceAsync(makerTokenAddress, makerAddress); - // Change maker balance to have less than the order amount - const remainingBalance = makerBalance.minus(signedOrder.makerAssetAmount.minus(1)); - await web3Wrapper.awaitTransactionSuccessAsync( - await contractWrappers.erc20Token.transferAsync( - makerTokenAddress, - makerAddress, - constants.NULL_ADDRESS, - remainingBalance, - ), - ); - // An amount is still transferrable - await contractWrappers.exchange.validateOrderFillableOrThrowAsync(signedOrder, { - validateRemainingOrderAmountIsFillable: false, - }); - }); - it('should throw when the ERC20 token has transfer restrictions', async () => { - const artifactDependencies = {}; - const untransferrableToken = await DummyERC20TokenContract.deployFrom0xArtifactAsync( - UntransferrableDummyERC20Token, - provider, - { from: userAddresses[0] }, - artifactDependencies, - 'UntransferrableToken', - 'UTT', - new BigNumber(constants.ZRX_DECIMALS), - // tslint:disable-next-line:custom-no-magic-numbers - new BigNumber(2).pow(20).minus(1), - ); - const untransferrableMakerAssetData = assetDataUtils.encodeERC20AssetData(untransferrableToken.address); - const invalidSignedOrder = await fillScenarios.createFillableSignedOrderAsync( - untransferrableMakerAssetData, - takerAssetData, - makerAddress, - takerAddress, - fillableAmount, - ); - await web3Wrapper.awaitTransactionSuccessAsync( - await contractWrappers.erc20Token.setProxyAllowanceAsync( - untransferrableToken.address, - makerAddress, - signedOrder.makerAssetAmount, - ), - ); - return expect( - contractWrappers.exchange.validateOrderFillableOrThrowAsync(invalidSignedOrder), - ).to.eventually.to.be.rejectedWith('TRANSFER_FAILED'); - }); - }); describe('#isValidSignature', () => { it('should check if the signature is valid', async () => { const orderHash = orderHashUtils.getOrderHashHex(signedOrder); - let isValid = await contractWrappers.exchange.isValidSignatureAsync( + let isValid = await contractWrappers.exchange.isValidSignature.callAsync( orderHash, signedOrder.makerAddress, signedOrder.signature, ); expect(isValid).to.be.true(); - isValid = await contractWrappers.exchange.isValidSignatureAsync( + isValid = await contractWrappers.exchange.isValidSignature.callAsync( orderHash, signedOrder.takerAddress, signedOrder.signature, @@ -404,7 +303,10 @@ describe('ExchangeWrapper', () => { it('should check if the validator is allowed', async () => { const signerAddress = makerAddress; const validatorAddress = constants.NULL_ADDRESS; - const isAllowed = await contractWrappers.exchange.isAllowedValidatorAsync(signerAddress, validatorAddress); + const isAllowed = await contractWrappers.exchange.allowedValidators.callAsync( + signerAddress, + validatorAddress, + ); expect(isAllowed).to.be.false(); }); }); @@ -413,52 +315,50 @@ describe('ExchangeWrapper', () => { const validatorAddress = constants.NULL_ADDRESS; const isApproved = true; const senderAddress = makerAddress; - txHash = await contractWrappers.exchange.setSignatureValidatorApprovalAsync( + await contractWrappers.exchange.setSignatureValidatorApproval.awaitTransactionSuccessAsync( validatorAddress, isApproved, - senderAddress, + { from: senderAddress }, ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); }); }); describe('#isTransactionExecutedAsync', () => { it('should check if the transaction is executed', async () => { const transactionHash = '0x0000000000000000000000000000000000000000000000000000000000000000'; - const isExecuted = await contractWrappers.exchange.isTransactionExecutedAsync(transactionHash); + const isExecuted = await contractWrappers.exchange.transactions.callAsync(transactionHash); expect(isExecuted).to.be.false(); }); }); describe('#getAssetProxyBySignatureAsync', () => { it('should fill or kill a valid order', async () => { - const erc20ProxyId = await contractWrappers.erc20Proxy.getProxyIdAsync(); - const erc20ProxyAddressById = await contractWrappers.exchange.getAssetProxyBySignatureAsync(erc20ProxyId); + const erc20ProxyId = await contractWrappers.erc20Proxy.getProxyId.callAsync(); + const erc20ProxyAddressById = await contractWrappers.exchange.getAssetProxy.callAsync(erc20ProxyId); const erc20ProxyAddress = contractWrappers.erc20Proxy.address; expect(erc20ProxyAddressById).to.be.equal(erc20ProxyAddress); - const erc721ProxyId = await contractWrappers.erc721Proxy.getProxyIdAsync(); - const erc721ProxyAddressById = await contractWrappers.exchange.getAssetProxyBySignatureAsync(erc721ProxyId); + const erc721ProxyId = await contractWrappers.erc721Proxy.getProxyId.callAsync(); + const erc721ProxyAddressById = await contractWrappers.exchange.getAssetProxy.callAsync(erc721ProxyId); const erc721ProxyAddress = contractWrappers.erc721Proxy.address; expect(erc721ProxyAddressById).to.be.equal(erc721ProxyAddress); }); }); - describe('#preSignAsync/isPreSignedAsync', () => { + describe('#preSign/isPresigned', () => { it('should preSign the hash', async () => { const senderAddress = takerAddress; const hash = orderHashUtils.getOrderHashHex(signedOrder); const signerAddress = signedOrder.makerAddress; - let isPreSigned = await contractWrappers.exchange.isPreSignedAsync(hash, signerAddress); + let isPreSigned = await contractWrappers.exchange.preSigned.callAsync(hash, signerAddress); expect(isPreSigned).to.be.false(); - txHash = await contractWrappers.exchange.preSignAsync( + await contractWrappers.exchange.preSign.awaitTransactionSuccessAsync( hash, signerAddress, signedOrder.signature, - senderAddress, + { from: senderAddress }, ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - isPreSigned = await contractWrappers.exchange.isPreSignedAsync(hash, signerAddress); + isPreSigned = await contractWrappers.exchange.preSigned.callAsync(hash, signerAddress); expect(isPreSigned).to.be.true(); const preSignedSignature = '0x06'; - const isValidSignature = await contractWrappers.exchange.isValidSignatureAsync( + const isValidSignature = await contractWrappers.exchange.isValidSignature.callAsync( hash, signerAddress, preSignedSignature, @@ -477,7 +377,7 @@ describe('ExchangeWrapper', () => { }); describe('#getVersionAsync', () => { it('should return version the hash', async () => { - const version = await contractWrappers.exchange.getVersionAsync(); + const version = await contractWrappers.exchange.VERSION.callAsync(); const VERSION = '2.0.0'; expect(version).to.be.equal(VERSION); }); @@ -510,10 +410,11 @@ describe('ExchangeWrapper', () => { }, ); contractWrappers.exchange.subscribe(ExchangeEvents.Fill, indexFilterValues, callback); - await contractWrappers.exchange.fillOrderAsync( + await contractWrappers.exchange.fillOrder.awaitTransactionSuccessAsync( signedOrder, takerTokenFillAmountInBaseUnits, - takerAddress, + signedOrder.signature, + { from: takerAddress }, ); })().catch(done); }); @@ -525,7 +426,9 @@ describe('ExchangeWrapper', () => { }, ); contractWrappers.exchange.subscribe(ExchangeEvents.Cancel, indexFilterValues, callback); - await contractWrappers.exchange.cancelOrderAsync(signedOrder); + await contractWrappers.exchange.cancelOrder.awaitTransactionSuccessAsync(signedOrder, { + from: makerAddress, + }); })().catch(done); }); it('Outstanding subscriptions are cancelled when contractWrappers.unsubscribeAll called', (done: DoneCallback) => { @@ -545,10 +448,11 @@ describe('ExchangeWrapper', () => { }, ); contractWrappers.exchange.subscribe(ExchangeEvents.Fill, indexFilterValues, callback); - await contractWrappers.exchange.fillOrderAsync( + await contractWrappers.exchange.fillOrder.awaitTransactionSuccessAsync( signedOrder, takerTokenFillAmountInBaseUnits, - takerAddress, + signedOrder.signature, + { from: takerAddress }, ); })().catch(done); }); @@ -565,10 +469,11 @@ describe('ExchangeWrapper', () => { callbackNeverToBeCalled, ); contractWrappers.exchange.unsubscribe(subscriptionToken); - await contractWrappers.exchange.fillOrderAsync( + await contractWrappers.exchange.fillOrder.awaitTransactionSuccessAsync( signedOrder, takerTokenFillAmountInBaseUnits, - takerAddress, + signedOrder.signature, + { from: takerAddress }, ); done(); })().catch(done); @@ -580,7 +485,12 @@ describe('ExchangeWrapper', () => { toBlock: BlockParamLiteral.Latest, }; it('should get logs with decoded args emitted by Fill', async () => { - txHash = await contractWrappers.exchange.fillOrderAsync(signedOrder, takerTokenFillAmount, takerAddress); + await contractWrappers.exchange.fillOrder.awaitTransactionSuccessAsync( + signedOrder, + takerTokenFillAmount, + signedOrder.signature, + { from: takerAddress }, + ); const eventName = ExchangeEvents.Fill; const indexFilterValues = {}; const logs = await contractWrappers.exchange.getLogsAsync(eventName, blockRange, indexFilterValues); @@ -588,8 +498,12 @@ describe('ExchangeWrapper', () => { expect(logs[0].event).to.be.equal(eventName); }); it('should only get the logs with the correct event name', async () => { - txHash = await contractWrappers.exchange.fillOrderAsync(signedOrder, takerTokenFillAmount, takerAddress); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); + await contractWrappers.exchange.fillOrder.awaitTransactionSuccessAsync( + signedOrder, + takerTokenFillAmount, + signedOrder.signature, + { from: takerAddress }, + ); const differentEventName = ExchangeEvents.Cancel; const indexFilterValues = {}; const logs = await contractWrappers.exchange.getLogsAsync( @@ -600,8 +514,12 @@ describe('ExchangeWrapper', () => { expect(logs).to.have.length(0); }); it('should only get the logs with the correct indexed fields', async () => { - txHash = await contractWrappers.exchange.fillOrderAsync(signedOrder, takerTokenFillAmount, takerAddress); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); + await contractWrappers.exchange.fillOrder.awaitTransactionSuccessAsync( + signedOrder, + takerTokenFillAmount, + signedOrder.signature, + { from: takerAddress }, + ); const signedOrderWithAnotherMakerAddress = await fillScenarios.createFillableSignedOrderAsync( makerAssetData, takerAssetData, @@ -609,13 +527,12 @@ describe('ExchangeWrapper', () => { takerAddress, fillableAmount, ); - txHash = await contractWrappers.exchange.fillOrderAsync( + await contractWrappers.exchange.fillOrder.awaitTransactionSuccessAsync( signedOrderWithAnotherMakerAddress, takerTokenFillAmount, - takerAddress, + signedOrderWithAnotherMakerAddress.signature, + { from: takerAddress }, ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - const eventName = ExchangeEvents.Fill; const indexFilterValues = { makerAddress: anotherMakerAddress, diff --git a/packages/contract-wrappers/test/forwarder_wrapper_test.ts b/packages/contract-wrappers/test/forwarder_wrapper_test.ts deleted file mode 100644 index 0d197eced8..0000000000 --- a/packages/contract-wrappers/test/forwarder_wrapper_test.ts +++ /dev/null @@ -1,167 +0,0 @@ -import { BlockchainLifecycle } from '@0x/dev-utils'; -import { FillScenarios } from '@0x/fill-scenarios'; -import { assetDataUtils } from '@0x/order-utils'; -import { SignedOrder } from '@0x/types'; -import { BigNumber } from '@0x/utils'; -import * as chai from 'chai'; -import 'mocha'; - -import { ContractWrappers, OrderStatus } from '../src'; - -import { chaiSetup } from './utils/chai_setup'; -import { constants } from './utils/constants'; -import { migrateOnceAsync } from './utils/migrate'; -import { tokenUtils } from './utils/token_utils'; -import { provider, web3Wrapper } from './utils/web3_wrapper'; - -chaiSetup.configure(); -const expect = chai.expect; -const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper); - -// tslint:disable:custom-no-magic-numbers -describe('ForwarderWrapper', () => { - const fillableAmount = new BigNumber(5); - let contractWrappers: ContractWrappers; - let fillScenarios: FillScenarios; - let exchangeContractAddress: string; - let zrxTokenAddress: string; - let userAddresses: string[]; - let makerAddress: string; - let takerAddress: string; - let makerTokenAddress: string; - let takerTokenAddress: string; - let makerAssetData: string; - let takerAssetData: string; - let signedOrder: SignedOrder; - let anotherSignedOrder: SignedOrder; - before(async () => { - const contractAddresses = await migrateOnceAsync(); - await blockchainLifecycle.startAsync(); - const config = { - networkId: constants.TESTRPC_NETWORK_ID, - contractAddresses, - blockPollingIntervalMs: 10, - }; - contractWrappers = new ContractWrappers(provider, config); - exchangeContractAddress = contractWrappers.exchange.address; - userAddresses = await web3Wrapper.getAvailableAddressesAsync(); - zrxTokenAddress = contractWrappers.exchange.zrxTokenAddress; - fillScenarios = new FillScenarios( - provider, - userAddresses, - zrxTokenAddress, - exchangeContractAddress, - contractWrappers.erc20Proxy.address, - contractWrappers.erc721Proxy.address, - ); - [, makerAddress, takerAddress] = userAddresses; - [makerTokenAddress] = tokenUtils.getDummyERC20TokenAddresses(); - takerTokenAddress = contractWrappers.forwarder.etherTokenAddress; - [makerAssetData, takerAssetData] = [ - assetDataUtils.encodeERC20AssetData(makerTokenAddress), - assetDataUtils.encodeERC20AssetData(takerTokenAddress), - ]; - signedOrder = await fillScenarios.createFillableSignedOrderAsync( - makerAssetData, - takerAssetData, - makerAddress, - constants.NULL_ADDRESS, - fillableAmount, - ); - anotherSignedOrder = await fillScenarios.createFillableSignedOrderAsync( - makerAssetData, - takerAssetData, - makerAddress, - constants.NULL_ADDRESS, - fillableAmount, - ); - }); - after(async () => { - await blockchainLifecycle.revertAsync(); - }); - beforeEach(async () => { - await blockchainLifecycle.startAsync(); - }); - afterEach(async () => { - await blockchainLifecycle.revertAsync(); - }); - describe('#marketBuyOrdersWithEthAsync', () => { - it('should market buy orders with eth', async () => { - const signedOrders = [signedOrder, anotherSignedOrder]; - const makerAssetFillAmount = signedOrder.makerAssetAmount.plus(anotherSignedOrder.makerAssetAmount); - const txHash = await contractWrappers.forwarder.marketBuyOrdersWithEthAsync( - signedOrders, - makerAssetFillAmount, - takerAddress, - makerAssetFillAmount, - ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - const ordersInfo = await contractWrappers.exchange.getOrdersInfoAsync([signedOrder, anotherSignedOrder]); - expect(ordersInfo[0].orderStatus).to.be.equal(OrderStatus.FullyFilled); - expect(ordersInfo[1].orderStatus).to.be.equal(OrderStatus.FullyFilled); - }); - it('should throw when invalid transaction and shouldValidate is true', async () => { - const signedOrders = [signedOrder]; - // request more makerAsset than what is available - const makerAssetFillAmount = signedOrder.makerAssetAmount.plus(100); - return expect( - contractWrappers.forwarder.marketBuyOrdersWithEthAsync( - signedOrders, - makerAssetFillAmount, - takerAddress, - makerAssetFillAmount, - [], - 0, - constants.NULL_ADDRESS, - { - shouldValidate: true, - }, - ), - ).to.be.rejectedWith('COMPLETE_FILL_FAILED'); - }); - }); - describe('#marketSellOrdersWithEthAsync', () => { - it('should market sell orders with eth', async () => { - const signedOrders = [signedOrder, anotherSignedOrder]; - const makerAssetFillAmount = signedOrder.makerAssetAmount.plus(anotherSignedOrder.makerAssetAmount); - const txHash = await contractWrappers.forwarder.marketSellOrdersWithEthAsync( - signedOrders, - takerAddress, - makerAssetFillAmount, - ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - const ordersInfo = await contractWrappers.exchange.getOrdersInfoAsync([signedOrder, anotherSignedOrder]); - expect(ordersInfo[0].orderStatus).to.be.equal(OrderStatus.FullyFilled); - expect(ordersInfo[1].orderStatus).to.be.equal(OrderStatus.Fillable); - expect(ordersInfo[1].orderTakerAssetFilledAmount).to.be.bignumber.equal(new BigNumber(4)); // only 95% of ETH is sold - }); - it('should throw when invalid transaction and shouldValidate is true', async () => { - // create an order with fees, we try to fill it but we do not provide enough ETH to cover the fees - const signedOrderWithFee = await fillScenarios.createFillableSignedOrderWithFeesAsync( - makerAssetData, - takerAssetData, - constants.ZERO_AMOUNT, - new BigNumber(100), - makerAddress, - constants.NULL_ADDRESS, - fillableAmount, - constants.NULL_ADDRESS, - ); - const signedOrders = [signedOrderWithFee]; - const makerAssetFillAmount = signedOrder.makerAssetAmount; - return expect( - contractWrappers.forwarder.marketSellOrdersWithEthAsync( - signedOrders, - takerAddress, - makerAssetFillAmount, - [], - 0, - constants.NULL_ADDRESS, - { - shouldValidate: true, - }, - ), - ).to.be.rejectedWith('COMPLETE_FILL_FAILED'); - }); - }); -}); diff --git a/packages/contract-wrappers/test/order_validator_wrapper_test.ts b/packages/contract-wrappers/test/order_validator_wrapper_test.ts deleted file mode 100644 index c61c05d312..0000000000 --- a/packages/contract-wrappers/test/order_validator_wrapper_test.ts +++ /dev/null @@ -1,146 +0,0 @@ -import { ContractAddresses } from '@0x/contract-addresses'; -import { BlockchainLifecycle } from '@0x/dev-utils'; -import { FillScenarios } from '@0x/fill-scenarios'; -import { assetDataUtils } from '@0x/order-utils'; -import { SignedOrder } from '@0x/types'; -import { BigNumber } from '@0x/utils'; -import * as chai from 'chai'; -import * as _ from 'lodash'; -import 'mocha'; - -import { ContractWrappers, OrderStatus } from '../src'; -import { OrderInfo, TraderInfo } from '../src/types'; - -import { chaiSetup } from './utils/chai_setup'; -import { constants } from './utils/constants'; -import { migrateOnceAsync } from './utils/migrate'; -import { tokenUtils } from './utils/token_utils'; -import { provider, web3Wrapper } from './utils/web3_wrapper'; - -chaiSetup.configure(); -const expect = chai.expect; -const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper); - -describe('OrderValidator', () => { - const fillableAmount = new BigNumber(5); - let contractWrappers: ContractWrappers; - let fillScenarios: FillScenarios; - let exchangeContractAddress: string; - let zrxTokenAddress: string; - let zrxTokenAssetData: string; - let userAddresses: string[]; - let coinbase: string; - let makerAddress: string; - let takerAddress: string; - let feeRecipient: string; - let anotherMakerAddress: string; - let makerTokenAddress: string; - let takerTokenAddress: string; - let makerAssetData: string; - let takerAssetData: string; - let signedOrder: SignedOrder; - let anotherSignedOrder: SignedOrder; - let contractAddresses: ContractAddresses; - - before(async () => { - contractAddresses = await migrateOnceAsync(); - await blockchainLifecycle.startAsync(); - const config = { - networkId: constants.TESTRPC_NETWORK_ID, - contractAddresses, - blockPollingIntervalMs: 10, - }; - contractWrappers = new ContractWrappers(provider, config); - exchangeContractAddress = contractWrappers.exchange.address; - userAddresses = await web3Wrapper.getAvailableAddressesAsync(); - zrxTokenAddress = contractWrappers.exchange.zrxTokenAddress; - zrxTokenAssetData = assetDataUtils.encodeERC20AssetData(zrxTokenAddress); - fillScenarios = new FillScenarios( - provider, - userAddresses, - zrxTokenAddress, - exchangeContractAddress, - contractWrappers.erc20Proxy.address, - contractWrappers.erc721Proxy.address, - ); - [coinbase, makerAddress, takerAddress, feeRecipient, anotherMakerAddress] = userAddresses; - [makerTokenAddress] = tokenUtils.getDummyERC20TokenAddresses(); - takerTokenAddress = contractAddresses.etherToken; - [makerAssetData, takerAssetData] = [ - assetDataUtils.encodeERC20AssetData(makerTokenAddress), - assetDataUtils.encodeERC20AssetData(takerTokenAddress), - ]; - - signedOrder = await fillScenarios.createFillableSignedOrderAsync( - makerAssetData, - takerAssetData, - makerAddress, - constants.NULL_ADDRESS, - fillableAmount, - ); - anotherSignedOrder = await fillScenarios.createFillableSignedOrderAsync( - zrxTokenAssetData, - takerAssetData, - makerAddress, - constants.NULL_ADDRESS, - fillableAmount, - ); - }); - after(async () => { - await blockchainLifecycle.revertAsync(); - }); - beforeEach(async () => { - await blockchainLifecycle.startAsync(); - }); - afterEach(async () => { - await blockchainLifecycle.revertAsync(); - }); - describe('#getOrdersAndTradersInfoAsync', () => { - let signedOrders: SignedOrder[]; - let takerAddresses: string[]; - let ordersInfo: OrderInfo[]; - let tradersInfo: TraderInfo[]; - beforeEach(async () => { - signedOrders = [signedOrder, anotherSignedOrder]; - takerAddresses = [takerAddress, takerAddress]; - const ordersAndTradersInfo = await contractWrappers.orderValidator.getOrdersAndTradersInfoAsync( - signedOrders, - takerAddresses, - ); - ordersInfo = _.map(ordersAndTradersInfo, orderAndTraderInfo => orderAndTraderInfo.orderInfo); - tradersInfo = _.map(ordersAndTradersInfo, orderAndTraderInfo => orderAndTraderInfo.traderInfo); - }); - it('should return the same number of order infos and trader infos as input orders', async () => { - expect(ordersInfo.length).to.be.equal(signedOrders.length); - expect(tradersInfo.length).to.be.equal(takerAddresses.length); - }); - it('should return correct on-chain order info for input orders', async () => { - const firstOrderInfo = ordersInfo[0]; - const secondOrderInfo = ordersInfo[1]; - expect(firstOrderInfo.orderStatus).to.be.equal(OrderStatus.Fillable); - expect(firstOrderInfo.orderTakerAssetFilledAmount).to.bignumber.equal(constants.ZERO_AMOUNT); - expect(secondOrderInfo.orderStatus).to.be.equal(OrderStatus.Fillable); - expect(secondOrderInfo.orderTakerAssetFilledAmount).to.bignumber.equal(constants.ZERO_AMOUNT); - }); - it('should return correct on-chain trader info for input takers', async () => { - const firstTraderInfo = tradersInfo[0]; - const secondTraderInfo = tradersInfo[1]; - expect(firstTraderInfo.makerBalance).to.bignumber.equal(new BigNumber(5)); - expect(firstTraderInfo.makerAllowance).to.bignumber.equal(new BigNumber(5)); - expect(firstTraderInfo.takerBalance).to.bignumber.equal(new BigNumber(0)); - expect(firstTraderInfo.takerAllowance).to.bignumber.equal(new BigNumber(0)); - expect(firstTraderInfo.makerZrxBalance).to.bignumber.equal(new BigNumber(5)); - expect(firstTraderInfo.makerZrxAllowance).to.bignumber.equal(new BigNumber(5)); - expect(firstTraderInfo.takerZrxBalance).to.bignumber.equal(new BigNumber(0)); - expect(firstTraderInfo.takerZrxAllowance).to.bignumber.equal(new BigNumber(0)); - expect(secondTraderInfo.makerBalance).to.bignumber.equal(new BigNumber(5)); - expect(secondTraderInfo.makerAllowance).to.bignumber.equal(new BigNumber(5)); - expect(secondTraderInfo.takerBalance).to.bignumber.equal(new BigNumber(0)); - expect(secondTraderInfo.takerAllowance).to.bignumber.equal(new BigNumber(0)); - expect(secondTraderInfo.makerZrxBalance).to.bignumber.equal(new BigNumber(5)); - expect(secondTraderInfo.makerZrxAllowance).to.bignumber.equal(new BigNumber(5)); - expect(secondTraderInfo.takerZrxBalance).to.bignumber.equal(new BigNumber(0)); - expect(secondTraderInfo.takerZrxAllowance).to.bignumber.equal(new BigNumber(0)); - }); - }); -}); diff --git a/packages/contract-wrappers/test/revert_validation_test.ts b/packages/contract-wrappers/test/revert_validation_test.ts deleted file mode 100644 index efd5dd61f1..0000000000 --- a/packages/contract-wrappers/test/revert_validation_test.ts +++ /dev/null @@ -1,115 +0,0 @@ -import { BlockchainLifecycle, devConstants, web3Factory } from '@0x/dev-utils'; -import { FillScenarios } from '@0x/fill-scenarios'; -import { runMigrationsAsync } from '@0x/migrations'; -import { assetDataUtils } from '@0x/order-utils'; -import { SignedOrder } from '@0x/types'; -import { BigNumber } from '@0x/utils'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import * as chai from 'chai'; -import 'mocha'; - -import { ContractWrappers } from '../src'; - -import { chaiSetup } from './utils/chai_setup'; -import { constants } from './utils/constants'; -import { tokenUtils } from './utils/token_utils'; - -chaiSetup.configure(); -const expect = chai.expect; - -describe('Revert Validation ExchangeWrapper', () => { - let contractWrappers: ContractWrappers; - let userAddresses: string[]; - let fillScenarios: FillScenarios; - let makerTokenAddress: string; - let takerTokenAddress: string; - let makerAddress: string; - let takerAddress: string; - let makerAssetData: string; - let takerAssetData: string; - let txHash: string; - let blockchainLifecycle: BlockchainLifecycle; - let web3Wrapper: Web3Wrapper; - const fillableAmount = new BigNumber(5); - const takerTokenFillAmount = new BigNumber(5); - let signedOrder: SignedOrder; - before(async () => { - // vmErrorsOnRPCResponse is useful for quick feedback and testing during development - // but is not the default behaviour in production. Here we ensure our failure cases - // are handled in an environment which behaves similar to production - const provider = web3Factory.getRpcProvider({ - shouldUseInProcessGanache: true, - shouldThrowErrorsOnGanacheRPCResponse: false, - }); - web3Wrapper = new Web3Wrapper(provider); - blockchainLifecycle = new BlockchainLifecycle(web3Wrapper); - // Re-deploy the artifacts in this provider, rather than in the default provider exposed in - // the beforeAll hook. This is due to the fact that the default provider enabled vmErrorsOnRPCResponse - // and we are explicity testing with vmErrorsOnRPCResponse disabled. - const txDefaults = { - gas: devConstants.GAS_LIMIT, - from: devConstants.TESTRPC_FIRST_ADDRESS, - }; - await blockchainLifecycle.startAsync(); - const contractAddresses = await runMigrationsAsync(provider, txDefaults); - const config = { - networkId: constants.TESTRPC_NETWORK_ID, - contractAddresses, - blockPollingIntervalMs: 10, - }; - contractWrappers = new ContractWrappers(provider, config); - userAddresses = await web3Wrapper.getAvailableAddressesAsync(); - fillScenarios = new FillScenarios( - provider, - userAddresses, - contractAddresses.zrxToken, - contractAddresses.exchange, - contractAddresses.erc20Proxy, - contractAddresses.erc721Proxy, - ); - [, makerAddress, takerAddress] = userAddresses; - [makerTokenAddress, takerTokenAddress] = tokenUtils.getDummyERC20TokenAddresses(); - [makerAssetData, takerAssetData] = [ - assetDataUtils.encodeERC20AssetData(makerTokenAddress), - assetDataUtils.encodeERC20AssetData(takerTokenAddress), - ]; - signedOrder = await fillScenarios.createFillableSignedOrderAsync( - makerAssetData, - takerAssetData, - makerAddress, - takerAddress, - fillableAmount, - ); - }); - after(async () => { - await blockchainLifecycle.revertAsync(); - }); - beforeEach(async () => { - await blockchainLifecycle.startAsync(); - }); - afterEach(async () => { - await blockchainLifecycle.revertAsync(); - }); - describe('#fillOrderAsync', () => { - it('should throw the revert reason when shouldValidate is true and a fill would revert', async () => { - // Create a scenario where the fill will revert - const makerTokenBalance = await contractWrappers.erc20Token.getBalanceAsync( - makerTokenAddress, - makerAddress, - ); - // Transfer all of the tokens from maker to create a failure scenario - txHash = await contractWrappers.erc20Token.transferAsync( - makerTokenAddress, - makerAddress, - takerAddress, - makerTokenBalance, - ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - return expect( - contractWrappers.exchange.fillOrderAsync(signedOrder, takerTokenFillAmount, takerAddress, { - shouldValidate: true, - }), - ).to.be.rejectedWith('TRANSFER_FAILED'); - }); - }); -}); diff --git a/packages/contract-wrappers/test/subscription_test.ts b/packages/contract-wrappers/test/subscription_test.ts deleted file mode 100644 index 0fa6af40d1..0000000000 --- a/packages/contract-wrappers/test/subscription_test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { BlockchainLifecycle } from '@0x/dev-utils'; -import { DoneCallback } from '@0x/types'; -import * as _ from 'lodash'; -import 'mocha'; -import * as Sinon from 'sinon'; - -import { - ContractWrappers, - ContractWrappersConfig, - DecodedLogEvent, - ERC20TokenApprovalEventArgs, - ERC20TokenEvents, -} from '../src'; - -import { chaiSetup } from './utils/chai_setup'; -import { constants } from './utils/constants'; -import { migrateOnceAsync } from './utils/migrate'; -import { tokenUtils } from './utils/token_utils'; -import { provider, web3Wrapper } from './utils/web3_wrapper'; - -chaiSetup.configure(); -const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper); - -describe('SubscriptionTest', () => { - let contractWrappers: ContractWrappers; - let config: ContractWrappersConfig; - - before(async () => { - const contractAddresses = await migrateOnceAsync(); - config = { - networkId: constants.TESTRPC_NETWORK_ID, - contractAddresses, - }; - contractWrappers = new ContractWrappers(provider, config); - }); - beforeEach(async () => { - await blockchainLifecycle.startAsync(); - }); - afterEach(async () => { - await blockchainLifecycle.revertAsync(); - }); - describe('#subscribe', () => { - const indexFilterValues = {}; - let tokenAddress: string; - let stubs: Sinon.SinonStub[] = []; - before(() => { - const tokenAddresses = tokenUtils.getDummyERC20TokenAddresses(); - tokenAddress = tokenAddresses[0]; - }); - afterEach(() => { - contractWrappers.erc20Token.unsubscribeAll(); - _.each(stubs, s => s.restore()); - stubs = []; - }); - it('Should allow unsubscribeAll to be called successfully after an error', (done: DoneCallback) => { - (async () => { - const callback = (err: Error | null, _logEvent?: DecodedLogEvent) => - _.noop.bind(_); - contractWrappers.erc20Token.subscribe( - tokenAddress, - ERC20TokenEvents.Approval, - indexFilterValues, - callback, - ); - stubs = [ - Sinon.stub((contractWrappers as any)._web3Wrapper, 'getBlockIfExistsAsync').throws( - new Error('JSON RPC error'), - ), - ]; - contractWrappers.erc20Token.unsubscribeAll(); - done(); - })().catch(done); - }); - }); -}); diff --git a/packages/contract-wrappers/test/transaction_encoder_test.ts b/packages/contract-wrappers/test/transaction_encoder_test.ts deleted file mode 100644 index a996b9f088..0000000000 --- a/packages/contract-wrappers/test/transaction_encoder_test.ts +++ /dev/null @@ -1,210 +0,0 @@ -import { BlockchainLifecycle } from '@0x/dev-utils'; -import { FillScenarios } from '@0x/fill-scenarios'; -import { assetDataUtils, generatePseudoRandomSalt, orderHashUtils, signatureUtils } from '@0x/order-utils'; -import { SignedOrder } from '@0x/types'; -import { BigNumber } from '@0x/utils'; -import 'mocha'; - -import { ContractWrappers } from '../src'; -import { TransactionEncoder } from '../src/utils/transaction_encoder'; - -import { constants } from './utils/constants'; -import { migrateOnceAsync } from './utils/migrate'; -import { tokenUtils } from './utils/token_utils'; -import { provider, web3Wrapper } from './utils/web3_wrapper'; - -const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper); - -describe('TransactionEncoder', () => { - let contractWrappers: ContractWrappers; - let userAddresses: string[]; - let fillScenarios: FillScenarios; - let exchangeContractAddress: string; - let makerTokenAddress: string; - let takerTokenAddress: string; - let coinbase: string; - let makerAddress: string; - let senderAddress: string; - let takerAddress: string; - let makerAssetData: string; - let takerAssetData: string; - let txHash: string; - const fillableAmount = new BigNumber(5); - const takerTokenFillAmount = new BigNumber(5); - let signedOrder: SignedOrder; - - before(async () => { - const contractAddresses = await migrateOnceAsync(); - await blockchainLifecycle.startAsync(); - const config = { - networkId: constants.TESTRPC_NETWORK_ID, - contractAddresses, - blockPollingIntervalMs: 10, - }; - contractWrappers = new ContractWrappers(provider, config); - exchangeContractAddress = contractWrappers.exchange.address; - userAddresses = await web3Wrapper.getAvailableAddressesAsync(); - const zrxTokenAddress = contractWrappers.exchange.zrxTokenAddress; - fillScenarios = new FillScenarios( - provider, - userAddresses, - zrxTokenAddress, - exchangeContractAddress, - contractWrappers.erc20Proxy.address, - contractWrappers.erc721Proxy.address, - ); - [coinbase, makerAddress, takerAddress, senderAddress] = userAddresses; - [makerTokenAddress, takerTokenAddress] = tokenUtils.getDummyERC20TokenAddresses(); - [makerAssetData, takerAssetData] = [ - assetDataUtils.encodeERC20AssetData(makerTokenAddress), - assetDataUtils.encodeERC20AssetData(takerTokenAddress), - ]; - signedOrder = await fillScenarios.createFillableSignedOrderAsync( - makerAssetData, - takerAssetData, - makerAddress, - takerAddress, - fillableAmount, - ); - }); - after(async () => { - await blockchainLifecycle.revertAsync(); - }); - beforeEach(async () => { - await blockchainLifecycle.startAsync(); - }); - afterEach(async () => { - await blockchainLifecycle.revertAsync(); - }); - describe('encode and executeTransaction', () => { - const executeTransactionOrThrowAsync = async ( - encoder: TransactionEncoder, - data: string, - signerAddress: string = takerAddress, - ): Promise => { - const salt = generatePseudoRandomSalt(); - const transactionHash = encoder.getTransactionHashHex(data, salt, signerAddress); - const signature = await signatureUtils.ecSignHashAsync(provider, transactionHash, signerAddress); - txHash = await contractWrappers.exchange.executeTransactionAsync( - salt, - signerAddress, - data, - signature, - senderAddress, - ); - await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - }; - describe('#fillOrderTx', () => { - it('should successfully execute the transaction', async () => { - const encoder = await contractWrappers.exchange.transactionEncoderAsync(); - const data = encoder.fillOrderTx(signedOrder, takerTokenFillAmount); - await executeTransactionOrThrowAsync(encoder, data); - }); - }); - describe('#fillOrderNoThrowTx', () => { - it('should successfully execute the transaction', async () => { - const encoder = await contractWrappers.exchange.transactionEncoderAsync(); - const data = encoder.fillOrderNoThrowTx(signedOrder, takerTokenFillAmount); - await executeTransactionOrThrowAsync(encoder, data); - }); - }); - describe('#fillOrKillOrderTx', () => { - it('should successfully execute the transaction', async () => { - const encoder = await contractWrappers.exchange.transactionEncoderAsync(); - const data = encoder.fillOrKillOrderTx(signedOrder, takerTokenFillAmount); - await executeTransactionOrThrowAsync(encoder, data); - }); - }); - describe('#marketSellOrdersTx', () => { - it('should successfully execute the transaction', async () => { - const encoder = await contractWrappers.exchange.transactionEncoderAsync(); - const data = encoder.marketSellOrdersTx([signedOrder], takerTokenFillAmount); - await executeTransactionOrThrowAsync(encoder, data); - }); - }); - describe('#marketSellOrdersNoThrowTx', () => { - it('should successfully execute the transaction', async () => { - const encoder = await contractWrappers.exchange.transactionEncoderAsync(); - const data = encoder.marketSellOrdersNoThrowTx([signedOrder], takerTokenFillAmount); - await executeTransactionOrThrowAsync(encoder, data); - }); - }); - describe('#marketBuyOrdersTx', () => { - it('should successfully execute the transaction', async () => { - const encoder = await contractWrappers.exchange.transactionEncoderAsync(); - const data = encoder.marketBuyOrdersTx([signedOrder], fillableAmount); - await executeTransactionOrThrowAsync(encoder, data); - }); - }); - describe('#marketBuyOrdersNoThrowTx', () => { - it('should successfully execute the transaction', async () => { - const encoder = await contractWrappers.exchange.transactionEncoderAsync(); - const data = encoder.marketBuyOrdersNoThrowTx([signedOrder], fillableAmount); - await executeTransactionOrThrowAsync(encoder, data); - }); - }); - describe('#preSignTx', () => { - it('should successfully execute the transaction', async () => { - const encoder = await contractWrappers.exchange.transactionEncoderAsync(); - const orderHash = orderHashUtils.getOrderHashHex(signedOrder); - const signature = signedOrder.signature; - const data = encoder.preSignTx(orderHash, makerAddress, signature); - await executeTransactionOrThrowAsync(encoder, data); - }); - }); - describe('#setSignatureValidatorApprovalTx', () => { - it('should successfully execute the transaction', async () => { - const encoder = await contractWrappers.exchange.transactionEncoderAsync(); - const isApproved = true; - const data = encoder.setSignatureValidatorApprovalTx(senderAddress, isApproved); - await executeTransactionOrThrowAsync(encoder, data); - }); - }); - describe('#batchFillOrdersTx', () => { - it('should successfully execute the transaction', async () => { - const encoder = await contractWrappers.exchange.transactionEncoderAsync(); - const data = encoder.batchFillOrdersTx([signedOrder], [takerTokenFillAmount]); - await executeTransactionOrThrowAsync(encoder, data); - }); - }); - describe('#batchFillOrKillOrdersTx', () => { - it('should successfully execute the transaction', async () => { - const encoder = await contractWrappers.exchange.transactionEncoderAsync(); - const data = encoder.batchFillOrKillOrdersTx([signedOrder], [takerTokenFillAmount]); - await executeTransactionOrThrowAsync(encoder, data); - }); - }); - describe('#batchFillOrdersNoThrowTx', () => { - it('should successfully execute the transaction', async () => { - const encoder = await contractWrappers.exchange.transactionEncoderAsync(); - const data = encoder.batchFillOrdersNoThrowTx([signedOrder], [takerTokenFillAmount]); - await executeTransactionOrThrowAsync(encoder, data); - }); - }); - describe('#batchCancelOrdersTx', () => { - it('should successfully execute the transaction', async () => { - const encoder = await contractWrappers.exchange.transactionEncoderAsync(); - const data = encoder.batchCancelOrdersTx([signedOrder]); - const signerAddress = makerAddress; - await executeTransactionOrThrowAsync(encoder, data, signerAddress); - }); - }); - describe('#cancelOrderTx', () => { - it('should successfully execute the transaction', async () => { - const encoder = await contractWrappers.exchange.transactionEncoderAsync(); - const data = encoder.cancelOrderTx(signedOrder); - const signerAddress = makerAddress; - await executeTransactionOrThrowAsync(encoder, data, signerAddress); - }); - }); - describe('#cancelOrdersUpToTx', () => { - it('should successfully execute the transaction', async () => { - const encoder = await contractWrappers.exchange.transactionEncoderAsync(); - const targetEpoch = signedOrder.salt; - const data = encoder.cancelOrdersUpToTx(targetEpoch); - const signerAddress = makerAddress; - await executeTransactionOrThrowAsync(encoder, data, signerAddress); - }); - }); - }); -}); diff --git a/packages/contract-wrappers/test/utils/dutch_auction_utils.ts b/packages/contract-wrappers/test/utils/dutch_auction_utils.ts deleted file mode 100644 index a7f11b3920..0000000000 --- a/packages/contract-wrappers/test/utils/dutch_auction_utils.ts +++ /dev/null @@ -1,150 +0,0 @@ -import { DummyERC20TokenContract } from '@0x/abi-gen-wrappers'; -import { assetDataUtils } from '@0x/order-utils'; -import { orderFactory } from '@0x/order-utils/lib/src/order_factory'; -import { SignedOrder } from '@0x/types'; -import { BigNumber } from '@0x/utils'; -import { Web3Wrapper } from '@0x/web3-wrapper'; - -import { DutchAuctionWrapper } from '../../src/contract_wrappers/dutch_auction_wrapper'; - -import { constants } from './constants'; - -export class DutchAuctionUtils { - private readonly _web3Wrapper: Web3Wrapper; - private readonly _coinbase: string; - private readonly _exchangeAddress: string; - private readonly _erc20ProxyAddress: string; - - constructor(web3Wrapper: Web3Wrapper, coinbase: string, exchangeAddress: string, erc20ProxyAddress: string) { - this._web3Wrapper = web3Wrapper; - this._coinbase = coinbase; - this._exchangeAddress = exchangeAddress; - this._erc20ProxyAddress = erc20ProxyAddress; - } - public async createSignedSellOrderAsync( - auctionBeginTimeSections: BigNumber, - acutionEndTimeSeconds: BigNumber, - auctionBeginTakerAssetAmount: BigNumber, - auctionEndTakerAssetAmount: BigNumber, - makerAssetAmount: BigNumber, - makerAssetData: string, - takerAssetData: string, - makerAddress: string, - takerAddress: string, - senderAddress?: string, - makerFee?: BigNumber, - takerFee?: BigNumber, - feeRecipientAddress?: string, - ): Promise { - // Notes on sell order: - // - The `takerAssetAmount` is set to the `auctionEndTakerAssetAmount`, which is the lowest amount the - // the seller can expect to receive - // - The `makerAssetData` is overloaded to include the auction begin time and begin taker asset amount - const makerAssetDataWithAuctionDetails = DutchAuctionWrapper.encodeDutchAuctionAssetData( - makerAssetData, - auctionBeginTimeSections, - auctionBeginTakerAssetAmount, - ); - const signedOrder = await orderFactory.createSignedOrderAsync( - this._web3Wrapper.getProvider(), - makerAddress, - makerAssetAmount, - makerAssetDataWithAuctionDetails, - auctionEndTakerAssetAmount, - takerAssetData, - this._exchangeAddress, - { - takerAddress, - senderAddress, - makerFee, - takerFee, - feeRecipientAddress, - expirationTimeSeconds: acutionEndTimeSeconds, - }, - ); - const erc20AssetData = assetDataUtils.decodeERC20AssetData(makerAssetData); - await this._increaseERC20BalanceAndAllowanceAsync(erc20AssetData.tokenAddress, makerAddress, makerAssetAmount); - return signedOrder; - } - public async createSignedBuyOrderAsync( - sellOrder: SignedOrder, - buyerAddress: string, - senderAddress?: string, - makerFee?: BigNumber, - takerFee?: BigNumber, - feeRecipientAddress?: string, - expirationTimeSeconds?: BigNumber, - ): Promise { - const dutchAuctionData = DutchAuctionWrapper.decodeDutchAuctionData(sellOrder.makerAssetData); - // Notes on buy order: - // - The `makerAssetAmount` is set to `dutchAuctionData.beginAmount`, which is - // the highest amount the buyer would have to pay out at any point during the auction. - // - The `takerAssetAmount` is set to the seller's `makerAssetAmount`, as the buyer - // receives the entire amount being sold by the seller. - // - The `makerAssetData`/`takerAssetData` are reversed from the sell order - const signedOrder = await orderFactory.createSignedOrderAsync( - this._web3Wrapper.getProvider(), - buyerAddress, - dutchAuctionData.beginAmount, - sellOrder.takerAssetData, - sellOrder.makerAssetAmount, - sellOrder.makerAssetData, - sellOrder.exchangeAddress, - { - senderAddress, - makerFee, - takerFee, - feeRecipientAddress, - expirationTimeSeconds, - }, - ); - const buyerERC20AssetData = assetDataUtils.decodeERC20AssetData(sellOrder.takerAssetData); - await this._increaseERC20BalanceAndAllowanceAsync( - buyerERC20AssetData.tokenAddress, - buyerAddress, - dutchAuctionData.beginAmount, - ); - return signedOrder; - } - private async _increaseERC20BalanceAndAllowanceAsync( - tokenAddress: string, - address: string, - amount: BigNumber, - ): Promise { - if (amount.isZero() || address === constants.NULL_ADDRESS) { - return; // noop - } - await Promise.all([ - this._increaseERC20BalanceAsync(tokenAddress, address, amount), - this._increaseERC20AllowanceAsync(tokenAddress, address, amount), - ]); - } - private async _increaseERC20BalanceAsync(tokenAddress: string, address: string, amount: BigNumber): Promise { - const erc20Token = new DummyERC20TokenContract( - tokenAddress, - this._web3Wrapper.getProvider(), - this._web3Wrapper.getContractDefaults(), - ); - const txHash = await erc20Token.transfer.sendTransactionAsync(address, amount, { - from: this._coinbase, - }); - await this._web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - } - private async _increaseERC20AllowanceAsync( - tokenAddress: string, - address: string, - amount: BigNumber, - ): Promise { - const erc20Token = new DummyERC20TokenContract( - tokenAddress, - this._web3Wrapper.getProvider(), - this._web3Wrapper.getContractDefaults(), - ); - const oldMakerAllowance = await erc20Token.allowance.callAsync(address, this._erc20ProxyAddress); - const newMakerAllowance = oldMakerAllowance.plus(amount); - const txHash = await erc20Token.approve.sendTransactionAsync(this._erc20ProxyAddress, newMakerAllowance, { - from: address, - }); - await this._web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - } -} diff --git a/packages/contract-wrappers/tsconfig.json b/packages/contract-wrappers/tsconfig.json index 2ee711adcc..03390d35cc 100644 --- a/packages/contract-wrappers/tsconfig.json +++ b/packages/contract-wrappers/tsconfig.json @@ -4,5 +4,6 @@ "outDir": "lib", "rootDir": "." }, - "include": ["./src/**/*", "./test/**/*"] + "include": ["./src/**/*", "./test/**/*"], + "exclude": ["node_modules"] } diff --git a/packages/contract-wrappers/typedoc-tsconfig.json b/packages/contract-wrappers/typedoc-tsconfig.json index c9b0af1ae6..a4c669cb6d 100644 --- a/packages/contract-wrappers/typedoc-tsconfig.json +++ b/packages/contract-wrappers/typedoc-tsconfig.json @@ -3,5 +3,5 @@ "compilerOptions": { "outDir": "lib" }, - "include": ["./src/**/*", "./test/**/*"] + "include": ["./src/**/*"] } diff --git a/packages/dev-utils/CHANGELOG.json b/packages/dev-utils/CHANGELOG.json index b585824eef..8f4e259934 100644 --- a/packages/dev-utils/CHANGELOG.json +++ b/packages/dev-utils/CHANGELOG.json @@ -1,4 +1,13 @@ [ + { + "version": "2.3.0", + "changes": [ + { + "note": "Move `tokenUtils` here from `@0x/contract-wrappers`", + "pr": 2037 + } + ] + }, { "timestamp": 1564604963, "version": "2.2.6", diff --git a/packages/dev-utils/src/index.ts b/packages/dev-utils/src/index.ts index d4c19f1bf2..5372501f2c 100644 --- a/packages/dev-utils/src/index.ts +++ b/packages/dev-utils/src/index.ts @@ -3,3 +3,4 @@ export { web3Factory } from './web3_factory'; export { constants as devConstants } from './constants'; export { env, EnvVars } from './env'; export { callbackErrorReporter } from './callback_error_reporter'; +export { tokenUtils } from './token_utils'; diff --git a/packages/dev-utils/src/token_utils.ts b/packages/dev-utils/src/token_utils.ts new file mode 100644 index 0000000000..1d4ee6b2ca --- /dev/null +++ b/packages/dev-utils/src/token_utils.ts @@ -0,0 +1,21 @@ +// 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/monorepo-scripts/src/doc_gen_configs.ts b/packages/monorepo-scripts/src/doc_gen_configs.ts index fa510b56e5..b7e23fb289 100644 --- a/packages/monorepo-scripts/src/doc_gen_configs.ts +++ b/packages/monorepo-scripts/src/doc_gen_configs.ts @@ -68,6 +68,11 @@ export const docGenConfigs: DocGenConfigs = { 'ForwarderWrapperError', 'CoordinatorServerError', 'CoordinatorServerCancellationResponse', + 'EventCallback', + 'IndexedFilterValues', + 'OrderInfo', + 'TransactionOpts', + 'EventCallback ', ], // 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. diff --git a/packages/order-watcher/package.json b/packages/order-watcher/package.json index 7abe6db5a5..e4d6515bba 100644 --- a/packages/order-watcher/package.json +++ b/packages/order-watcher/package.json @@ -64,7 +64,7 @@ "@0x/base-contract": "^5.3.0", "@0x/contract-addresses": "^3.0.2", "@0x/contract-artifacts": "^2.0.3", - "@0x/contract-wrappers": "^10.1.0", + "@0x/contract-wrappers": "10.1.0", "@0x/fill-scenarios": "^3.0.15", "@0x/json-schemas": "^3.1.12", "@0x/order-utils": "^8.2.4", diff --git a/packages/order-watcher/test/expiration_watcher_test.ts b/packages/order-watcher/test/expiration_watcher_test.ts index fb5ea2a27d..885994ce8f 100644 --- a/packages/order-watcher/test/expiration_watcher_test.ts +++ b/packages/order-watcher/test/expiration_watcher_test.ts @@ -1,5 +1,4 @@ -import { tokenUtils } from '@0x/contract-wrappers/lib/test/utils/token_utils'; -import { BlockchainLifecycle, callbackErrorReporter } from '@0x/dev-utils'; +import { BlockchainLifecycle, callbackErrorReporter, tokenUtils } from '@0x/dev-utils'; import { FillScenarios } from '@0x/fill-scenarios'; import { assetDataUtils, orderHashUtils } from '@0x/order-utils'; import { DoneCallback } from '@0x/types'; diff --git a/packages/order-watcher/test/order_watcher_test.ts b/packages/order-watcher/test/order_watcher_test.ts index 22bc666554..6776ee0b4c 100644 --- a/packages/order-watcher/test/order_watcher_test.ts +++ b/packages/order-watcher/test/order_watcher_test.ts @@ -1,7 +1,6 @@ // tslint:disable:no-unnecessary-type-assertion import { ContractAddresses, ContractWrappers } from '@0x/contract-wrappers'; -import { tokenUtils } from '@0x/contract-wrappers/lib/test/utils/token_utils'; -import { BlockchainLifecycle, callbackErrorReporter } from '@0x/dev-utils'; +import { BlockchainLifecycle, callbackErrorReporter, tokenUtils } from '@0x/dev-utils'; import { FillScenarios } from '@0x/fill-scenarios'; import { assetDataUtils, orderHashUtils } from '@0x/order-utils'; import { orderFactory } from '@0x/order-utils/lib/src/order_factory'; diff --git a/packages/order-watcher/test/order_watcher_web_socket_server_test.ts b/packages/order-watcher/test/order_watcher_web_socket_server_test.ts index 36135f65c3..60a3204a98 100644 --- a/packages/order-watcher/test/order_watcher_web_socket_server_test.ts +++ b/packages/order-watcher/test/order_watcher_web_socket_server_test.ts @@ -1,7 +1,6 @@ import { ContractAddresses } from '@0x/contract-addresses'; import { ContractWrappers } from '@0x/contract-wrappers'; -import { tokenUtils } from '@0x/contract-wrappers/lib/test/utils/token_utils'; -import { BlockchainLifecycle } from '@0x/dev-utils'; +import { BlockchainLifecycle, tokenUtils } from '@0x/dev-utils'; import { FillScenarios } from '@0x/fill-scenarios'; import { assetDataUtils, orderHashUtils } from '@0x/order-utils'; import { ExchangeContractErrs, OrderStateInvalid, SignedOrder } from '@0x/types'; diff --git a/yarn.lock b/yarn.lock index 625617025f..ea312eb01f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -687,6 +687,31 @@ version "1.5.1" resolved "https://registry.npmjs.org/@0x/contract-artifacts/-/contract-artifacts-1.5.1.tgz#6fba56a1d3e2d5d897a75fcfa432e49e2ebb17a7" +"@0x/contract-wrappers@10.1.0": + version "10.1.0" + resolved "https://registry.yarnpkg.com/@0x/contract-wrappers/-/contract-wrappers-10.1.0.tgz#7d4d7871a0c55bf77b5f4f253311fc5aea9c18f6" + dependencies: + "@0x/abi-gen-wrappers" "^5.1.0" + "@0x/assert" "^2.1.2" + "@0x/base-contract" "^5.3.0" + "@0x/contract-addresses" "^3.0.2" + "@0x/contract-artifacts" "^2.0.3" + "@0x/json-schemas" "^3.1.12" + "@0x/order-utils" "^8.2.4" + "@0x/types" "^2.4.1" + "@0x/typescript-typings" "^4.2.4" + "@0x/utils" "^4.4.2" + "@0x/web3-wrapper" "^6.0.9" + ethereum-types "^2.1.4" + ethereumjs-abi "0.6.5" + ethereumjs-blockstream "6.0.0" + ethereumjs-util "^5.1.1" + ethers "~4.0.4" + http-status-codes "^1.3.2" + js-sha3 "^0.7.0" + lodash "^4.17.11" + uuid "^3.3.2" + "@0x/contract-wrappers@^9.1.6", "@0x/contract-wrappers@^9.1.7": version "9.1.8" resolved "https://registry.yarnpkg.com/@0x/contract-wrappers/-/contract-wrappers-9.1.8.tgz#5923d35af3e4b442a57d02f74e02620b2d5b1356" @@ -859,8 +884,8 @@ js-tokens "^4.0.0" "@babel/polyfill@^7.0.0": - version "7.4.3" - resolved "https://registry.yarnpkg.com/@babel/polyfill/-/polyfill-7.4.3.tgz#332dc6f57b718017c3a8b37b4eea8aa6eeac1187" + version "7.4.4" + resolved "https://registry.yarnpkg.com/@babel/polyfill/-/polyfill-7.4.4.tgz#78801cf3dbe657844eeabf31c1cae3828051e893" dependencies: core-js "^2.6.5" regenerator-runtime "^0.13.2" @@ -1885,9 +1910,9 @@ version "5.2.7" resolved "https://registry.yarnpkg.com/@types/mocha/-/mocha-5.2.7.tgz#315d570ccb56c53452ff8638738df60726d5b6ea" -"@types/nock@^10.0.1": - version "10.0.1" - resolved "https://registry.yarnpkg.com/@types/nock/-/nock-10.0.1.tgz#ca545bdd0c2559fe76e3cda1ba011a74fb940d45" +"@types/nock@^10.0.3": + version "10.0.3" + resolved "https://registry.yarnpkg.com/@types/nock/-/nock-10.0.3.tgz#dab1d18ffbccfbf2db811dab9584304eeb6e1c4c" dependencies: "@types/node" "*" @@ -2140,7 +2165,6 @@ "@types/toposort@^2.0.1": version "2.0.1" resolved "https://registry.yarnpkg.com/@types/toposort/-/toposort-2.0.1.tgz#d950563ae45147fc28866fe66f3712e9b2a90f88" - integrity sha512-u9mzB6WehAYUw6RJLGO2IbxNpg1ec/ooBfLxjYCAsanETh5M3GVG8dijvwyGzXEdgdWxcIBKnOkeaLnZg+VO8g== "@types/uglify-js@*": version "3.0.4" @@ -2577,7 +2601,7 @@ any-promise@1.3.0, any-promise@^1.0.0, any-promise@^1.3.0: anymatch@^1.3.0: version "1.3.2" - resolved "https://registry.npmjs.org/anymatch/-/anymatch-1.3.2.tgz#553dcb8f91e3c889845dfdba34c77721b90b9d7a" + resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-1.3.2.tgz#553dcb8f91e3c889845dfdba34c77721b90b9d7a" dependencies: micromatch "^2.1.5" normalize-path "^2.0.0" @@ -2597,8 +2621,8 @@ anymatch@^3.0.1: picomatch "^2.0.4" app-root-path@^2.0.1: - version "2.1.0" - resolved "https://registry.yarnpkg.com/app-root-path/-/app-root-path-2.1.0.tgz#98bf6599327ecea199309866e8140368fd2e646a" + version "2.2.1" + resolved "https://registry.yarnpkg.com/app-root-path/-/app-root-path-2.2.1.tgz#d0df4a682ee408273583d43f6f79e9892624bc9a" append-buffer@^1.0.2: version "1.0.2" @@ -2823,11 +2847,7 @@ async-done@^1.2.0, async-done@^1.2.2: process-nextick-args "^2.0.0" stream-exhaust "^1.0.1" -async-each@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/async-each/-/async-each-1.0.1.tgz#19d386a1d9edc6e7c1c85d388aedbcc56d33602d" - -async-each@^1.0.1: +async-each@^1.0.0, async-each@^1.0.1: version "1.0.3" resolved "https://registry.yarnpkg.com/async-each/-/async-each-1.0.3.tgz#b727dbf87d7651602f06f4d4ac387f47d91b0cbf" @@ -3973,7 +3993,7 @@ body-parser@1.18.2, body-parser@^1.16.0, body-parser@^1.17.1: raw-body "2.3.2" type-is "~1.6.15" -body-parser@1.18.3, body-parser@^1.18.3: +body-parser@1.18.3: version "1.18.3" resolved "https://registry.yarnpkg.com/body-parser/-/body-parser-1.18.3.tgz#5b292198ffdd553b3a0f20ded0592b956955c8b4" dependencies: @@ -3988,6 +4008,21 @@ body-parser@1.18.3, body-parser@^1.18.3: raw-body "2.3.3" type-is "~1.6.16" +body-parser@^1.18.3: + version "1.19.0" + resolved "https://registry.yarnpkg.com/body-parser/-/body-parser-1.19.0.tgz#96b2709e57c9c4e09a6fd66a8fd979844f69f08a" + dependencies: + bytes "3.1.0" + content-type "~1.0.4" + debug "2.6.9" + depd "~1.1.2" + http-errors "1.7.2" + iconv-lite "0.4.24" + on-finished "~2.3.0" + qs "6.7.0" + raw-body "2.4.0" + type-is "~1.6.17" + bonjour@^3.5.0: version "3.5.0" resolved "https://registry.yarnpkg.com/bonjour/-/bonjour-3.5.0.tgz#8e890a183d8ee9a2393b3844c691a42bcf7bc9f5" @@ -4322,6 +4357,10 @@ bytes@3.0.0, bytes@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/bytes/-/bytes-3.0.0.tgz#d32815404d689699f85a4ea4fa8755dd13a96048" +bytes@3.1.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/bytes/-/bytes-3.1.0.tgz#f6cf7933a360e0588fa9fde85651cdc7f805d1f6" + bytewise-core@^1.2.2: version "1.2.3" resolved "https://registry.yarnpkg.com/bytewise-core/-/bytewise-core-1.2.3.tgz#3fb410c7e91558eb1ab22a82834577aa6bd61d42" @@ -5447,8 +5486,8 @@ core-js@^2.4.0, core-js@^2.5.0: resolved "https://registry.yarnpkg.com/core-js/-/core-js-2.5.5.tgz#b14dde936c640c0579a6b50cabcc132dd6127e3b" core-js@^2.6.5: - version "2.6.5" - resolved "https://registry.yarnpkg.com/core-js/-/core-js-2.6.5.tgz#44bc8d249e7fb2ff5d00e0341a7ffb94fbf67895" + version "2.6.9" + resolved "https://registry.yarnpkg.com/core-js/-/core-js-2.6.9.tgz#6b4b214620c834152e179323727fc19741b084f2" core-util-is@1.0.2, core-util-is@~1.0.0: version "1.0.2" @@ -7775,8 +7814,8 @@ figgy-pudding@^3.1.0, figgy-pudding@^3.2.1, figgy-pudding@^3.4.1, figgy-pudding@ resolved "https://registry.yarnpkg.com/figgy-pudding/-/figgy-pudding-3.5.1.tgz#862470112901c727a0e495a80744bd5baa1d6790" figlet@^1.1.1: - version "1.2.1" - resolved "https://registry.yarnpkg.com/figlet/-/figlet-1.2.1.tgz#48d35df9d9b10b1b3888302e6e57904a0b00509c" + version "1.2.3" + resolved "https://registry.yarnpkg.com/figlet/-/figlet-1.2.3.tgz#7d25df546f41fc411c2a8b88012d48d55de72129" figures@^1.7.0: version "1.7.0" @@ -8215,20 +8254,20 @@ fs.realpath@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" -fsevents@^1.0.0, fsevents@^1.2.3: - version "1.2.4" - resolved "https://registry.npmjs.org/fsevents/-/fsevents-1.2.4.tgz#f41dcb1af2582af3692da36fc55cbd8e1041c426" - dependencies: - nan "^2.9.2" - node-pre-gyp "^0.10.0" - -fsevents@^1.2.7: +fsevents@^1.0.0, fsevents@^1.2.7: version "1.2.9" resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-1.2.9.tgz#3f5ed66583ccd6f400b5a00db6f7e861363e388f" dependencies: nan "^2.12.1" node-pre-gyp "^0.12.0" +fsevents@^1.2.3: + version "1.2.4" + resolved "https://registry.npmjs.org/fsevents/-/fsevents-1.2.4.tgz#f41dcb1af2582af3692da36fc55cbd8e1041c426" + dependencies: + nan "^2.9.2" + node-pre-gyp "^0.10.0" + fsevents@^2.0.6: version "2.0.7" resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.0.7.tgz#382c9b443c6cbac4c57187cdda23aa3bf1ccfc2a" @@ -8816,27 +8855,10 @@ got@^6.7.1: unzip-response "^2.0.1" url-parse-lax "^1.0.0" -graceful-fs@^3.0.0: - version "3.0.11" - resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-3.0.11.tgz#7613c778a1afea62f25c630a086d7f3acbbdd818" - integrity sha1-dhPHeKGv6mLyXGMKCG1/Osu92Bg= - dependencies: - natives "^1.1.0" - -graceful-fs@^4.0.0, graceful-fs@^4.1.10, graceful-fs@^4.1.11, graceful-fs@^4.1.15, graceful-fs@^4.1.2, graceful-fs@^4.1.6, graceful-fs@^4.1.9: +graceful-fs@4.1.15, graceful-fs@^3.0.0, graceful-fs@^4.0.0, graceful-fs@^4.1.10, graceful-fs@^4.1.11, graceful-fs@^4.1.15, graceful-fs@^4.1.2, graceful-fs@^4.1.6, graceful-fs@^4.1.9, graceful-fs@^4.2.0, graceful-fs@~1.2.0: version "4.1.15" resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.1.15.tgz#ffb703e1066e8a0eeaa4c8b80ba9253eeefbfb00" -graceful-fs@^4.2.0: - version "4.2.0" - resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.0.tgz#8d8fdc73977cb04104721cb53666c1ca64cd328b" - integrity sha512-jpSvDPV4Cq/bgtpndIWbI5hmYxhQGHPC4d4cqBPb4DLniCfhJokdXhwhaDuLBGLQdvvRum/UiX6ECVIPvDXqdg== - -graceful-fs@~1.2.0: - version "1.2.3" - resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-1.2.3.tgz#15a4806a57547cb2d2dbf27f42e89a8c3451b364" - integrity sha1-FaSAaldUfLLS2/J/QuiajDRRs2Q= - "graceful-readlink@>= 1.0.0": version "1.0.1" resolved "https://registry.yarnpkg.com/graceful-readlink/-/graceful-readlink-1.0.1.tgz#4cafad76bc62f02fa039b2f94e9a3dd3a391a725" @@ -9155,10 +9177,14 @@ highlight.js@^9.0.0, highlight.js@^9.11.0, highlight.js@~9.12.0: version "9.12.0" resolved "https://registry.yarnpkg.com/highlight.js/-/highlight.js-9.12.0.tgz#e6d9dbe57cbefe60751f02af336195870c90c01e" -highlight.js@^9.13.1, highlight.js@^9.6.0: +highlight.js@^9.13.1: version "9.13.1" resolved "https://registry.yarnpkg.com/highlight.js/-/highlight.js-9.13.1.tgz#054586d53a6863311168488a0f58d6c505ce641e" +highlight.js@^9.6.0: + version "9.15.9" + resolved "https://registry.yarnpkg.com/highlight.js/-/highlight.js-9.15.9.tgz#865257da1dbb4a58c4552d46c4b3854f77f0e6d5" + highlightjs-solidity@^1.0.5: version "1.0.6" resolved "https://registry.yarnpkg.com/highlightjs-solidity/-/highlightjs-solidity-1.0.6.tgz#59394d8a2c57013580d5bfbb62f7df98386ae7ac" @@ -9342,6 +9368,16 @@ http-errors@1.6.3, http-errors@~1.6.2, http-errors@~1.6.3: setprototypeof "1.1.0" statuses ">= 1.4.0 < 2" +http-errors@1.7.2: + version "1.7.2" + resolved "https://registry.yarnpkg.com/http-errors/-/http-errors-1.7.2.tgz#4f5029cf13239f31036e5b2e55292bcfbcc85c8f" + dependencies: + depd "~1.1.2" + inherits "2.0.3" + setprototypeof "1.1.1" + statuses ">= 1.5.0 < 2" + toidentifier "1.0.0" + http-https@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/http-https/-/http-https-1.0.0.tgz#2f908dd5f1db4068c058cd6e6d4ce392c913389b" @@ -10652,7 +10688,7 @@ js-tokens@^3.0.0, js-tokens@^3.0.2: version "4.0.0" resolved "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499" -js-yaml@3.13.1, js-yaml@^3.13.1: +js-yaml@3.13.1, js-yaml@^3.11.0, js-yaml@^3.13.1: version "3.13.1" resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.13.1.tgz#aff151b30bfdfa8e49e05da22e7415e9dfa37847" dependencies: @@ -10666,13 +10702,6 @@ js-yaml@3.x, js-yaml@^3.4.2, js-yaml@^3.6.1, js-yaml@^3.7.0: argparse "^1.0.7" esprima "^4.0.0" -js-yaml@^3.11.0: - version "3.12.1" - resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.12.1.tgz#295c8632a18a23e054cf5c9d3cecafe678167600" - dependencies: - argparse "^1.0.7" - esprima "^4.0.0" - js-yaml@^3.12.0, js-yaml@^3.9.0: version "3.12.0" resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.12.0.tgz#eaed656ec8344f10f527c6bfa1b6e2244de167d1" @@ -12111,6 +12140,10 @@ miller-rabin@^4.0.0: bn.js "^4.0.0" brorand "^1.0.1" +mime-db@1.40.0: + version "1.40.0" + resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.40.0.tgz#a65057e998db090f732a68f6c276d387d4126c32" + "mime-db@>= 1.33.0 < 2", mime-db@~1.33.0: version "1.33.0" resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.33.0.tgz#a3492050a5cb9b63450541e39d9788d2272783db" @@ -12131,6 +12164,12 @@ mime-types@~2.1.19: dependencies: mime-db "~1.35.0" +mime-types@~2.1.24: + version "2.1.24" + resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.24.tgz#b6f8d0b3e951efb77dedeca194cff6d16f676f81" + dependencies: + mime-db "1.40.0" + mime@1.4.1: version "1.4.1" resolved "https://registry.yarnpkg.com/mime/-/mime-1.4.1.tgz#121f9ebc49e3766f311a76e1fa1c8003c4b03aa6" @@ -12418,7 +12457,7 @@ mz@^2.4.0, mz@^2.6.0: object-assign "^4.0.1" thenify-all "^1.0.0" -nan@2.10.0, nan@^2.0.8, nan@^2.2.1, nan@^2.3.3, nan@^2.6.2, nan@^2.9.2, nan@~2.10.0: +nan@2.10.0, nan@^2.0.8, nan@^2.2.1, nan@^2.3.3, nan@^2.6.2, nan@^2.9.2: version "2.10.0" resolved "https://registry.yarnpkg.com/nan/-/nan-2.10.0.tgz#96d0cd610ebd58d4b4de9cc0c6828cda99c7548f" @@ -12451,11 +12490,6 @@ nanomatch@^1.2.9: snapdragon "^0.8.1" to-regex "^3.0.1" -natives@^1.1.0: - version "1.1.6" - resolved "https://registry.yarnpkg.com/natives/-/natives-1.1.6.tgz#a603b4a498ab77173612b9ea1acdec4d980f00bb" - integrity sha512-6+TDFewD4yxY14ptjKaS63GVdtKiES1pTPyxn9Jb0rBqPMZ7VcCiooEhPNsr+mqHtMGxa/5c/HhcC4uPEUw/nA== - natural-compare@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7" @@ -12683,7 +12717,7 @@ node-notifier@^5.2.1: shellwords "^0.1.1" which "^1.3.0" -node-pre-gyp@^0.10.0, node-pre-gyp@^0.10.3: +node-pre-gyp@^0.10.0: version "0.10.3" resolved "https://registry.npmjs.org/node-pre-gyp/-/node-pre-gyp-0.10.3.tgz#3070040716afdc778747b61b6887bf78880b80fc" dependencies: @@ -12698,6 +12732,21 @@ node-pre-gyp@^0.10.0, node-pre-gyp@^0.10.3: semver "^5.3.0" tar "^4" +node-pre-gyp@^0.11.0: + version "0.11.0" + resolved "https://registry.yarnpkg.com/node-pre-gyp/-/node-pre-gyp-0.11.0.tgz#db1f33215272f692cd38f03238e3e9b47c5dd054" + dependencies: + detect-libc "^1.0.2" + mkdirp "^0.5.1" + needle "^2.2.1" + nopt "^4.0.1" + npm-packlist "^1.1.6" + npmlog "^4.0.2" + rc "^1.2.7" + rimraf "^2.6.1" + semver "^5.3.0" + tar "^4" + node-pre-gyp@^0.12.0: version "0.12.0" resolved "https://registry.yarnpkg.com/node-pre-gyp/-/node-pre-gyp-0.12.0.tgz#39ba4bb1439da030295f899e3b520b7785766149" @@ -14546,7 +14595,7 @@ qs@6.5.2, qs@~6.5.2: version "6.5.2" resolved "https://registry.yarnpkg.com/qs/-/qs-6.5.2.tgz#cb3ae806e8740444584ef154ce8ee98d403f3e36" -qs@^6.5.1: +qs@6.7.0, qs@^6.5.1: version "6.7.0" resolved "https://registry.yarnpkg.com/qs/-/qs-6.7.0.tgz#41dc1a015e3d581f1621776be31afb2876a9b1bc" @@ -14679,6 +14728,15 @@ raw-body@2.3.3: iconv-lite "0.4.23" unpipe "1.0.0" +raw-body@2.4.0: + version "2.4.0" + resolved "https://registry.yarnpkg.com/raw-body/-/raw-body-2.4.0.tgz#a1ce6fb9c9bc356ca52e89256ab59059e13d0332" + dependencies: + bytes "3.1.0" + http-errors "1.7.2" + iconv-lite "0.4.24" + unpipe "1.0.0" + raw-loader@^0.5.1: version "0.5.1" resolved "https://registry.yarnpkg.com/raw-loader/-/raw-loader-0.5.1.tgz#0c3d0beaed8a01c966d9787bf778281252a979aa" @@ -14834,8 +14892,6 @@ react-highlight@0xproject/react-highlight#react-peer-deps: dependencies: highlight.js "^9.11.0" highlightjs-solidity "^1.0.5" - react "^16.5.2" - react-dom "^16.5.2" react-hot-loader@^4.3.3: version "4.3.4" @@ -15218,16 +15274,7 @@ readdir-scoped-modules@^1.0.0: graceful-fs "^4.1.2" once "^1.3.0" -readdirp@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-2.1.0.tgz#4ed0ad060df3073300c48440373f72d1cc642d78" - dependencies: - graceful-fs "^4.1.2" - minimatch "^3.0.2" - readable-stream "^2.0.2" - set-immediate-shim "^1.0.1" - -readdirp@^2.2.1: +readdirp@^2.0.0, readdirp@^2.2.1: version "2.2.1" resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-2.2.1.tgz#0e87622a3325aa33e892285caf8b4e846529a525" dependencies: @@ -15356,14 +15403,10 @@ redux@^3.6.0: loose-envify "^1.1.0" symbol-observable "^1.0.3" -reflect-metadata@^0.1.10: +reflect-metadata@^0.1.10, reflect-metadata@^0.1.12: version "0.1.13" resolved "https://registry.yarnpkg.com/reflect-metadata/-/reflect-metadata-0.1.13.tgz#67ae3ca57c972a2aa1642b10fe363fe32d49dc08" -reflect-metadata@^0.1.12: - version "0.1.12" - resolved "https://registry.yarnpkg.com/reflect-metadata/-/reflect-metadata-0.1.12.tgz#311bf0c6b63cd782f228a81abe146a2bfa9c56f2" - refractor@^2.4.1: version "2.6.2" resolved "https://registry.yarnpkg.com/refractor/-/refractor-2.6.2.tgz#8e0877ab8864165275aafeea5d9c8eebe871552f" @@ -16270,6 +16313,10 @@ setprototypeof@1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/setprototypeof/-/setprototypeof-1.1.0.tgz#d0bd85536887b6fe7c0d818cb962d9d91c54e656" +setprototypeof@1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/setprototypeof/-/setprototypeof-1.1.1.tgz#7e95acb24aa92f5885e0abef5ba131330d4ae683" + sha.js@^2.4.0, sha.js@^2.4.8: version "2.4.11" resolved "https://registry.yarnpkg.com/sha.js/-/sha.js-2.4.11.tgz#37a5cf0b81ecbc6943de109ba2960d1b26584ae7" @@ -16766,11 +16813,11 @@ sprintf-js@~1.0.2: resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" sqlite3@^4.0.2: - version "4.0.4" - resolved "https://registry.yarnpkg.com/sqlite3/-/sqlite3-4.0.4.tgz#1f75e3ededad6e26f7dd819929460ce44a49dfcd" + version "4.0.9" + resolved "https://registry.yarnpkg.com/sqlite3/-/sqlite3-4.0.9.tgz#cff74550fa5a1159956815400bdef69245557640" dependencies: - nan "~2.10.0" - node-pre-gyp "^0.10.3" + nan "^2.12.1" + node-pre-gyp "^0.11.0" request "^2.87.0" sshpk@^1.7.0: @@ -16822,7 +16869,7 @@ static-extend@^0.1.1: define-property "^0.2.5" object-copy "^0.1.0" -"statuses@>= 1.3.1 < 2", "statuses@>= 1.4.0 < 2": +"statuses@>= 1.3.1 < 2", "statuses@>= 1.4.0 < 2", "statuses@>= 1.5.0 < 2": version "1.5.0" resolved "https://registry.yarnpkg.com/statuses/-/statuses-1.5.0.tgz#161c7dac177659fd9811f43771fa99381478628c" @@ -17620,6 +17667,10 @@ toggle-selection@^1.0.3: version "1.0.6" resolved "https://registry.yarnpkg.com/toggle-selection/-/toggle-selection-1.0.6.tgz#6e45b1263f2017fa0acc7d89d78b15b8bf77da32" +toidentifier@1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/toidentifier/-/toidentifier-1.0.0.tgz#7e1be3470f1e77948bc43d94a3c8f4d7752ba553" + toposort@^1.0.0: version "1.0.7" resolved "https://registry.yarnpkg.com/toposort/-/toposort-1.0.7.tgz#2e68442d9f64ec720b8cc89e6443ac6caa950029" @@ -17627,7 +17678,6 @@ toposort@^1.0.0: toposort@^2.0.2: version "2.0.2" resolved "https://registry.yarnpkg.com/toposort/-/toposort-2.0.2.tgz#ae21768175d1559d48bef35420b2f4962f09c330" - integrity sha1-riF2gXXRVZ1IvvNUILL0li8JwzA= touch@^3.1.0: version "3.1.0" @@ -17859,6 +17909,13 @@ type-is@~1.6.15, type-is@~1.6.16: media-typer "0.3.0" mime-types "~2.1.18" +type-is@~1.6.17: + version "1.6.18" + resolved "https://registry.yarnpkg.com/type-is/-/type-is-1.6.18.tgz#4e552cd05df09467dcbc4ef739de89f2cf37c131" + dependencies: + media-typer "0.3.0" + mime-types "~2.1.24" + typed-styles@^0.0.5: version "0.0.5" resolved "https://registry.npmjs.org/typed-styles/-/typed-styles-0.0.5.tgz#a60df245d482a9b1adf9c06c078d0f06085ed1cf" @@ -19129,7 +19186,7 @@ websocket@1.0.26: typedarray-to-buffer "^3.1.2" yaeti "^0.0.6" -websocket@1.0.29: +websocket@1.0.29, websocket@^1.0.25: version "1.0.29" resolved "https://registry.yarnpkg.com/websocket/-/websocket-1.0.29.tgz#3f83e49d3279657c58b02a22d90749c806101b98" dependencies: @@ -19139,7 +19196,7 @@ websocket@1.0.29: typedarray-to-buffer "^3.1.5" yaeti "^0.0.6" -websocket@^1.0.25, websocket@^1.0.26: +websocket@^1.0.26: version "1.0.28" resolved "https://registry.yarnpkg.com/websocket/-/websocket-1.0.28.tgz#9e5f6fdc8a3fe01d4422647ef93abdd8d45a78d3" dependencies: